codetether-agent 4.5.7

A2A-native AI coding agent for the CodeTether ecosystem
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
//! Configuration system
//!
//! Handles loading configuration from multiple sources:
//! - Global config (~/.config/codetether/config.toml)
//! - Project config (./codetether.toml or .codetether/config.toml)
//! - Environment variables (CODETETHER_*)

use anyhow::Result;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tokio::fs;

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Default provider to use
    #[serde(default)]
    pub default_provider: Option<String>,

    /// Default model to use (provider/model format)
    #[serde(default)]
    pub default_model: Option<String>,

    /// Provider-specific configurations
    #[serde(default)]
    pub providers: HashMap<String, ProviderConfig>,

    /// Agent configurations
    #[serde(default)]
    pub agents: HashMap<String, AgentConfig>,

    /// Permission rules
    #[serde(default)]
    pub permissions: PermissionConfig,

    /// A2A worker settings
    #[serde(default)]
    pub a2a: A2aConfig,

    /// UI/TUI settings
    #[serde(default)]
    pub ui: UiConfig,

    /// Session settings
    #[serde(default)]
    pub session: SessionConfig,

    /// Telemetry and crash reporting settings
    #[serde(default)]
    pub telemetry: TelemetryConfig,

    /// LSP / linter server settings
    #[serde(default)]
    pub lsp: LspSettings,

    /// RLM (Recursive Language Model) settings.
    ///
    /// Controls when and how large-output tool results and long
    /// conversation prefixes are handed off to the RLM router for
    /// compression/analysis. See [`crate::rlm::RlmConfig`] for fields.
    #[serde(default)]
    pub rlm: crate::rlm::RlmConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            // Default to GLM-5 via Z.AI everywhere unless overridden.
            // Use provider/model format so provider selection is unambiguous.
            default_provider: Some("zai".to_string()),
            default_model: Some("zai/glm-5".to_string()),
            providers: HashMap::new(),
            agents: HashMap::new(),
            permissions: PermissionConfig::default(),
            a2a: A2aConfig::default(),
            ui: UiConfig::default(),
            session: SessionConfig::default(),
            telemetry: TelemetryConfig::default(),
            lsp: LspSettings::default(),
            rlm: crate::rlm::RlmConfig::default(),
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Default)]
pub struct ProviderConfig {
    /// API key (can also be set via env var)
    pub api_key: Option<String>,

    /// Base URL override
    pub base_url: Option<String>,

    /// Custom headers
    #[serde(default)]
    pub headers: HashMap<String, String>,

    /// Organization ID (for OpenAI)
    pub organization: Option<String>,
}

impl std::fmt::Debug for ProviderConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProviderConfig")
            .field("api_key", &self.api_key.as_ref().map(|_| "<REDACTED>"))
            .field("api_key_len", &self.api_key.as_ref().map(|k| k.len()))
            .field("base_url", &self.base_url)
            .field("organization", &self.organization)
            .field("headers_count", &self.headers.len())
            .finish()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent name
    pub name: String,

    /// Description
    #[serde(default)]
    pub description: Option<String>,

    /// Model override for this agent
    #[serde(default)]
    pub model: Option<String>,

    /// System prompt override
    #[serde(default)]
    pub prompt: Option<String>,

    /// Temperature setting
    #[serde(default)]
    pub temperature: Option<f32>,

    /// Top-p setting
    #[serde(default)]
    pub top_p: Option<f32>,

    /// Custom permissions for this agent
    #[serde(default)]
    pub permissions: HashMap<String, PermissionAction>,

    /// Whether this agent is disabled
    #[serde(default)]
    pub disabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PermissionConfig {
    /// Default permission rules
    #[serde(default)]
    pub rules: HashMap<String, PermissionAction>,

    /// Tool-specific permissions
    #[serde(default)]
    pub tools: HashMap<String, PermissionAction>,

    /// Path-specific permissions
    #[serde(default)]
    pub paths: HashMap<String, PermissionAction>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum PermissionAction {
    Allow,
    Deny,
    #[default]
    Ask,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct A2aConfig {
    /// Default A2A server URL
    pub server_url: Option<String>,

    /// Worker name
    pub worker_name: Option<String>,

    /// Auto-approve policy
    #[serde(default)]
    pub auto_approve: AutoApprovePolicy,

    /// Workspaces to register
    #[serde(default)]
    pub workspaces: Vec<PathBuf>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AutoApprovePolicy {
    All,
    #[default]
    Safe,
    None,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiConfig {
    /// Theme name ("default", "marketing", "dark", "light", "solarized-dark", "solarized-light", or custom)
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Show line numbers in code
    #[serde(default = "default_true")]
    pub line_numbers: bool,

    /// Enable mouse support
    #[serde(default = "default_true")]
    pub mouse: bool,

    /// Custom theme configuration (overrides preset themes)
    #[serde(default)]
    pub custom_theme: Option<crate::tui::theme::Theme>,

    /// Enable theme hot-reloading (apply changes without restart)
    #[serde(default = "default_false")]
    pub hot_reload: bool,
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            line_numbers: true,
            mouse: true,
            custom_theme: None,
            hot_reload: false,
        }
    }
}

fn default_theme() -> String {
    "marketing".to_string()
}

fn default_true() -> bool {
    true
}

fn default_false() -> bool {
    false
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionConfig {
    /// Auto-compact sessions when they get too long
    #[serde(default = "default_true")]
    pub auto_compact: bool,

    /// Maximum context tokens before compaction
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,

    /// Enable session persistence
    #[serde(default = "default_true")]
    pub persist: bool,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            auto_compact: true,
            max_tokens: default_max_tokens(),
            persist: true,
        }
    }
}

fn default_max_tokens() -> usize {
    100_000
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TelemetryConfig {
    /// Opt-in crash reporting. Disabled by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crash_reporting: Option<bool>,

    /// Whether we have already prompted the user about crash reporting consent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crash_reporting_prompted: Option<bool>,

    /// Endpoint for crash report ingestion.
    /// Defaults to the CodeTether telemetry endpoint when unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crash_report_endpoint: Option<String>,
}

impl TelemetryConfig {
    pub fn crash_reporting_enabled(&self) -> bool {
        self.crash_reporting.unwrap_or(false)
    }

    pub fn crash_reporting_prompted(&self) -> bool {
        self.crash_reporting_prompted.unwrap_or(false)
    }

    pub fn crash_report_endpoint(&self) -> String {
        self.crash_report_endpoint
            .clone()
            .unwrap_or_else(default_crash_report_endpoint)
    }
}

fn default_crash_report_endpoint() -> String {
    "https://api.codetether.run/v1/crash-reports".to_string()
}

/// Configuration for LSP language servers and linter servers.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LspSettings {
    /// Additional language servers beyond the built-in defaults.
    /// Keyed by a user-chosen name (e.g. "my-ruby-lsp").
    #[serde(default)]
    pub servers: HashMap<String, LspServerEntry>,

    /// Linter servers that run alongside the primary language server.
    /// These only contribute diagnostics; they are not used for
    /// go-to-definition, completion, etc.
    /// Use the built-in name ("eslint", "ruff", "biome") or provide
    /// a custom entry with `command`.
    #[serde(default)]
    pub linters: HashMap<String, LspLinterEntry>,

    /// Disable all built-in linter integrations (default: false).
    #[serde(default)]
    pub disable_builtin_linters: bool,
}

/// A user-defined language server entry in config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LspServerEntry {
    /// Binary / command to run.
    pub command: String,
    /// Arguments passed to the command.
    #[serde(default)]
    pub args: Vec<String>,
    /// File extensions this server handles (e.g. ["rb", "erb"]).
    #[serde(default)]
    pub file_extensions: Vec<String>,
    /// Optional initialization options (JSON value).
    #[serde(default)]
    pub initialization_options: Option<serde_json::Value>,
    /// Request timeout in milliseconds (default 30 000).
    #[serde(default = "default_lsp_timeout")]
    pub timeout_ms: u64,
}

/// A linter server entry in config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LspLinterEntry {
    /// Binary / command to run.  For built-in linters (eslint, ruff, biome)
    /// this can be omitted — the default binary name will be used.
    pub command: Option<String>,
    /// Arguments passed to the command.
    #[serde(default)]
    pub args: Vec<String>,
    /// File extensions this linter handles.  If empty, the built-in
    /// defaults for the linter are used.
    #[serde(default)]
    pub file_extensions: Vec<String>,
    /// Optional initialization options.
    #[serde(default)]
    pub initialization_options: Option<serde_json::Value>,
    /// Whether this linter is enabled (default: true).
    #[serde(default = "default_true")]
    pub enabled: bool,
}

impl Default for LspLinterEntry {
    fn default() -> Self {
        Self {
            command: None,
            args: Vec::new(),
            file_extensions: Vec::new(),
            initialization_options: None,
            enabled: true,
        }
    }
}

fn default_lsp_timeout() -> u64 {
    30_000
}

impl Config {
    /// Load configuration from all sources (global, project, env)
    ///
    /// Performance: issues every candidate file read concurrently so that
    /// slow-disk or network-mounted home directories don't sum their
    /// latency. Merge order is preserved: global < project-root <
    /// project-dot-dir < env.
    pub async fn load() -> Result<Self> {
        // Resolve all candidate paths up front.
        let global_path = Self::global_config_path();
        let project_paths = [
            PathBuf::from("codetether.toml"),
            PathBuf::from(".codetether/config.toml"),
        ];

        // Fire all reads in parallel. Each future returns (path, Option<content>).
        // Missing / unreadable files yield `None` and are simply skipped.
        async fn read_opt(p: PathBuf) -> (PathBuf, Option<String>) {
            match fs::read_to_string(&p).await {
                Ok(s) => (p, Some(s)),
                Err(_) => (p, None),
            }
        }

        let global_future = async {
            match global_path {
                Some(p) => Some(read_opt(p).await),
                None => None,
            }
        };
        let project_futures = futures::future::join_all(project_paths.into_iter().map(read_opt));

        let (global_result, project_results) = tokio::join!(global_future, project_futures);

        let mut config = Self::default();
        if let Some((path, Some(content))) = global_result {
            match toml::from_str::<Config>(&content) {
                Ok(global) => config = config.merge(global),
                Err(err) => {
                    return Err(err).map_err(|e| {
                        anyhow::anyhow!("failed to parse {}: {}", path.display(), e)
                    });
                }
            }
        }
        for (path, maybe) in project_results {
            let Some(content) = maybe else { continue };
            match toml::from_str::<Config>(&content) {
                Ok(project) => config = config.merge(project),
                Err(err) => {
                    return Err(err).map_err(|e| {
                        anyhow::anyhow!("failed to parse {}: {}", path.display(), e)
                    });
                }
            }
        }

        // Apply environment overrides
        config.apply_env();
        config.normalize_legacy_defaults();

        Ok(config)
    }

    /// Get the global config directory path
    pub fn global_config_path() -> Option<PathBuf> {
        ProjectDirs::from("ai", "codetether", "codetether-agent")
            .map(|dirs| dirs.config_dir().join("config.toml"))
    }

    /// Get the data directory path
    pub fn data_dir() -> Option<PathBuf> {
        if let Ok(explicit) = std::env::var("CODETETHER_DATA_DIR") {
            let explicit = explicit.trim();
            if !explicit.is_empty() {
                return Some(PathBuf::from(explicit));
            }
        }

        workspace_data_dir().or_else(|| {
            ProjectDirs::from("ai", "codetether", "codetether-agent")
                .map(|dirs| dirs.data_dir().to_path_buf())
        })
    }

    /// Initialize default configuration file
    pub async fn init_default() -> Result<()> {
        if let Some(path) = Self::global_config_path() {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).await?;
            }
            let default = Self::default();
            let content = toml::to_string_pretty(&default)?;
            fs::write(&path, content).await?;
            tracing::info!("Created config at {:?}", path);
        }
        Ok(())
    }

    /// Set a configuration value
    pub async fn set(key: &str, value: &str) -> Result<()> {
        let mut config = Self::load().await?;

        // Parse key path and set value
        match key {
            "default_provider" => config.default_provider = Some(value.to_string()),
            "default_model" => config.default_model = Some(value.to_string()),
            "a2a.server_url" => config.a2a.server_url = Some(value.to_string()),
            "a2a.worker_name" => config.a2a.worker_name = Some(value.to_string()),
            "ui.theme" => config.ui.theme = value.to_string(),
            "telemetry.crash_reporting" => {
                config.telemetry.crash_reporting = Some(parse_bool(value)?)
            }
            "telemetry.crash_reporting_prompted" => {
                config.telemetry.crash_reporting_prompted = Some(parse_bool(value)?)
            }
            "telemetry.crash_report_endpoint" => {
                config.telemetry.crash_report_endpoint = Some(value.to_string())
            }
            _ => anyhow::bail!("Unknown config key: {}", key),
        }

        // Save to global config
        if let Some(path) = Self::global_config_path() {
            let content = toml::to_string_pretty(&config)?;
            fs::write(&path, content).await?;
        }

        Ok(())
    }

    /// Merge two configs (other takes precedence)
    fn merge(mut self, other: Self) -> Self {
        if other.default_provider.is_some() {
            self.default_provider = other.default_provider;
        }
        if other.default_model.is_some() {
            self.default_model = other.default_model;
        }
        self.providers.extend(other.providers);
        self.agents.extend(other.agents);
        self.permissions.rules.extend(other.permissions.rules);
        self.permissions.tools.extend(other.permissions.tools);
        self.permissions.paths.extend(other.permissions.paths);
        if other.a2a.server_url.is_some() {
            self.a2a = other.a2a;
        }
        if other.telemetry.crash_reporting.is_some() {
            self.telemetry.crash_reporting = other.telemetry.crash_reporting;
        }
        if other.telemetry.crash_reporting_prompted.is_some() {
            self.telemetry.crash_reporting_prompted = other.telemetry.crash_reporting_prompted;
        }
        if other.telemetry.crash_report_endpoint.is_some() {
            self.telemetry.crash_report_endpoint = other.telemetry.crash_report_endpoint;
        }
        self.lsp.servers.extend(other.lsp.servers);
        self.lsp.linters.extend(other.lsp.linters);
        if other.lsp.disable_builtin_linters {
            self.lsp.disable_builtin_linters = true;
        }
        self
    }

    /// Load theme based on configuration
    pub fn load_theme(&self) -> crate::tui::theme::Theme {
        // Use custom theme if provided
        if let Some(custom) = &self.ui.custom_theme {
            return custom.clone();
        }

        // Use preset theme
        match self.ui.theme.as_str() {
            "marketing" | "default" => crate::tui::theme::Theme::marketing(),
            "dark" => crate::tui::theme::Theme::dark(),
            "light" => crate::tui::theme::Theme::light(),
            "solarized-dark" => crate::tui::theme::Theme::solarized_dark(),
            "solarized-light" => crate::tui::theme::Theme::solarized_light(),
            _ => {
                // Log warning and fallback to marketing theme
                tracing::warn!(theme = %self.ui.theme, "Unknown theme name, falling back to marketing");
                crate::tui::theme::Theme::marketing()
            }
        }
    }

    /// Apply environment variable overrides
    fn apply_env(&mut self) {
        if let Ok(val) = std::env::var("CODETETHER_DEFAULT_MODEL") {
            self.default_model = Some(val);
        }
        if let Ok(val) = std::env::var("CODETETHER_DEFAULT_PROVIDER") {
            self.default_provider = Some(val);
        }
        if let Ok(val) = std::env::var("OPENAI_API_KEY") {
            self.providers
                .entry("openai".to_string())
                .or_default()
                .api_key = Some(val);
        }
        if let Ok(val) = std::env::var("ANTHROPIC_API_KEY") {
            self.providers
                .entry("anthropic".to_string())
                .or_default()
                .api_key = Some(val);
        }
        if let Ok(val) = std::env::var("GOOGLE_API_KEY") {
            self.providers
                .entry("google".to_string())
                .or_default()
                .api_key = Some(val);
        }
        if let Ok(val) = std::env::var("CODETETHER_A2A_SERVER") {
            self.a2a.server_url = Some(val);
        }
        if let Ok(val) = std::env::var("CODETETHER_CRASH_REPORTING") {
            match parse_bool(&val) {
                Ok(enabled) => self.telemetry.crash_reporting = Some(enabled),
                Err(_) => tracing::warn!(
                    value = %val,
                    "Invalid CODETETHER_CRASH_REPORTING value; expected true/false"
                ),
            }
        }
        if let Ok(val) = std::env::var("CODETETHER_CRASH_REPORT_ENDPOINT") {
            self.telemetry.crash_report_endpoint = Some(val);
        }
    }

    /// Normalize legacy provider/model defaults from older releases.
    ///
    /// Historical versions defaulted to Moonshot Kimi K2.5. The current
    /// product default is Z.AI GLM-5, so we migrate only known legacy default
    /// values while preserving all other explicit user choices.
    fn normalize_legacy_defaults(&mut self) {
        if let Some(provider) = self.default_provider.as_deref()
            && provider.trim().eq_ignore_ascii_case("zhipuai")
        {
            self.default_provider = Some("zai".to_string());
        }

        if let Some(model) = self.default_model.as_deref() {
            let model_trimmed = model.trim();

            if model_trimmed.eq_ignore_ascii_case("zhipuai/glm-5") {
                self.default_model = Some("zai/glm-5".to_string());
                return;
            }

            let is_legacy_kimi_default = model_trimmed.eq_ignore_ascii_case("moonshotai/kimi-k2.5")
                || model_trimmed.eq_ignore_ascii_case("kimi-k2.5");

            if is_legacy_kimi_default {
                tracing::info!(
                    from = %model_trimmed,
                    to = "zai/glm-5",
                    "Migrating legacy default model to current Z.AI GLM-5 default"
                );
                self.default_model = Some("zai/glm-5".to_string());

                let should_update_provider = self.default_provider.as_deref().is_none_or(|p| {
                    let p = p.trim();
                    p.eq_ignore_ascii_case("moonshotai") || p.eq_ignore_ascii_case("zhipuai")
                });
                if should_update_provider {
                    self.default_provider = Some("zai".to_string());
                }
            }
        }
    }
}

fn parse_bool(value: &str) -> Result<bool> {
    let normalized = value.trim().to_ascii_lowercase();
    match normalized.as_str() {
        "1" | "true" | "yes" | "on" => Ok(true),
        "0" | "false" | "no" | "off" => Ok(false),
        _ => anyhow::bail!("Invalid boolean value: {}", value),
    }
}

fn workspace_data_dir() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    Some(workspace_data_dir_from(&cwd))
}

fn workspace_data_dir_from(start: &Path) -> PathBuf {
    detect_workspace_root(start)
        .unwrap_or_else(|| start.to_path_buf())
        .join(".codetether-agent")
}

fn detect_workspace_root(start: &Path) -> Option<PathBuf> {
    start
        .ancestors()
        .find(|path| path.join(".git").exists())
        .map(Path::to_path_buf)
}

#[cfg(test)]
mod tests {
    use super::Config;
    use super::{detect_workspace_root, workspace_data_dir_from};
    use tempfile::tempdir;

    #[test]
    fn migrates_legacy_kimi_default_to_zai_glm5() {
        let mut cfg = Config {
            default_provider: Some("moonshotai".to_string()),
            default_model: Some("moonshotai/kimi-k2.5".to_string()),
            ..Default::default()
        };

        cfg.normalize_legacy_defaults();

        assert_eq!(cfg.default_provider.as_deref(), Some("zai"));
        assert_eq!(cfg.default_model.as_deref(), Some("zai/glm-5"));
    }

    #[test]
    fn preserves_explicit_non_legacy_default_model() {
        let mut cfg = Config {
            default_provider: Some("openai".to_string()),
            default_model: Some("openai/gpt-4o".to_string()),
            ..Default::default()
        };

        cfg.normalize_legacy_defaults();

        assert_eq!(cfg.default_provider.as_deref(), Some("openai"));
        assert_eq!(cfg.default_model.as_deref(), Some("openai/gpt-4o"));
    }

    #[test]
    fn normalizes_zhipuai_aliases_to_zai() {
        let mut cfg = Config {
            default_provider: Some("zhipuai".to_string()),
            default_model: Some("zhipuai/glm-5".to_string()),
            ..Default::default()
        };

        cfg.normalize_legacy_defaults();

        assert_eq!(cfg.default_provider.as_deref(), Some("zai"));
        assert_eq!(cfg.default_model.as_deref(), Some("zai/glm-5"));
    }

    #[test]
    fn detects_workspace_root_using_git_marker() {
        let temp = tempdir().expect("tempdir");
        let repo_root = temp.path().join("repo");
        std::fs::create_dir_all(repo_root.join(".git")).expect("create .git");
        let nested = repo_root.join("src").join("nested");
        std::fs::create_dir_all(&nested).expect("create nested");

        let detected = detect_workspace_root(&nested);
        assert_eq!(detected.as_deref(), Some(repo_root.as_path()));
    }

    #[test]
    fn workspace_data_dir_defaults_to_workspace_root() {
        let temp = tempdir().expect("tempdir");
        let repo_root = temp.path().join("repo");
        std::fs::create_dir_all(repo_root.join(".git")).expect("create .git");
        let nested = repo_root.join("api").join("src");
        std::fs::create_dir_all(&nested).expect("create nested");

        let data_dir = workspace_data_dir_from(&nested);
        assert_eq!(data_dir, repo_root.join(".codetether-agent"));
    }

    #[test]
    fn workspace_data_dir_falls_back_to_start_when_not_git_repo() {
        let temp = tempdir().expect("tempdir");
        let workspace = temp.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("create workspace");

        let data_dir = workspace_data_dir_from(&workspace);
        assert_eq!(data_dir, workspace.join(".codetether-agent"));
    }
}