newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
//! **One table of named roles, so a colour is chosen once and named
//! everywhere.**
//!
//! Before this, colour in the TUI was thirty-odd literals spread across nine
//! files, and the census reads exactly like the spinner census in CLAUDE.md
//! that justified the `tty` arbiter:
//!
//! - **`DarkGray` twenty times and `DarkGrey` thirteen** — two spellings of one
//!   intent, which no amount of grepping reconciles into a single decision.
//! - **`Color::Rgb { r: 255, g: 165, b: 90 }` written out in `palette.rs` beside
//!   `ACTIVE_INPUT_CT`**, which is that exact colour. The same duplication was
//!   fixed in `header_line` (#2019) and simply reappeared elsewhere, because
//!   nothing named the colour.
//! - Nine files each deciding, privately, what "dim" and "emphasis" mean.
//!
//! A theme fixes that by making the knowledge DATA: a role has a name, a role
//! has one colour, and a surface asks for the role. That is the three Cs
//! applied to presentation — the language-pack model CLAUDE.md names as
//! canonical, pointed at the palette.
//!
//! # What a role is, and what it is not
//!
//! A role is a MEANING, not a place. `Dim` is "subordinate to what is beside
//! it", not "the colour of the provenance column" — so a new surface with
//! subordinate text asks for `Dim` and is automatically consistent with every
//! other one. A role named after a widget would just be a literal wearing a
//! longer name.
//!
//! # The default theme changes nothing
//!
//! [`Theme::builtin`] reproduces the current colours EXACTLY, site for site,
//! and `the_builtin_theme_preserves_every_colour_in_use` pins that. A theme
//! seam whose arrival re-colours the product is two changes wearing one commit
//! message, and the second one is invisible in review.

use crossterm::style::Color;

use super::ACTIVE_INPUT_CT;

/// What a colour MEANS on this surface.
///
/// Deliberately small. Every role here is one a surface actually asked for —
/// derived from the colour census rather than invented, so there is no role
/// that exists only in this file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Role {
    /// The live input line, and anything that currently owns the keyboard.
    /// The one colour an operator reads as "here".
    Accent,
    /// Ordinary body text.
    Text,
    /// Subordinate to what it sits beside: hints, provenance, timestamps, a
    /// receded prompt. The role that was thirty-three literals in two
    /// spellings.
    Dim,
    /// Between [`Self::Text`] and [`Self::Dim`] — present, but not the point.
    Muted,
    /// Draws the eye without claiming the keyboard: a mode word, an open
    /// command line.
    Emphasis,
    /// Added source text and its semantic background.
    Added,
    AddedBackground,
    /// Removed source text and its semantic background.
    Removed,
    RemovedBackground,

    /// Model reasoning and its closing label, independent of the final reply.
    Thinking,
    /// The model's own words mid-turn: the sentence it sends beside a tool
    /// batch, saying what it is about to do. Distinct from [`Self::AgentText`]
    /// (the reply) and [`Self::Thinking`] (reasoning), so intent reads apart
    /// from answer at a glance.
    Narration,

    /// The slab a `!` or `:` command is rendered on.
    CommandBackground,
    /// The same slab while a modal owns the keyboard.
    CommandBackgroundInactive,
    /// The `!` host-command marker.
    CommandBang,
    /// The `:` ex-command marker.
    CommandEx,

    /// Context budget: comfortable.
    GaugeOk,
    /// Context budget: worth noticing.
    GaugeWarn,
    /// Context budget: act now.
    GaugeCritical,

    /// A selected row's label.
    SelectedLabel,
    /// A selected row's value.
    SelectedValue,
    /// Model currently used by the session, independent of the keyboard cursor.
    ActiveModel,
    /// A model resident in server memory.
    LoadedModel,
    /// Succeeded, allowed, present.
    Ok,
    /// A persona, a name, an identity.
    Identity,

    /// The frame around a dialog that owns the keyboard.
    ///
    /// Its own role, and accent-coloured by default, because a modal IS the
    /// keyboard being somewhere: the same claim [`Self::Accent`] makes for the
    /// input line. The panel border shipped with no `border_style` at all, so
    /// it drew in whatever the terminal last set — which is how a dialog that
    /// has taken the keyboard ends up looking like ordinary output.
    ModalBorder,
    /// The dialog's name, in its frame.
    HumanText,
    AgentText,
    MarkdownHeading,
    InlineCode,
    MarkdownStrong,
    MarkdownItalic,
    Spill,
    MarkdownLink,
    MarkdownStrike,
    ModalTitle,
}

/// A complete assignment of colours to roles.
///
/// Total by construction: [`Self::color`] is a `match`, so a role added to the
/// enum fails to compile until every theme answers for it. A theme with a
/// missing role would silently fall back to whatever the terminal last set,
/// which is the class of bug that makes a colour scheme look "sometimes
/// broken".
#[derive(Debug, Clone, PartialEq)]
pub struct Theme {
    pub name: String,
    attributes: std::collections::BTreeMap<Role, crossterm::style::Attributes>,
    accent: Color,
    text: Color,
    dim: Color,
    muted: Color,
    emphasis: Color,
    added: Color,
    added_background: Color,
    removed: Color,
    removed_background: Color,
    thinking: Color,
    narration: Color,
    command_background: Color,
    command_background_inactive: Color,
    command_bang: Color,
    command_ex: Color,
    gauge_ok: Color,
    gauge_warn: Color,
    gauge_critical: Color,
    selected_label: Color,
    selected_value: Color,
    active_model: Color,
    loaded_model: Color,
    ok: Color,
    identity: Color,
    modal_border: Color,
    human_text: Color,
    agent_text: Color,
    markdown_heading: Color,
    inline_code: Color,
    markdown_strong: Color,
    markdown_italic: Color,
    spill: Color,
    markdown_link: Color,
    markdown_strike: Color,
    modal_title: Color,
}

impl Theme {
    /// The colours the TUI uses today, named.
    ///
    /// Existing roles preserve the colors of their original surfaces. Added
    /// and removed source text introduce their own foreground/background
    /// roles, so a file review can be tuned without recoloring other output.
    pub fn builtin() -> Self {
        Self {
            human_text: Color::Cyan,
            agent_text: Color::Grey,
            markdown_heading: Color::Blue,
            inline_code: Color::White,
            markdown_strong: Color::White,
            markdown_italic: Color::Grey,
            spill: Color::DarkGrey,
            markdown_link: Color::Grey,
            markdown_strike: Color::Grey,
            name: "newt".to_string(),
            // THE constant, not a copy of its value. This table used to
            // re-write `Rgb(255, 165, 90)` — the same duplication its own
            // module doc complains about, merely relocated. Living in the
            // crate that DEFINES `ACTIVE_INPUT_CT` lets it name the thing.
            attributes: Default::default(),
            accent: ACTIVE_INPUT_CT,
            text: Color::White,
            // `DarkGray` (20 sites) and `DarkGrey` (13) were the same request.
            dim: Color::DarkGrey,
            muted: Color::Grey,
            emphasis: Color::Yellow,
            added: Color::Green,
            added_background: Color::Rgb {
                r: 24,
                g: 56,
                b: 37,
            },
            removed: Color::Red,
            removed_background: Color::Rgb {
                r: 65,
                g: 29,
                b: 32,
            },
            thinking: Color::DarkGrey,
            narration: Color::Magenta,
            command_background: Color::Rgb {
                r: 82,
                g: 82,
                b: 82,
            },
            command_background_inactive: Color::Rgb {
                r: 45,
                g: 45,
                b: 45,
            },
            command_bang: Color::Magenta,
            command_ex: Color::Yellow,
            gauge_ok: Color::DarkGreen,
            gauge_warn: Color::Rgb {
                r: 200,
                g: 140,
                b: 0,
            },
            gauge_critical: Color::DarkRed,
            selected_label: Color::DarkCyan,
            selected_value: Color::DarkYellow,
            active_model: Color::Cyan,
            loaded_model: Color::DarkMagenta,
            ok: Color::DarkGreen,
            identity: Color::DarkMagenta,
            // A modal owns the keyboard, so it wears the colour that means so.
            modal_border: ACTIVE_INPUT_CT,
            modal_title: Color::Yellow,
        }
    }

    /// The colour for a role. Total: adding a `Role` breaks this until every
    /// theme answers.
    pub fn color(&self, role: Role) -> Color {
        match role {
            Role::Accent => self.accent,
            Role::Text => self.text,
            Role::Dim => self.dim,
            Role::Muted => self.muted,
            Role::Emphasis => self.emphasis,
            Role::Added => self.added,
            Role::AddedBackground => self.added_background,
            Role::Removed => self.removed,
            Role::RemovedBackground => self.removed_background,
            Role::Thinking => self.thinking,
            Role::Narration => self.narration,
            Role::CommandBackground => self.command_background,
            Role::CommandBackgroundInactive => self.command_background_inactive,
            Role::CommandBang => self.command_bang,
            Role::CommandEx => self.command_ex,
            Role::GaugeOk => self.gauge_ok,
            Role::GaugeWarn => self.gauge_warn,
            Role::GaugeCritical => self.gauge_critical,
            Role::SelectedLabel => self.selected_label,
            Role::SelectedValue => self.selected_value,
            Role::ActiveModel => self.active_model,
            Role::LoadedModel => self.loaded_model,
            Role::Ok => self.ok,
            Role::Identity => self.identity,
            Role::ModalBorder => self.modal_border,
            Role::HumanText => self.human_text,
            Role::AgentText => self.agent_text,
            Role::MarkdownHeading => self.markdown_heading,
            Role::InlineCode => self.inline_code,
            Role::MarkdownStrong => self.markdown_strong,
            Role::MarkdownItalic => self.markdown_italic,
            Role::Spill => self.spill,
            Role::MarkdownLink => self.markdown_link,
            Role::MarkdownStrike => self.markdown_strike,
            Role::ModalTitle => self.modal_title,
        }
    }

    /// Complete terminal style for a semantic role.
    pub fn style(&self, role: Role) -> crossterm::style::ContentStyle {
        use crossterm::style::{Attribute, Attributes, ContentStyle};
        let attributes = self.attributes.get(&role).copied().unwrap_or_else(|| {
            let mut a = Attributes::default();
            match role {
                Role::Ok
                | Role::Identity
                | Role::MarkdownHeading
                | Role::MarkdownStrong
                | Role::InlineCode
                | Role::SelectedLabel
                | Role::SelectedValue
                | Role::ModalTitle => a.set(Attribute::Bold),
                Role::MarkdownLink => a.set(Attribute::Underlined),
                Role::MarkdownStrike => a.set(Attribute::CrossedOut),
                Role::MarkdownItalic => a.set(Attribute::Italic),
                _ => {}
            }
            a
        });
        ContentStyle {
            foreground_color: Some(self.color(role)),
            attributes,
            ..ContentStyle::default()
        }
    }

    /// ANSI prefix for a role; callers reset at their row boundary.
    pub fn ansi(&self, role: Role) -> String {
        ansi_style(self.style(role))
    }

    /// Change color and attributes together; explicit empty attributes disable defaults.
    pub fn set_style(&mut self, role: Role, style: crossterm::style::ContentStyle) {
        if let Some(color) = style.foreground_color {
            *self = self.clone().overlaid(&self.name.clone(), &[(role, color)]);
        }
        self.attributes.insert(role, style.attributes);
    }

    /// Overlay a partial assignment read from a theme file.
    ///
    /// Partial ON PURPOSE, and it is the whole ergonomic argument: an operator
    /// who wants a brighter accent writes one line, not a file of all our
    /// colours they must keep in step with ours. Everything unstated keeps the
    /// built-in value, so a theme file cannot go stale by omission when a role
    /// is added — the same droppable-override shape the language packs use.
    pub fn overlaid(mut self, name: &str, overrides: &[(Role, Color)]) -> Self {
        self.name = name.to_string();
        for (role, color) in overrides {
            match role {
                Role::Accent => self.accent = *color,
                Role::Text => self.text = *color,
                Role::Dim => self.dim = *color,
                Role::Muted => self.muted = *color,
                Role::Emphasis => self.emphasis = *color,
                Role::Added => self.added = *color,
                Role::AddedBackground => self.added_background = *color,
                Role::Removed => self.removed = *color,
                Role::RemovedBackground => self.removed_background = *color,
                Role::Thinking => self.thinking = *color,
                Role::Narration => self.narration = *color,
                Role::CommandBackground => self.command_background = *color,
                Role::CommandBackgroundInactive => self.command_background_inactive = *color,
                Role::CommandBang => self.command_bang = *color,
                Role::CommandEx => self.command_ex = *color,
                Role::GaugeOk => self.gauge_ok = *color,
                Role::GaugeWarn => self.gauge_warn = *color,
                Role::GaugeCritical => self.gauge_critical = *color,
                Role::SelectedLabel => self.selected_label = *color,
                Role::SelectedValue => self.selected_value = *color,
                Role::ActiveModel => self.active_model = *color,
                Role::LoadedModel => self.loaded_model = *color,
                Role::Ok => self.ok = *color,
                Role::Identity => self.identity = *color,
                Role::ModalBorder => self.modal_border = *color,
                Role::HumanText => self.human_text = *color,
                Role::AgentText => self.agent_text = *color,
                Role::MarkdownHeading => self.markdown_heading = *color,
                Role::InlineCode => self.inline_code = *color,
                Role::MarkdownStrong => self.markdown_strong = *color,
                Role::MarkdownItalic => self.markdown_italic = *color,
                Role::Spill => self.spill = *color,
                Role::MarkdownLink => self.markdown_link = *color,
                Role::MarkdownStrike => self.markdown_strike = *color,
                Role::ModalTitle => self.modal_title = *color,
            }
        }
        self
    }
}

/// Encode a foreground without consulting process-global NO_COLOR. The calling
/// renderer owns its explicit color switch, including headless previews/tests.
pub fn ansi_color(color: Color) -> String {
    let index = match color {
        Color::Reset => return "\x1b[39m".into(),
        Color::Rgb { r, g, b } => return format!("\x1b[38;2;{r};{g};{b}m"),
        Color::AnsiValue(n) => return format!("\x1b[38;5;{n}m"),
        Color::Black => 0,
        Color::DarkRed => 1,
        Color::DarkGreen => 2,
        Color::DarkYellow => 3,
        Color::DarkBlue => 4,
        Color::DarkMagenta => 5,
        Color::DarkCyan => 6,
        Color::Grey => 7,
        Color::DarkGrey => 8,
        Color::Red => 9,
        Color::Green => 10,
        Color::Yellow => 11,
        Color::Blue => 12,
        Color::Magenta => 13,
        Color::Cyan => 14,
        Color::White => 15,
    };
    format!("\x1b[38;5;{index}m")
}

pub fn ansi_style(style: crossterm::style::ContentStyle) -> String {
    use crossterm::style::{Attribute, SetAttribute};
    let mut text = String::new();
    for attr in [
        Attribute::Bold,
        Attribute::Dim,
        Attribute::Italic,
        Attribute::Underlined,
        Attribute::Reverse,
        Attribute::CrossedOut,
    ] {
        if style.attributes.has(attr) {
            text.push_str(&format!("{}", SetAttribute(attr)));
        }
    }
    if let Some(color) = style.foreground_color {
        text.push_str(&ansi_color(color));
    }
    text
}

/// The role vocabulary as it appears in a theme file.
///
/// Kebab-case, and the same strings the `/theme` command will print — an
/// operator who reads a role in the UI can put that exact word in the file.
pub fn role_from_name(name: &str) -> Option<Role> {
    Some(match name.trim().to_ascii_lowercase().as_str() {
        "accent" => Role::Accent,
        "text" => Role::Text,
        "dim" => Role::Dim,
        "muted" => Role::Muted,
        "emphasis" => Role::Emphasis,
        "added" => Role::Added,
        "added-background" => Role::AddedBackground,
        "removed" => Role::Removed,
        "removed-background" => Role::RemovedBackground,
        "thinking" => Role::Thinking,
        "narration" => Role::Narration,
        "command-background" => Role::CommandBackground,
        "command-background-inactive" => Role::CommandBackgroundInactive,
        "command-bang" => Role::CommandBang,
        "command-ex" => Role::CommandEx,
        "gauge-ok" => Role::GaugeOk,
        "gauge-warn" => Role::GaugeWarn,
        "gauge-critical" => Role::GaugeCritical,
        "selected-label" => Role::SelectedLabel,
        "selected-value" => Role::SelectedValue,
        "active-model" => Role::ActiveModel,
        "loaded-model" => Role::LoadedModel,
        "ok" => Role::Ok,
        "identity" => Role::Identity,
        "modal-border" => Role::ModalBorder,
        "human-text" => Role::HumanText,
        "agent-text" => Role::AgentText,
        "markdown-heading" => Role::MarkdownHeading,
        "inline-code" => Role::InlineCode,
        "markdown-strong" => Role::MarkdownStrong,
        "markdown-italic" => Role::MarkdownItalic,
        "spill" => Role::Spill,
        "markdown-link" => Role::MarkdownLink,
        "markdown-strike" => Role::MarkdownStrike,
        "modal-title" => Role::ModalTitle,
        _ => return None,
    })
}

/// Every role, for `/theme` and for the totality test.
pub const ALL_ROLES: &[Role] = &[
    Role::Accent,
    Role::Text,
    Role::Dim,
    Role::Muted,
    Role::Emphasis,
    Role::Added,
    Role::AddedBackground,
    Role::Removed,
    Role::RemovedBackground,
    Role::Thinking,
    Role::Narration,
    Role::CommandBackground,
    Role::CommandBackgroundInactive,
    Role::CommandBang,
    Role::CommandEx,
    Role::GaugeOk,
    Role::GaugeWarn,
    Role::GaugeCritical,
    Role::SelectedLabel,
    Role::SelectedValue,
    Role::ActiveModel,
    Role::LoadedModel,
    Role::Ok,
    Role::Identity,
    Role::ModalBorder,
    Role::HumanText,
    Role::AgentText,
    Role::MarkdownHeading,
    Role::InlineCode,
    Role::MarkdownStrong,
    Role::MarkdownItalic,
    Role::Spill,
    Role::MarkdownLink,
    Role::MarkdownStrike,
    Role::ModalTitle,
];

/// The name a role answers to in a theme file.
pub fn role_name(role: Role) -> &'static str {
    match role {
        Role::Accent => "accent",
        Role::Text => "text",
        Role::Dim => "dim",
        Role::Muted => "muted",
        Role::Emphasis => "emphasis",
        Role::Added => "added",
        Role::AddedBackground => "added-background",
        Role::Removed => "removed",
        Role::RemovedBackground => "removed-background",
        Role::Thinking => "thinking",
        Role::Narration => "narration",
        Role::CommandBackground => "command-background",
        Role::CommandBackgroundInactive => "command-background-inactive",
        Role::CommandBang => "command-bang",
        Role::CommandEx => "command-ex",
        Role::GaugeOk => "gauge-ok",
        Role::GaugeWarn => "gauge-warn",
        Role::GaugeCritical => "gauge-critical",
        Role::SelectedLabel => "selected-label",
        Role::SelectedValue => "selected-value",
        Role::ActiveModel => "active-model",
        Role::LoadedModel => "loaded-model",
        Role::Ok => "ok",
        Role::Identity => "identity",
        Role::ModalBorder => "modal-border",
        Role::HumanText => "human-text",
        Role::AgentText => "agent-text",
        Role::MarkdownHeading => "markdown-heading",
        Role::InlineCode => "inline-code",
        Role::MarkdownStrong => "markdown-strong",
        Role::MarkdownItalic => "markdown-italic",
        Role::Spill => "spill",
        Role::MarkdownLink => "markdown-link",
        Role::MarkdownStrike => "markdown-strike",
        Role::ModalTitle => "modal-title",
    }
}

/// Parse a colour as a theme file writes one.
///
/// Three spellings, because three are what people actually have to hand: a hex
/// triplet from a palette they like, an ANSI index from a terminal scheme, or
/// one of the sixteen names. A fourth would be a fourth thing to get wrong.
///
/// # Errors
///
/// The value is not a colour this vocabulary can express.
pub fn parse_color(value: &str) -> Result<Color, String> {
    let value = value.trim();
    if let Some(hex) = value.strip_prefix('#') {
        if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Err(format!("`{value}` is not #rrggbb"));
        }
        let byte = |at: usize| u8::from_str_radix(&hex[at..at + 2], 16).unwrap_or(0);
        return Ok(Color::Rgb {
            r: byte(0),
            g: byte(2),
            b: byte(4),
        });
    }
    if let Ok(index) = value.parse::<u8>() {
        return Ok(Color::AnsiValue(index));
    }
    Ok(match value.to_ascii_lowercase().as_str() {
        "default" => Color::Reset,
        "black" => Color::Black,
        "red" => Color::DarkRed,
        "green" => Color::DarkGreen,
        "yellow" => Color::DarkYellow,
        "blue" => Color::DarkBlue,
        "magenta" => Color::DarkMagenta,
        "cyan" => Color::DarkCyan,
        "gray" | "grey" => Color::Grey,
        // One spelling in, both accepted — the DarkGray/DarkGrey split is
        // exactly what this file exists to stop, and it must not be recreated
        // in the config vocabulary.
        "dark-gray" | "dark-grey" => Color::DarkGrey,
        "light-red" => Color::Red,
        "light-green" => Color::Green,
        "light-yellow" => Color::Yellow,
        "light-blue" => Color::Blue,
        "light-magenta" => Color::Magenta,
        "light-cyan" => Color::Cyan,
        "white" => Color::White,
        other => {
            return Err(format!(
                "`{other}` is not a colour name, an ANSI index (0-255), or #rrggbb"
            ))
        }
    })
}

/// The theme in force, from `NEWT_THEME` — `role=colour` pairs, comma
/// separated: `NEWT_THEME='dim=gray,accent=#00d7ff'`.
///
/// An env vocabulary rather than a file, for now, and deliberately: it is the
/// smallest thing that makes a role TUNABLE, it needs no path resolution or
/// precedence story, and it is what an operator reaches for while deciding
/// what they actually want. A `[tui] theme` file follows once the roles have
/// stopped moving — the same order `brand.rs` took, whose env override shipped
/// before anything richer.
///
/// **A bad pair is reported, not obeyed and not fatal.** An unreadable theme
/// that silently half-applies looks like a rendering bug everywhere except the
/// one place that would explain it.
pub fn from_env(raw: Option<&str>) -> (Theme, Vec<String>) {
    overlay_env(Theme::builtin(), raw)
}

/// The `NEWT_THEME` pairs applied over `base`; one parser for both the
/// built-in default and a persisted preference, so the two cannot drift.
fn overlay_env(base: Theme, raw: Option<&str>) -> (Theme, Vec<String>) {
    let Some(raw) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
        return (base, Vec::new());
    };
    let (mut overrides, mut complaints) = (Vec::new(), Vec::new());
    for pair in raw.split(',').map(str::trim).filter(|p| !p.is_empty()) {
        let Some((name, value)) = pair.split_once('=') else {
            complaints.push(format!("`{pair}` is not `role=colour`"));
            continue;
        };
        let Some(role) = role_from_name(name) else {
            // Name what IS valid. An operator who mistyped a role has no other
            // way to discover the vocabulary, and "not a theme role" without
            // the list is a dead end wearing an error's clothes.
            let known = ALL_ROLES
                .iter()
                .map(|r| role_name(*r))
                .collect::<Vec<_>>()
                .join(", ");
            complaints.push(format!(
                "`{}` is not a theme role (have: {known})",
                name.trim()
            ));
            continue;
        };
        match parse_color(value) {
            Ok(color) => overrides.push((role, color)),
            Err(why) => complaints.push(format!("{}: {why}", name.trim())),
        }
    }
    (base.overlaid("custom", &overrides), complaints)
}

/// Snapshot of the current theme. Seeded from the built-in table plus
/// `NEWT_THEME` only; a persisted preference reaches it solely through
/// [`restore_preferences`] (an explicit startup step) or [`set_active`].
/// Invalid `NEWT_THEME` pairs are reported through [`complaints`].
pub fn active() -> std::sync::Arc<Theme> {
    runtime().read().unwrap_or_else(|e| e.into_inner()).clone()
}

/// Apply a complete theme without restarting or leaking old snapshots.
pub fn set_active(theme: Theme) {
    *runtime().write().unwrap_or_else(|e| e.into_inner()) = std::sync::Arc::new(theme);
}

fn runtime() -> &'static std::sync::RwLock<std::sync::Arc<Theme>> {
    static ACTIVE: std::sync::OnceLock<std::sync::RwLock<std::sync::Arc<Theme>>> =
        std::sync::OnceLock::new();
    ACTIVE.get_or_init(|| std::sync::RwLock::new(std::sync::Arc::new(resolved().0.clone())))
}

/// What was wrong with `NEWT_THEME`, if anything.
pub fn complaints() -> &'static [String] {
    &resolved().1
}

/// Built-in table plus `NEWT_THEME`, nothing else. Deliberately NOT the
/// persisted preference: this is what every renderer sees by default, so a
/// lazy read of the operator's config dir here would make the markdown and
/// stream goldens depend on whatever theme the developer last applied —
/// green on a bare CI runner, red on the box that shipped the feature. The
/// unit tier is hermetic only because this function never touches the fs.
fn resolved() -> &'static (Theme, Vec<String>) {
    static THEME: std::sync::OnceLock<(Theme, Vec<String>)> = std::sync::OnceLock::new();
    THEME.get_or_init(default_snapshot)
}

/// What [`resolved`] memoises. Separate so a test can assert on it without
/// the `OnceLock`'s first-caller-wins ordering.
fn default_snapshot() -> (Theme, Vec<String>) {
    from_env(std::env::var("NEWT_THEME").ok().as_deref())
}

/// Apply the persisted preference (`<config dir>/themes/active.toml`) with
/// `NEWT_THEME` overlaid on top — the environment still wins, as it did when
/// it was the only override. An explicit startup step for the interactive
/// binary, never a side effect of rendering; returns what was wrong with the
/// persisted file, for the same one-line startup report as [`complaints`].
pub fn restore_preferences() -> Vec<String> {
    let (theme, warnings) = restored_theme();
    set_active(theme);
    warnings
}

fn restored_theme() -> (Theme, Vec<String>) {
    let (persisted, warnings) = preferences::restore();
    // Env complaints are already reported once through `complaints()`.
    let (theme, _) = overlay_env(persisted, std::env::var("NEWT_THEME").ok().as_deref());
    (theme, warnings)
}

pub mod preferences;

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

    #[test]
    fn env_overrides_preserve_other_saved_styles() {
        use crossterm::style::Attribute;
        let mut saved = Theme::builtin().overlaid(
            "saved",
            &[
                (
                    Role::Thinking,
                    Color::Rgb {
                        r: 12,
                        g: 34,
                        b: 56,
                    },
                ),
                (
                    Role::AgentText,
                    Color::Rgb {
                        r: 78,
                        g: 90,
                        b: 123,
                    },
                ),
            ],
        );
        let mut thinking = saved.style(Role::Thinking);
        thinking.attributes.set(Attribute::Italic);
        saved.set_style(Role::Thinking, thinking);
        let (overlaid, warnings) = overlay_env(saved.clone(), Some("accent=cyan"));
        assert!(warnings.is_empty());
        assert_eq!(overlaid.color(Role::Accent), Color::DarkCyan);
        assert_eq!(overlaid.style(Role::Thinking), saved.style(Role::Thinking));
        assert_eq!(
            overlaid.style(Role::AgentText),
            saved.style(Role::AgentText)
        );
    }

    /// **A persisted preference never leaks into the default snapshot.** The
    /// markdown/stream goldens pin built-in SGR bytes through `active()`; if
    /// the config dir's `active.toml` could reach `resolved()`, applying
    /// `daylight` once would turn `cargo test` red on that box. Pins
    /// `NEWT_CONFIG_DIR` under the `real_fs` serial lane like every other
    /// mutation site in this crate, and asserts on `default_snapshot()`
    /// rather than the memoised `resolved()` so the result does not depend
    /// on which test initialised the `OnceLock` first.
    #[test]
    #[serial_test::serial(real_fs)]
    fn a_persisted_theme_reaches_active_only_through_restore_preferences() {
        let dir = tempfile::tempdir().expect("temp config dir");
        std::fs::create_dir_all(dir.path().join("themes")).unwrap();
        std::fs::write(
            dir.path().join("themes/active.toml"),
            "name = \"daylight\"\n[roles.agent-text]\ncolor = \"black\"\n",
        )
        .unwrap();
        let prev = std::env::var_os(crate::config::NEWT_CONFIG_DIR_ENV);
        std::env::set_var(crate::config::NEWT_CONFIG_DIR_ENV, dir.path());

        let (default_snapshot, _) = default_snapshot();
        let (restored, warnings) = restored_theme();

        match prev {
            Some(v) => std::env::set_var(crate::config::NEWT_CONFIG_DIR_ENV, v),
            None => std::env::remove_var(crate::config::NEWT_CONFIG_DIR_ENV),
        }

        // `!= "daylight"` rather than `== "newt"`: a developer shell that
        // exports a valid NEWT_THEME names the default `custom`, and that is
        // not what this test is about.
        assert_ne!(
            default_snapshot.name, "daylight",
            "the default snapshot read the config dir"
        );
        assert_ne!(default_snapshot.color(Role::AgentText), Color::Black);
        assert_eq!(restored.name, "daylight");
        assert_eq!(restored.color(Role::AgentText), Color::Black);
        assert!(warnings.is_empty(), "{warnings:?}");
    }

    #[test]
    fn file_change_foregrounds_and_backgrounds_are_independently_tunable() {
        let (theme, complaints) = from_env(Some(
            "added=light-green,removed=light-red,added-background=#183825,removed-background=#411d20",
        ));
        assert!(complaints.is_empty(), "{complaints:?}");
        for (name, expected) in [
            ("added", Color::Green),
            ("removed", Color::Red),
            (
                "added-background",
                Color::Rgb {
                    r: 24,
                    g: 56,
                    b: 37,
                },
            ),
            (
                "removed-background",
                Color::Rgb {
                    r: 65,
                    g: 29,
                    b: 32,
                },
            ),
        ] {
            assert_eq!(theme.color(role_from_name(name).unwrap()), expected);
        }
        assert_eq!(theme.color(Role::Text), Theme::builtin().color(Role::Text));
    }

    /// **The seam changes nothing on arrival.**
    ///
    /// Every value the built-in theme serves is one that was already on
    /// screen, so adopting it is invisible to an operator. A theme seam that
    /// re-coloured the product would be two changes in one commit, and the
    /// second would be invisible in review.
    #[test]
    fn the_builtin_theme_preserves_every_colour_in_use() {
        let t = Theme::builtin();
        // The accent, which `palette.rs` wrote out as a literal beside the
        // constant that already held it.
        assert_eq!(
            t.color(Role::Accent),
            Color::Rgb {
                r: 255,
                g: 165,
                b: 90
            }
        );
        assert_eq!(
            t.color(Role::Accent),
            ACTIVE_INPUT_CT,
            "the accent IS the active-input colour; two sources would drift"
        );
        assert_ne!(
            t.color(Role::Accent),
            NEWT_ORANGE_CT,
            "the activity row is the ACTIVE-INPUT accent, not the darker brand \
             orange; `tty::mod` documents the two as deliberately distinct"
        );
        // The role that was thirty-three literals under two spellings.
        assert_eq!(t.color(Role::Dim), Color::DarkGrey);
        assert_eq!(t.color(Role::Muted), Color::Grey);
        assert_eq!(t.color(Role::Emphasis), Color::Yellow);
        assert_eq!(
            t.color(Role::CommandBackground),
            Color::Rgb {
                r: 82,
                g: 82,
                b: 82
            }
        );
        assert_eq!(
            t.color(Role::CommandBackgroundInactive),
            Color::Rgb {
                r: 45,
                g: 45,
                b: 45
            }
        );
        assert_eq!(t.color(Role::CommandBang), Color::Magenta);
        assert_eq!(t.color(Role::CommandEx), Color::Yellow);
        assert_eq!(
            t.color(Role::GaugeWarn),
            Color::Rgb {
                r: 200,
                g: 140,
                b: 0
            }
        );
        assert_eq!(t.color(Role::GaugeCritical), Color::DarkRed);
        assert_eq!(t.color(Role::SelectedLabel), Color::DarkCyan);
        assert_eq!(t.color(Role::SelectedValue), Color::DarkYellow);
        assert_eq!(t.color(Role::Identity), Color::DarkMagenta);
    }

    /// The model's mid-turn narration reads apart from its reply, its
    /// reasoning, and the operator's own text in the default theme.
    #[test]
    fn narration_is_distinct_from_reply_thinking_and_human_text() {
        let t = Theme::builtin();
        assert_eq!(t.color(Role::Narration), Color::Magenta);
        assert_ne!(t.color(Role::Narration), t.color(Role::AgentText));
        assert_ne!(t.color(Role::Narration), t.color(Role::Thinking));
        assert_ne!(t.color(Role::Narration), t.color(Role::HumanText));
        assert_ne!(t.color(Role::Narration), t.color(Role::Dim));
    }

    /// Reasoning and activity remain visibly distinct in the default theme.
    #[test]
    fn thinking_and_activity_keep_separate_default_colors() {
        assert_eq!(Theme::builtin().color(Role::Thinking), Color::DarkGrey);
        assert_eq!(Theme::builtin().color(Role::Accent), ACTIVE_INPUT_CT);
    }

    /// **Every role is reachable by name, both ways.** A role the file cannot
    /// spell is a role an operator cannot theme, and a name that parses to
    /// nothing is a typo the file accepts in silence.
    #[test]
    fn every_role_round_trips_through_its_name() {
        for role in ALL_ROLES {
            let name = role_name(*role);
            assert_eq!(
                role_from_name(name),
                Some(*role),
                "`{name}` does not parse back to the role it names"
            );
            assert_eq!(name, name.to_ascii_lowercase(), "names are kebab-case");
        }
        assert_eq!(ALL_ROLES.len(), 35, "add the new role to ALL_ROLES too");
        assert_eq!(role_from_name("nonsense"), None);
    }

    /// An override is PARTIAL: state one role, keep the rest.
    #[test]
    fn an_override_touches_only_what_it_names() {
        let base = Theme::builtin();
        let themed = Theme::builtin().overlaid("high-contrast", &[(Role::Dim, Color::Grey)]);
        assert_eq!(themed.name, "high-contrast");
        assert_eq!(
            themed.color(Role::Dim),
            Color::Grey,
            "the stated role moved"
        );
        for role in ALL_ROLES.iter().filter(|r| **r != Role::Dim) {
            assert_eq!(
                themed.color(*role),
                base.color(*role),
                "`{}` was not named and must not have moved",
                role_name(*role)
            );
        }
    }

    /// A role is TUNABLE, which is the point of naming it.
    #[test]
    fn the_environment_can_retheme_any_role() {
        let (themed, complaints) = from_env(Some("dim=gray, accent=#00d7ff,thinking=214"));
        assert!(complaints.is_empty(), "{complaints:?}");
        assert_eq!(themed.color(Role::Dim), Color::Grey);
        assert_eq!(
            themed.color(Role::Accent),
            Color::Rgb {
                r: 0,
                g: 215,
                b: 255
            }
        );
        assert_eq!(themed.color(Role::Thinking), Color::AnsiValue(214));
        // Unnamed roles keep the built-in value.
        assert_eq!(
            themed.color(Role::Emphasis),
            Theme::builtin().color(Role::Emphasis)
        );

        // Absent, empty, and whitespace are all "no theme", not an error.
        for nothing in [None, Some(""), Some("   ")] {
            let (t, c) = from_env(nothing);
            assert_eq!(t, Theme::builtin());
            assert!(c.is_empty());
        }
    }

    /// **A bad pair is REPORTED, and the rest still applies.** A theme that
    /// silently half-applies looks like a rendering bug everywhere except the
    /// one place that would explain it.
    #[test]
    fn a_bad_pair_is_named_and_the_rest_still_applies() {
        let (themed, complaints) = from_env(Some("dim=gray,nonsense=red,accent=puce,bare-word"));
        assert_eq!(
            themed.color(Role::Dim),
            Color::Grey,
            "the good pair applied"
        );
        assert_eq!(complaints.len(), 3, "{complaints:?}");
        assert!(complaints.iter().any(|c| c.contains("nonsense")));
        assert!(complaints.iter().any(|c| c.contains("puce")));
        assert!(complaints.iter().any(|c| c.contains("bare-word")));
    }

    #[test]
    fn colours_are_written_the_three_ways_people_have_them() {
        assert_eq!(
            parse_color("#ffa55a"),
            Ok(Color::Rgb {
                r: 255,
                g: 165,
                b: 90
            })
        );
        assert_eq!(
            parse_color("#FFA55A"),
            Ok(Color::Rgb {
                r: 255,
                g: 165,
                b: 90
            })
        );
        assert_eq!(parse_color("214"), Ok(Color::AnsiValue(214)));
        assert_eq!(parse_color("0"), Ok(Color::AnsiValue(0)));
        assert_eq!(parse_color("light-yellow"), Ok(Color::Yellow));
        assert_eq!(parse_color("  cyan  "), Ok(Color::DarkCyan), "trimmed");

        // Both spellings in, one colour out. Recreating the DarkGray/DarkGrey
        // split in the CONFIG vocabulary would be this file's own bug.
        assert_eq!(parse_color("dark-gray"), parse_color("dark-grey"));
        assert_eq!(parse_color("gray"), parse_color("grey"));

        // A refusal names what it wanted rather than falling back silently: a
        // theme that quietly ignores a typo looks broken in one place and
        // right everywhere else, which is the hardest kind to report.
        for bad in ["#fff", "#gggggg", "puce", "256", ""] {
            let err = parse_color(bad).expect_err("`{bad}` is not a colour");
            assert!(err.contains(bad) || bad.is_empty(), "{err}");
        }
    }
}