triage-core 0.2.0

Shared session trait and types for Triage, the attention-routing terminal supervisor.
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
//! Typed Triage configuration loaded from TOML.

use std::net::SocketAddr;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail, ensure};
use serde::Deserialize;

#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    pub general: GeneralConfig,
    pub ui: UiConfig,
    pub attention: AttentionConfig,
    pub agents: AgentsConfig,
    pub remote: RemoteConfig,
    pub mcp: McpConfig,
    pub grpc: GrpcConfig,
    pub approval: ApprovalConfig,
    pub keybindings: KeybindingsConfig,
    pub summarizer: SummarizerConfig,
    pub update: UpdateConfig,
}

impl Config {
    pub fn from_toml_str(input: &str) -> Result<Self> {
        let config: Self = toml::from_str(input).context("parsing config TOML")?;
        config.validate()?;
        Ok(config)
    }

    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        let input =
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
        Self::from_toml_str(&input)
    }

    pub fn default_path() -> Result<PathBuf> {
        let home = std::env::var("HOME")
            .or_else(|_| std::env::var("USERPROFILE"))
            .context("neither HOME nor USERPROFILE environment variable is set")?;
        Ok(PathBuf::from(home).join(".config/triage/config.toml"))
    }

    pub fn validate(&self) -> Result<()> {
        self.general.validate()?;
        self.ui.validate()?;
        self.attention.validate()?;
        self.agents.validate()?;
        self.remote.validate()?;
        self.mcp.validate()?;
        self.grpc.validate()?;
        self.approval.validate()?;
        self.keybindings.validate()?;
        self.summarizer.validate()?;
        self.update.validate()?;
        Ok(())
    }
}

/// Settings for the background update check (Phase 1 of self-update). The daemon
/// periodically asks the release host for the latest published tag and surfaces
/// an "update available" banner; nothing is ever downloaded or installed
/// automatically. Set `check = false` to disable the check entirely.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct UpdateConfig {
    /// Whether the daemon polls for newer releases at all.
    pub check: bool,
    /// How often to poll, in hours. Must be greater than zero.
    pub interval_hours: u64,
    /// Release channel to track. Only `stable` is recognized today.
    pub channel: String,
}

impl UpdateConfig {
    fn validate(&self) -> Result<()> {
        ensure!(
            self.interval_hours > 0,
            "update.interval_hours must be greater than zero"
        );
        ensure_non_empty("update.channel", &self.channel)?;
        // Only `stable` is wired up today; reject anything else loudly rather
        // than silently accepting a channel that has no effect. Relax this to an
        // enum once more channels exist.
        ensure!(
            self.channel == "stable",
            "update.channel must be \"stable\" (the only channel supported today)"
        );
        Ok(())
    }
}

impl Default for UpdateConfig {
    fn default() -> Self {
        Self {
            check: true,
            interval_hours: 6,
            channel: "stable".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct GeneralConfig {
    pub default_shell: String,
}

impl GeneralConfig {
    fn validate(&self) -> Result<()> {
        ensure_non_empty("general.default_shell", &self.default_shell)
    }
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            default_shell: "/bin/zsh".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct UiConfig {
    pub theme: String,
    pub sidebar_width_percent: u8,
    pub group_by: GroupBy,
}

impl UiConfig {
    fn validate(&self) -> Result<()> {
        ensure!(
            (1..=80).contains(&self.sidebar_width_percent),
            "ui.sidebar_width_percent must be between 1 and 80"
        );
        ensure_non_empty("ui.theme", &self.theme)
    }
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            theme: "catppuccin-mocha".to_string(),
            sidebar_width_percent: 22,
            group_by: GroupBy::Worktree,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GroupBy {
    Repo,
    Worktree,
    Flat,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AttentionConfig {
    pub idle_threshold_ms: u64,
    pub notify_on_awaiting: bool,
    pub notify_sound: bool,
}

impl AttentionConfig {
    fn validate(&self) -> Result<()> {
        ensure!(
            self.idle_threshold_ms > 0,
            "attention.idle_threshold_ms must be greater than zero"
        );
        Ok(())
    }
}

impl Default for AttentionConfig {
    fn default() -> Self {
        Self {
            idle_threshold_ms: 1500,
            notify_on_awaiting: true,
            notify_sound: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AgentsConfig {
    pub known: Vec<String>,
    pub custom_pack: AgentPatternPack,
}

impl AgentsConfig {
    fn validate(&self) -> Result<()> {
        ensure_non_empty_items("agents.known", &self.known)?;
        self.custom_pack.validate("agents.custom_pack")
    }
}

impl Default for AgentsConfig {
    fn default() -> Self {
        Self {
            known: vec![
                "claude".to_string(),
                "aider".to_string(),
                "codex".to_string(),
                "cline".to_string(),
                "continue".to_string(),
            ],
            custom_pack: AgentPatternPack::default(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct AgentPatternPack {
    pub process_names: Vec<String>,
    pub prompt_patterns: Vec<String>,
}

impl AgentPatternPack {
    fn validate(&self, prefix: &str) -> Result<()> {
        ensure_non_empty_items(&format!("{prefix}.process_names"), &self.process_names)?;
        ensure_non_empty_items(&format!("{prefix}.prompt_patterns"), &self.prompt_patterns)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RemoteConfig {
    pub bind: String,
    pub require_pairing: bool,
    pub tls_cert: Option<String>,
    pub tls_key: Option<String>,
    pub web_assets_path: Option<String>,
    /// Tailnet login names (e.g. `you@example.com`) permitted to approve pairing
    /// from a remote device. When non-empty, a `/pair` request whose tailnet
    /// identity (`tailscale whois`) matches an entry is allowed to approve, in
    /// addition to loopback / same-host. Empty (the default) keeps approval
    /// loopback-only.
    pub pair_approval_tailnet_users: Vec<String>,
    /// Whether loopback / same-host peers are auto-trusted to approve pairing.
    /// Defaults to `true`. Set to `false` when a loopback reverse proxy (or any
    /// intermediary that makes remote requests appear local) terminates TLS in
    /// front of the daemon — otherwise every forwarded request looks like a
    /// loopback peer and bypasses the tailnet identity check. When `false`,
    /// `pair_approval_tailnet_users` must be non-empty (otherwise nothing could
    /// ever approve pairing).
    pub pair_approval_trust_local_peers: bool,
}

/// Tailscale reports tag-owned (non-user) nodes with this synthetic login. It is
/// shared by *every* tagged node on a tailnet, so it must never be treated as an
/// approvable identity — it is rejected by remote-config validation and the
/// `/pair` gate.
pub const TAGGED_DEVICES_LOGIN: &str = "tagged-devices";

impl RemoteConfig {
    pub fn bind_addr(&self) -> Result<SocketAddr> {
        parse_socket_addr("remote.bind", &self.bind)
    }

    fn validate(&self) -> Result<()> {
        self.bind_addr()?;
        if let Some(ref path) = self.web_assets_path {
            ensure_non_empty("remote.web_assets_path", path)?;
        }
        ensure_non_empty_items(
            "remote.pair_approval_tailnet_users",
            &self.pair_approval_tailnet_users,
        )?;
        for (index, user) in self.pair_approval_tailnet_users.iter().enumerate() {
            if user.trim().eq_ignore_ascii_case(TAGGED_DEVICES_LOGIN) {
                bail!(
                    "remote.pair_approval_tailnet_users[{index}] must not be \"{TAGGED_DEVICES_LOGIN}\": \
                     this is Tailscale's shared pseudo-login for every tag-owned node, so listing it \
                     would grant pairing approval to all tagged devices on the tailnet"
                );
            }
        }
        if !self.pair_approval_tailnet_users.is_empty() && !self.require_pairing {
            bail!(
                "remote.pair_approval_tailnet_users requires remote.require_pairing = true \
                 (pairing approval is meaningless when pairing is disabled)"
            );
        }
        if !self.pair_approval_trust_local_peers && self.pair_approval_tailnet_users.is_empty() {
            bail!(
                "remote.pair_approval_trust_local_peers = false requires a non-empty \
                 remote.pair_approval_tailnet_users (otherwise no peer could ever approve pairing)"
            );
        }
        match (&self.tls_cert, &self.tls_key) {
            (Some(cert), Some(key)) => {
                ensure_non_empty("remote.tls_cert", cert)?;
                ensure_non_empty("remote.tls_key", key)
            }
            (None, None) => Ok(()),
            _ => bail!("remote.tls_cert and remote.tls_key must be set together"),
        }
    }
}

impl Default for RemoteConfig {
    fn default() -> Self {
        Self {
            // Bind to all interfaces by default so the client can connect from
            // another device (LAN/tailnet). Access is gated by pairing
            // (`require_pairing`, default true); `triaged` logs a warning at
            // startup when bound to an unspecified address.
            bind: "0.0.0.0:7777".to_string(),
            require_pairing: true,
            tls_cert: None,
            tls_key: None,
            web_assets_path: None,
            // Loopback-only pairing approval by default; opt in to remote
            // (tailnet) approval by listing tailnet login names here.
            pair_approval_tailnet_users: Vec::new(),
            // Trust loopback / same-host peers to approve pairing by default;
            // disable only when a loopback reverse proxy fronts the daemon.
            pair_approval_trust_local_peers: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct McpConfig {
    pub tcp_bind: String,
}

impl McpConfig {
    pub fn tcp_bind_addr(&self) -> Result<SocketAddr> {
        parse_socket_addr("mcp.tcp_bind", &self.tcp_bind)
    }

    fn validate(&self) -> Result<()> {
        self.tcp_bind_addr()?;
        Ok(())
    }
}

impl Default for McpConfig {
    fn default() -> Self {
        Self {
            tcp_bind: "127.0.0.1:7778".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct GrpcConfig {
    pub enabled: bool,
    pub bind: Option<String>,
}

impl GrpcConfig {
    pub fn bind_addr(&self) -> Result<Option<SocketAddr>> {
        self.bind
            .as_deref()
            .map(|bind| parse_socket_addr("grpc.bind", bind))
            .transpose()
    }

    fn validate(&self) -> Result<()> {
        match (self.enabled, &self.bind) {
            (true, None) => bail!("grpc.bind must be set when grpc.enabled is true"),
            (_, Some(bind)) => {
                ensure_non_empty("grpc.bind", bind)?;
                self.bind_addr()?;
            }
            (false, None) => {}
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ApprovalConfig {
    pub patterns: Vec<String>,
}

impl ApprovalConfig {
    fn validate(&self) -> Result<()> {
        ensure_non_empty_items("approval.patterns", &self.patterns)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct KeybindingsConfig {
    pub overview: String,
    pub search: String,
    pub next_attention: String,
    pub cycle_agents: String,
    pub cycle_current_repo: String,
    pub pause_all: String,
}

impl KeybindingsConfig {
    fn validate(&self) -> Result<()> {
        ensure_non_empty("keybindings.overview", &self.overview)?;
        ensure_non_empty("keybindings.search", &self.search)?;
        ensure_non_empty("keybindings.next_attention", &self.next_attention)?;
        ensure_non_empty("keybindings.cycle_agents", &self.cycle_agents)?;
        ensure_non_empty("keybindings.cycle_current_repo", &self.cycle_current_repo)?;
        ensure_non_empty("keybindings.pause_all", &self.pause_all)
    }
}

impl Default for KeybindingsConfig {
    fn default() -> Self {
        Self {
            overview: "ctrl+e".to_string(),
            search: "ctrl+f".to_string(),
            next_attention: "g w".to_string(),
            cycle_agents: "g a".to_string(),
            cycle_current_repo: "g r".to_string(),
            pause_all: "ctrl+shift+p".to_string(),
        }
    }
}

/// Local-LLM session summarizer: generates a short one-line description of what
/// each session is doing, shown in the client's side rail.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SummarizerConfig {
    /// Master switch. When false, no model is loaded and no snippets are produced.
    pub enabled: bool,
    /// LeapBundles bundle id, e.g. `LFM2.5-1.2B-Instruct-GGUF`.
    pub bundle_id: String,
    /// Quantization tag, e.g. `Q4_0`.
    pub quant: String,
    /// Inference context window (tokens). Kept small — we only summarize one screen.
    pub context_size: u32,
    /// Upper bound on generated tokens per snippet.
    pub max_tokens: u32,
    /// Upper bound on generated tokens for the longer-form detail summary
    /// (hover popover / search). Larger than `max_tokens`.
    pub detail_max_tokens: u32,
    /// How long a session's output must be quiet before we (re)summarize it.
    pub settle_ms: u64,
    /// Minimum interval between regenerations for a single session.
    pub min_regen_ms: u64,
    /// Where to cache downloaded model files. `None` → `~/.cache/triage/models`.
    pub cache_dir: Option<String>,
}

impl SummarizerConfig {
    fn validate(&self) -> Result<()> {
        if !self.enabled {
            return Ok(());
        }
        ensure_non_empty("summarizer.bundle_id", &self.bundle_id)?;
        ensure_non_empty("summarizer.quant", &self.quant)?;
        ensure!(
            self.context_size > 0,
            "summarizer.context_size must be greater than zero"
        );
        ensure!(
            self.max_tokens > 0,
            "summarizer.max_tokens must be greater than zero"
        );
        ensure!(
            self.detail_max_tokens > 0,
            "summarizer.detail_max_tokens must be greater than zero"
        );
        if let Some(ref dir) = self.cache_dir {
            ensure_non_empty("summarizer.cache_dir", dir)?;
        }
        Ok(())
    }
}

impl Default for SummarizerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            bundle_id: "LFM2.5-1.2B-Instruct-GGUF".to_string(),
            quant: "Q4_0".to_string(),
            context_size: 1024,
            max_tokens: 24,
            detail_max_tokens: 180,
            settle_ms: 1500,
            min_regen_ms: 5000,
            cache_dir: None,
        }
    }
}

fn parse_socket_addr(field: &str, value: &str) -> Result<SocketAddr> {
    ensure_non_empty(field, value)?;
    value
        .parse()
        .with_context(|| format!("{field} must be a socket address"))
}

fn ensure_non_empty(field: &str, value: &str) -> Result<()> {
    ensure!(!value.trim().is_empty(), "{field} must not be empty");
    Ok(())
}

fn ensure_non_empty_items(field: &str, values: &[String]) -> Result<()> {
    for (index, value) in values.iter().enumerate() {
        ensure!(
            !value.trim().is_empty(),
            "{field}[{index}] must not be empty"
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use super::*;

    const FULL_CONFIG: &str = r#"
[general]
default_shell = "/bin/fish"

[ui]
theme = "catppuccin-latte"
sidebar_width_percent = 30
group_by = "repo"

[attention]
idle_threshold_ms = 2500
notify_on_awaiting = false
notify_sound = false

[agents]
known = ["claude", "codex"]

[agents.custom_pack]
process_names = ["my-agent"]
prompt_patterns = ['\? for shortcuts', '\[y/n\]']

[remote]
bind = "127.0.0.1:8888"
require_pairing = true
tls_cert = "~/.config/triage/certs/dev.crt"
tls_key = "~/.config/triage/certs/dev.key"
pair_approval_tailnet_users = ["alice@example.com", "bob@example.com"]
pair_approval_trust_local_peers = false

[mcp]
tcp_bind = "127.0.0.1:8889"

[grpc]
enabled = true
bind = "127.0.0.1:50051"

[approval]
patterns = ["^rm -rf"]

[keybindings]
overview = "ctrl+o"
search = "ctrl+s"
next_attention = "g n"
cycle_agents = "g c"
cycle_current_repo = "g p"
pause_all = "ctrl+p"
"#;

    #[test]
    fn defaults_match_documented_config() {
        let config = Config::default();

        assert_eq!(config.general.default_shell, "/bin/zsh");
        assert_eq!(config.ui.theme, "catppuccin-mocha");
        assert_eq!(config.ui.sidebar_width_percent, 22);
        assert_eq!(config.ui.group_by, GroupBy::Worktree);
        assert_eq!(config.attention.idle_threshold_ms, 1500);
        assert!(config.attention.notify_on_awaiting);
        assert!(config.attention.notify_sound);
        assert_eq!(
            config.agents.known,
            ["claude", "aider", "codex", "cline", "continue"]
        );
        assert_eq!(config.remote.bind, "0.0.0.0:7777");
        assert!(config.remote.require_pairing);
        assert!(config.remote.pair_approval_tailnet_users.is_empty());
        assert!(config.remote.pair_approval_trust_local_peers);
        assert_eq!(config.mcp.tcp_bind, "127.0.0.1:7778");
        assert!(!config.grpc.enabled);
        assert_eq!(config.keybindings.next_attention, "g w");
        assert!(config.summarizer.enabled);
        assert_eq!(config.summarizer.bundle_id, "LFM2.5-1.2B-Instruct-GGUF");
        assert_eq!(config.summarizer.quant, "Q4_0");
        assert_eq!(config.summarizer.context_size, 1024);
    }

    #[test]
    fn sparse_toml_uses_defaults() {
        let config = Config::from_toml_str(
            r#"
[ui]
theme = "plain"

[attention]
notify_sound = false
"#,
        )
        .expect("sparse config should parse");

        assert_eq!(config.ui.theme, "plain");
        assert_eq!(config.ui.sidebar_width_percent, 22);
        assert_eq!(config.ui.group_by, GroupBy::Worktree);
        assert_eq!(config.attention.idle_threshold_ms, 1500);
        assert!(!config.attention.notify_sound);
    }

    #[test]
    fn full_documented_toml_parses() {
        let config = Config::from_toml_str(FULL_CONFIG).expect("full config should parse");

        assert_eq!(config.general.default_shell, "/bin/fish");
        assert_eq!(config.ui.group_by, GroupBy::Repo);
        assert_eq!(config.remote.bind_addr().unwrap().port(), 8888);
        // The allowlist assertion below is only reachable because the fixture
        // also sets require_pairing = true (validation rejects the pair-approval
        // allowlist otherwise) — assert that coupling explicitly so it can't
        // regress silently.
        assert!(config.remote.require_pairing);
        assert_eq!(
            config.remote.pair_approval_tailnet_users,
            ["alice@example.com", "bob@example.com"]
        );
        assert!(!config.remote.pair_approval_trust_local_peers);
        assert_eq!(config.mcp.tcp_bind_addr().unwrap().port(), 8889);
        assert_eq!(config.grpc.bind_addr().unwrap().unwrap().port(), 50051);
        assert_eq!(config.approval.patterns, ["^rm -rf"]);
        assert_eq!(config.keybindings.overview, "ctrl+o");
    }

    #[test]
    fn invalid_group_by_fails() {
        let error = Config::from_toml_str(
            r#"
[ui]
group_by = "workspace"
"#,
        )
        .expect_err("invalid group_by should fail");

        assert!(error.to_string().contains("parsing config TOML"));
    }

    #[test]
    fn invalid_bind_address_fails() {
        let error = Config::from_toml_str(
            r#"
[remote]
bind = "localhost"
"#,
        )
        .expect_err("invalid bind should fail");

        assert!(
            error
                .to_string()
                .contains("remote.bind must be a socket address")
        );
    }

    #[test]
    fn invalid_sidebar_width_fails() {
        let error = Config::from_toml_str(
            r#"
[ui]
sidebar_width_percent = 0
"#,
        )
        .expect_err("invalid sidebar width should fail");

        assert!(
            error
                .to_string()
                .contains("ui.sidebar_width_percent must be between 1 and 80")
        );
    }

    #[test]
    fn tls_cert_and_key_must_be_paired() {
        let error = Config::from_toml_str(
            r#"
[remote]
tls_cert = "server.crt"
"#,
        )
        .expect_err("unpaired TLS cert should fail");

        assert!(
            error
                .to_string()
                .contains("remote.tls_cert and remote.tls_key must be set together")
        );
    }

    #[test]
    fn empty_tailnet_pair_approval_user_fails_validation() {
        let error = Config::from_toml_str(
            r#"
[remote]
pair_approval_tailnet_users = ["alice@example.com", " "]
"#,
        )
        .expect_err("empty tailnet pair approval user should fail");

        assert!(
            error
                .to_string()
                .contains("remote.pair_approval_tailnet_users[1] must not be empty")
        );
    }

    #[test]
    fn tailnet_pair_approval_requires_require_pairing() {
        let error = Config::from_toml_str(
            r#"
[remote]
require_pairing = false
pair_approval_tailnet_users = ["alice@example.com"]
"#,
        )
        .expect_err("tailnet pair approval without require_pairing should fail");

        assert!(
            error.to_string().contains(
                "remote.pair_approval_tailnet_users requires remote.require_pairing = true"
            )
        );
    }

    #[test]
    fn tagged_devices_pseudo_login_is_rejected() {
        let error = Config::from_toml_str(
            r#"
[remote]
pair_approval_tailnet_users = ["alice@example.com", " Tagged-Devices "]
"#,
        )
        .expect_err("tagged-devices pseudo-login should fail");

        assert!(
            error.to_string().contains("must not be \"tagged-devices\""),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn distrusting_local_peers_requires_an_allowlist() {
        let error = Config::from_toml_str(
            r#"
[remote]
pair_approval_trust_local_peers = false
"#,
        )
        .expect_err("distrusting local peers with no allowlist should fail");

        assert!(
            error
                .to_string()
                .contains("remote.pair_approval_trust_local_peers = false requires a non-empty"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn empty_values_fail_validation() {
        let error = Config::from_toml_str(
            r#"
[keybindings]
search = " "
"#,
        )
        .expect_err("empty keybinding should fail");

        assert!(
            error
                .to_string()
                .contains("keybindings.search must not be empty")
        );
    }

    #[test]
    fn empty_default_shell_fails_validation() {
        let error = Config::from_toml_str(
            r#"
[general]
default_shell = " "
"#,
        )
        .expect_err("empty default shell should fail");

        assert!(
            error
                .to_string()
                .contains("general.default_shell must not be empty")
        );
    }

    #[test]
    fn enabled_grpc_requires_bind() {
        let error = Config::from_toml_str(
            r#"
[grpc]
enabled = true
"#,
        )
        .expect_err("enabled grpc without bind should fail");

        assert!(
            error
                .to_string()
                .contains("grpc.bind must be set when grpc.enabled is true")
        );
    }

    #[test]
    fn loads_from_path() {
        let unique = format!(
            "triage-config-test-{}-{}.toml",
            std::process::id(),
            std::time::UNIX_EPOCH
                .elapsed()
                .expect("system clock should be after Unix epoch")
                .as_nanos()
        );
        let path = std::env::temp_dir().join(unique);
        let mut file = std::fs::File::create(&path).expect("test config file should be created");
        file.write_all(
            br#"
[general]
default_shell = "/bin/bash"
"#,
        )
        .expect("test config should be written");
        file.flush().expect("test config should be flushed");
        drop(file);

        let config = Config::load_from_path(&path).expect("config should load from path");
        std::fs::remove_file(&path).expect("test config file should be removed");

        assert_eq!(config.general.default_shell, "/bin/bash");
    }

    #[test]
    fn update_defaults_are_valid() {
        let config = Config::default();
        assert!(config.update.check);
        assert_eq!(config.update.interval_hours, 6);
        assert_eq!(config.update.channel, "stable");
        config
            .validate()
            .expect("default update config should validate");
    }

    #[test]
    fn unknown_update_channel_is_rejected() {
        let error = Config::from_toml_str(
            r#"
[update]
channel = "beta"
"#,
        )
        .expect_err("an unrecognized update channel should fail");

        assert!(
            error
                .to_string()
                .contains("update.channel must be \"stable\""),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn zero_update_interval_is_rejected() {
        let error = Config::from_toml_str(
            r#"
[update]
interval_hours = 0
"#,
        )
        .expect_err("a zero update interval should fail");

        assert!(
            error
                .to_string()
                .contains("update.interval_hours must be greater than zero"),
            "unexpected error: {error}"
        );
    }
}