Skip to main content

codewhale_runtime/
config_persistence.rs

1//! Config file path resolution and TOML persistence helpers.
2//!
3//! These helpers are used by command handlers and non-command UI code, so
4//! persistence lives outside the command tree.
5//!
6//! Every `config.toml` mutation funnels through [`mutate_config_document`]:
7//! the file is edited in place with `toml_edit` so unrelated comments,
8//! ordering, and formatting survive, and the result is replaced atomically
9//! (same-directory temp file + rename) with owner-only permissions.
10
11use std::path::{Path, PathBuf};
12
13use anyhow::Context;
14
15use crate::config::{ProviderIdentity, StatusItem, expand_path};
16use codewhale_config::ProviderKind;
17
18/// Parse the TOML document at `path` (an absent or empty file yields an empty
19/// document), apply `mutate`, and atomically persist the result.
20///
21/// This is the single write path for TUI config mutations: `toml_edit` keeps
22/// user comments and formatting intact, and the temp-file + rename write can
23/// never leave a half-written config behind.
24pub fn mutate_config_document<F>(path: &Path, mutate: F) -> anyhow::Result<()>
25where
26    F: FnOnce(&mut toml_edit::DocumentMut) -> anyhow::Result<()>,
27{
28    mutate_config_document_with_migration(path, |doc, _| mutate(doc))
29}
30
31/// [`mutate_config_document`], also handing `mutate` the receipt of the legacy
32/// top-level `base_url` / `api_key` move this same write made (#6394).
33pub(crate) fn mutate_config_document_with_migration<F>(path: &Path, mutate: F) -> anyhow::Result<()>
34where
35    F: FnOnce(
36        &mut toml_edit::DocumentMut,
37        &codewhale_config::legacy_root::LegacyRootMigration,
38    ) -> anyhow::Result<()>,
39{
40    codewhale_config::mutate_config_document_with_migration(path, |doc, moved| {
41        migrate_legacy_route_preferences(path, doc)?;
42        mutate(doc, moved)
43    })
44}
45
46/// Commit the legacy effective startup selection with its receipt in the same
47/// atomic config write. Settings remains untouched, so an interrupted cleanup
48/// or an older binary cannot erase the user's historical choices. After this
49/// marker, Config never consults those legacy route fields again.
50pub fn migrate_legacy_route_preferences(
51    path: &Path,
52    doc: &mut toml_edit::DocumentMut,
53) -> anyhow::Result<()> {
54    if !crate::config::is_home_config_path(path)
55        || doc
56            .get("route_preferences_version")
57            .and_then(toml_edit::Item::as_integer)
58            .is_some()
59    {
60        return Ok(());
61    }
62    let mut config = crate::config::parse_config_base(&doc.to_string()).map_err(|_| {
63        anyhow::anyhow!(
64            "Could not parse configuration for route preference migration; contents omitted"
65        )
66    })?;
67    let previous_config = config.clone();
68    let settings =
69        crate::settings::Settings::load_legacy_route_preferences_read_only().map_err(|_| {
70            anyhow::anyhow!(
71                "Could not read legacy route preferences; configuration was not changed"
72            )
73        })?;
74    // An unparsable settings.toml loads as defaults carrying `load_error`, which
75    // keeps the UI usable but is not evidence that no preferences were saved.
76    // This migration is one-way: stamping the version over defaults would retire
77    // the user's real legacy choices unread. Refuse instead, exactly as
78    // `Settings::save_to_path` refuses to overwrite an unreadable document.
79    // Contents stay omitted; the file may hold private text.
80    anyhow::ensure!(
81        settings.load_error.is_none(),
82        "Could not read legacy route preferences; configuration was not changed"
83    );
84    if let Some(provider) = settings
85        .default_provider
86        .as_deref()
87        .filter(|provider| !provider.trim().is_empty())
88    {
89        let identity = config.resolve_provider_identity(provider).map_err(|_| anyhow::anyhow!("Legacy saved provider is unavailable in this configuration; route preference migration did not change files"))?;
90        let mut scoped = config.clone();
91        scoped.scope_to_provider_identity(&identity).map_err(|_| anyhow::anyhow!("Legacy saved provider cannot be selected from this configuration; route preference migration did not change files"))?;
92    }
93    config.apply_saved_selection(&settings);
94    if let Some(models) = &settings.provider_models {
95        for (provider, model) in models {
96            let model = model.trim();
97            if model.is_empty() || model.chars().any(char::is_control) {
98                continue;
99            }
100            let identity = config.legacy_selection_identity(provider).map_err(|_| anyhow::anyhow!("Legacy saved model refers to an unavailable provider; route preference migration did not change files"))?;
101            let mut scoped = config.clone();
102            scoped.scope_to_provider_identity(&identity).map_err(|_| anyhow::anyhow!("Legacy saved model provider cannot be selected from this configuration; route preference migration did not change files"))?;
103        }
104    }
105    let active_identity = config.active_provider_identity().ok();
106    let selector = active_identity
107        .as_ref()
108        .and_then(|identity| {
109            identity
110                .migrated_legacy_ollama_cloud_route
111                .then(|| identity.persisted_id())
112                .flatten()
113        })
114        .or(config.provider.as_deref());
115    if let Some(provider) = selector {
116        if previous_config.provider.as_deref() != Some(provider)
117            && let Some(previous) = previous_config.provider.as_deref()
118        {
119            set_document_value(
120                doc,
121                &["route_preferences_migration", "previous_provider"],
122                previous,
123            )?;
124        }
125        set_document_value(doc, &["provider"], provider)?;
126    }
127    let mut providers: Vec<&str> = settings
128        .provider_models
129        .as_ref()
130        .map(|models| models.keys().map(String::as_str).collect())
131        .unwrap_or_default();
132    if settings.default_model.is_some() {
133        for provider in [
134            ProviderKind::Deepseek.as_str(),
135            codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id,
136        ] {
137            if !providers.contains(&provider) {
138                providers.push(provider);
139            }
140        }
141    }
142    providers.sort_unstable();
143    for provider in providers {
144        let Ok(identity) = config.legacy_selection_identity(provider) else {
145            continue;
146        };
147        let mut scoped = config.clone();
148        scoped
149            .scope_to_provider_identity(&identity)
150            .map_err(anyhow::Error::msg)?;
151        let model =
152            if identity.provider == ProviderKind::Custom && identity.persisted_id().is_none() {
153                scoped.default_text_model.as_deref()
154            } else {
155                scoped
156                    .provider_config_for(&identity)
157                    .and_then(|entry| entry.model.as_deref())
158            };
159        if let Some(model) = model {
160            let mut previous = previous_config.clone();
161            previous
162                .scope_to_provider_identity(&identity)
163                .map_err(anyhow::Error::msg)?;
164            if let Some(old_model) = previous
165                .provider_config_for(&identity)
166                .and_then(|entry| entry.model.as_deref())
167                .or_else(|| {
168                    (previous_config.active_provider_identity().ok().as_ref() == Some(&identity))
169                        .then_some(previous_config.default_text_model.as_deref())
170                        .flatten()
171                })
172                && old_model != model
173            {
174                // Keep the displaced Config choice as an inert migration
175                // receipt. Nothing resolves routes from this archive.
176                set_document_value(
177                    doc,
178                    &[
179                        "route_preferences_migration",
180                        "previous_models",
181                        identity.key.as_str(),
182                    ],
183                    old_model,
184                )?;
185            }
186            set_verified_provider_model_document(doc, &config, &identity, model)?;
187        }
188    }
189    set_document_value(doc, &["route_preferences_version"], 1_i64)
190}
191
192// `config` is the freshly parsed same-lock document, before any intended delta.
193// Reuse that projection so a root receipt is not dropped by a second parse of
194// the canonicalized document. Every path verifies before writing the delta.
195pub fn set_verified_provider_model_document(
196    doc: &mut toml_edit::DocumentMut,
197    config: &crate::config::Config,
198    identity: &ProviderIdentity,
199    model: &str,
200) -> anyhow::Result<()> {
201    anyhow::ensure!(
202        !model.trim().is_empty() && !model.chars().any(char::is_control),
203        "model must be nonempty and contain no control characters"
204    );
205    config
206        .verify_provider_identity(identity)
207        .map_err(anyhow::Error::msg)?;
208    let provider_key = identity.config_table_key()?;
209    set_document_value(doc, &["providers", provider_key, "model"], model)
210}
211
212/// Atomically replace `path` with `body` via a same-directory temp file and
213/// rename. On Unix the file lands with 0o600 permissions: config.toml can
214/// hold API keys, so this matches `ConfigStore::save` and the auth save path.
215pub(crate) fn write_config_toml_atomic(path: &Path, body: &str) -> anyhow::Result<()> {
216    codewhale_config::create_config_document(path, body)
217}
218
219/// Set the value at `segments` (parent tables plus the final key), creating
220/// missing intermediate tables. Replacing an existing value keeps its decor,
221/// so comments above the key and trailing same-line comments survive.
222///
223/// Segments are separate strings rather than one dotted key, so table names
224/// that need quoting (`[providers."my.provider"]`) resolve correctly.
225pub fn set_document_value(
226    doc: &mut toml_edit::DocumentMut,
227    segments: &[&str],
228    value: impl Into<toml_edit::Value>,
229) -> anyhow::Result<()> {
230    codewhale_config::set_config_document_value(doc, segments, value)
231}
232
233/// Remove the value at `segments`. Returns `Ok(true)` when an entry was
234/// removed; missing keys and missing (or non-table) parents are a no-op.
235pub fn unset_document_value(
236    doc: &mut toml_edit::DocumentMut,
237    segments: &[&str],
238) -> anyhow::Result<bool> {
239    codewhale_config::unset_config_document_value(doc, segments)
240}
241
242/// Remove every entry named `key` from `table` and, recursively, from nested
243/// tables, inline tables, and arrays of tables. Used by `/logout` to strip
244/// `api_key` everywhere without disturbing keys like `api_key_env`.
245pub(crate) fn remove_document_key_recursive(table: &mut dyn toml_edit::TableLike, key: &str) {
246    remove_key_preserving_leading_decor(table, key);
247    for (_, item) in table.iter_mut() {
248        if let toml_edit::Item::ArrayOfTables(tables) = item {
249            for nested in tables.iter_mut() {
250                remove_document_key_recursive(nested, key);
251            }
252        } else if let Some(nested) = item.as_table_like_mut() {
253            remove_document_key_recursive(nested, key);
254        }
255    }
256}
257
258fn remove_key_preserving_leading_decor(table: &mut dyn toml_edit::TableLike, key: &str) -> bool {
259    let mut found = false;
260    let next_key = table.iter().find_map(|(candidate, _)| {
261        if found {
262            Some(candidate.to_owned())
263        } else {
264            found = candidate == key;
265            None
266        }
267    });
268    let leading_prefix = leading_prefix_for_key(table, key);
269    if table.remove(key).is_none() {
270        return false;
271    }
272    let Some(prefix) = leading_prefix else {
273        return true;
274    };
275    let Some(next_key) = next_key else {
276        return true;
277    };
278    if prefix.as_str() == Some("") {
279        return true;
280    }
281    if let Some(mut next_key_decor) = table.key_mut(&next_key)
282        && decor_prefix_is_empty(next_key_decor.leaf_decor())
283    {
284        next_key_decor.leaf_decor_mut().set_prefix(prefix);
285    }
286    true
287}
288
289fn decor_prefix_is_empty(decor: &toml_edit::Decor) -> bool {
290    match decor.prefix() {
291        Some(prefix) => prefix.as_str() == Some(""),
292        None => true,
293    }
294}
295
296fn leading_prefix_for_key(
297    table: &dyn toml_edit::TableLike,
298    key: &str,
299) -> Option<toml_edit::RawString> {
300    table
301        .key(key)
302        .and_then(|key| key.leaf_decor().prefix().cloned())
303        .or_else(|| {
304            table
305                .get(key)
306                .and_then(|item| item.as_value())
307                .and_then(|value| value.decor().prefix().cloned())
308        })
309}
310
311pub fn persist_status_items(items: &[StatusItem]) -> anyhow::Result<PathBuf> {
312    let path = config_toml_path(None)?;
313    let items: toml_edit::Array = items.iter().map(|item| item.key()).collect();
314    mutate_config_document(&path, |doc| {
315        set_document_value(doc, &["tui", "status_items"], items)
316    })?;
317    Ok(path)
318}
319
320pub fn persist_root_string_key(
321    config_path: Option<&Path>,
322    key: &str,
323    value: &str,
324) -> anyhow::Result<PathBuf> {
325    let path = config_toml_path(config_path)?;
326    mutate_config_document(&path, |doc| set_document_value(doc, &[key], value))?;
327    Ok(path)
328}
329
330pub fn persist_unset_root_key(config_path: Option<&Path>, key: &str) -> anyhow::Result<PathBuf> {
331    let path = config_toml_path(config_path)?;
332    mutate_config_document(&path, |doc| unset_document_value(doc, &[key]).map(|_| ()))?;
333    Ok(path)
334}
335
336pub fn persist_unset_table_key(
337    config_path: Option<&Path>,
338    table_name: &str,
339    key: &str,
340) -> anyhow::Result<PathBuf> {
341    let path = config_toml_path(config_path)?;
342    mutate_config_document(&path, |doc| {
343        unset_document_value(doc, &[table_name, key]).map(|_| ())
344    })?;
345    Ok(path)
346}
347
348pub fn persist_root_bool_key(
349    config_path: Option<&Path>,
350    key: &str,
351    value: bool,
352) -> anyhow::Result<PathBuf> {
353    let path = config_toml_path(config_path)?;
354    mutate_config_document(&path, |doc| set_document_value(doc, &[key], value))?;
355    Ok(path)
356}
357
358pub fn persist_subagents_bool_key(
359    config_path: Option<&Path>,
360    key: &str,
361    value: bool,
362) -> anyhow::Result<PathBuf> {
363    persist_table_value_key(config_path, "subagents", key, value.into())
364}
365
366pub fn persist_mini_window_bool_key(
367    config_path: Option<&Path>,
368    key: &str,
369    value: bool,
370) -> anyhow::Result<PathBuf> {
371    persist_table_value_key(config_path, "mini_window", key, value.into())
372}
373
374pub fn persist_subagents_integer_key(
375    config_path: Option<&Path>,
376    key: &str,
377    value: u64,
378) -> anyhow::Result<PathBuf> {
379    let value = i64::try_from(value).context("integer value is too large for TOML")?;
380    persist_table_value_key(config_path, "subagents", key, value.into())
381}
382
383pub fn persist_table_bool_key(
384    config_path: Option<&Path>,
385    table_name: &str,
386    key: &str,
387    value: bool,
388) -> anyhow::Result<PathBuf> {
389    persist_table_value_key(config_path, table_name, key, value.into())
390}
391
392pub fn persist_table_string_key(
393    config_path: Option<&Path>,
394    table_name: &str,
395    key: &str,
396    value: &str,
397) -> anyhow::Result<PathBuf> {
398    persist_table_value_key(config_path, table_name, key, value.into())
399}
400
401pub fn persist_table_value_key(
402    config_path: Option<&Path>,
403    table_name: &str,
404    key: &str,
405    value: toml_edit::Value,
406) -> anyhow::Result<PathBuf> {
407    let path = config_toml_path(config_path)?;
408    mutate_config_document(&path, |doc| {
409        set_document_value(doc, &[table_name, key], value)
410    })?;
411    Ok(path)
412}
413
414/// Persist the endpoint that `GET /v1/config` reports as `base_url`.
415///
416/// That value belongs to exactly one route, and the route keeps it in exactly
417/// one place: its own `[providers.<table>]` table — the typed table for a
418/// built-in, the exact `[providers.<name>]` table for a custom route. There is
419/// no top-level `base_url` any more (#6394); writing one used to hand a
420/// DeepSeek endpoint to every route that inherited it.
421pub fn persist_route_base_url(
422    config_path: Option<&Path>,
423    identity: &ProviderIdentity,
424    value: &str,
425) -> anyhow::Result<PathBuf> {
426    let path = config_toml_path(config_path)?;
427    mutate_config_document_with_migration(&path, |doc, moved| {
428        let config = crate::config::parse_config_after_locked_migration(&doc.to_string(), moved)
429            .map_err(|_| anyhow::anyhow!("Could not parse destination route; contents omitted"))?;
430        config
431            .verify_provider_identity(identity)
432            .map_err(anyhow::Error::msg)?;
433        let table = if identity.provider == ProviderKind::Custom {
434            identity.key.as_str()
435        } else {
436            provider_base_url_table_key(identity)?
437        };
438        set_document_value(doc, &["providers", table, "base_url"], value)
439    })?;
440    Ok(path)
441}
442
443/// Persist the model for one exact provider route without rewriting the
444/// legacy root DeepSeek fallback used by unrelated providers.
445///
446/// Built-in providers write to their typed `[providers.<name>]` table, while
447/// named custom routes use their exact user-owned table id. The locked writer first preserves legacy root provenance, then writes the
448/// canonical leaf created by its one-way migration.
449pub fn persist_provider_model_key(
450    config_path: Option<&Path>,
451    identity: &ProviderIdentity,
452    value: &str,
453) -> anyhow::Result<PathBuf> {
454    let path = config_toml_path(config_path)?;
455    mutate_config_document_with_migration(&path, |doc, moved| {
456        let config = crate::config::parse_config_after_locked_migration(&doc.to_string(), moved)
457            .map_err(|_| anyhow::anyhow!("Could not parse destination route; contents omitted"))?;
458        set_verified_provider_model_document(doc, &config, identity, value)
459    })?;
460    Ok(path)
461}
462
463fn provider_base_url_table_key(identity: &ProviderIdentity) -> anyhow::Result<&'static str> {
464    identity
465        .compatibility()
466        .map(|row| row.base_url_config_key)
467        .context("custom providers store base_url in their named [providers.<name>] table")
468}
469
470pub fn persist_custom_provider(
471    config_path: Option<&Path>,
472    provider_id: &str,
473    base_url: &str,
474    model: Option<&str>,
475    api_key_env: Option<&str>,
476) -> anyhow::Result<PathBuf> {
477    let provider_id = normalize_custom_provider_id(provider_id)?;
478    let base_url = normalize_custom_provider_base_url(base_url)?;
479    let model = model.and_then(normalize_optional_custom_provider_field);
480    let api_key_env = api_key_env.and_then(normalize_optional_custom_provider_field);
481
482    let path = config_toml_path(config_path)?;
483    mutate_config_document(&path, |doc| {
484        let entry = ["providers", provider_id.as_str()];
485        set_document_value(doc, &["provider"], provider_id.as_str())?;
486        set_document_value(doc, &[entry[0], entry[1], "kind"], "openai-compatible")?;
487        set_document_value(doc, &[entry[0], entry[1], "base_url"], base_url.as_str())?;
488        if provider_id == "ds4" && crate::config::base_url_uses_local_host(&base_url) {
489            // Match the documented starter server. DS4 explicitly requires
490            // clients not to budget beyond the server's --ctx value.
491            set_document_value(doc, &[entry[0], entry[1], "context_window"], 100_000)?;
492        }
493        match model.as_deref() {
494            Some(model) => set_document_value(doc, &[entry[0], entry[1], "model"], model)?,
495            None => {
496                unset_document_value(doc, &[entry[0], entry[1], "model"])?;
497            }
498        }
499        match api_key_env.as_deref() {
500            Some(env) => {
501                set_document_value(doc, &[entry[0], entry[1], "api_key_env"], env)?;
502                unset_document_value(doc, &[entry[0], entry[1], "auth_mode"])?;
503            }
504            None => {
505                unset_document_value(doc, &[entry[0], entry[1], "api_key_env"])?;
506                if provider_id == "ds4" && crate::config::base_url_uses_local_host(&base_url) {
507                    set_document_value(doc, &[entry[0], entry[1], "auth_mode"], "none")?;
508                } else {
509                    unset_document_value(doc, &[entry[0], entry[1], "auth_mode"])?;
510                }
511            }
512        }
513        Ok(())
514    })?;
515    Ok(path)
516}
517
518fn normalize_custom_provider_id(raw: &str) -> anyhow::Result<String> {
519    use anyhow::bail;
520
521    let value = raw.trim();
522    if value.is_empty() {
523        bail!("custom provider name is required");
524    }
525    if value == "__custom__" {
526        bail!("custom provider name is reserved");
527    }
528    if codewhale_config::ProviderKind::parse(value).is_some() {
529        bail!("custom provider name must not shadow a built-in provider");
530    }
531    if !value
532        .chars()
533        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-'))
534    {
535        bail!("custom provider name may only use letters, numbers, '-' and '_'");
536    }
537    Ok(value.to_string())
538}
539
540fn normalize_custom_provider_base_url(raw: &str) -> anyhow::Result<String> {
541    use anyhow::bail;
542
543    let value = raw.trim().trim_end_matches('/');
544    if value.is_empty() {
545        bail!("custom provider base URL is required");
546    }
547    let parsed = reqwest::Url::parse(value)
548        .map_err(|err| anyhow::anyhow!("custom provider base URL is invalid: {err}"))?;
549    if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
550        bail!("custom provider base URL must be an http(s) URL with a host");
551    }
552    Ok(value.to_string())
553}
554
555fn normalize_optional_custom_provider_field(raw: &str) -> Option<String> {
556    let value = raw.trim();
557    (!value.is_empty()).then(|| value.to_string())
558}
559
560pub fn persist_hotbar_bindings(
561    config_path: Option<&Path>,
562    bindings: &[codewhale_config::HotbarBindingToml],
563) -> anyhow::Result<PathBuf> {
564    let path = config_toml_path(config_path)?;
565    mutate_config_document(&path, |doc| {
566        let table = doc.as_table_mut();
567        table.remove("hotbar");
568        if bindings.is_empty() {
569            table.insert(
570                "hotbar",
571                toml_edit::Item::Value(toml_edit::Value::Array(toml_edit::Array::new())),
572            );
573        } else {
574            let mut hotbar = toml_edit::ArrayOfTables::new();
575            for binding in bindings {
576                let mut entry = toml_edit::Table::new();
577                entry["slot"] = toml_edit::value(i64::from(binding.slot));
578                entry["action"] = toml_edit::value(binding.action.clone());
579                if let Some(label) = binding.label.as_deref() {
580                    entry["label"] = toml_edit::value(label);
581                }
582                hotbar.push(entry);
583            }
584            table.insert("hotbar", toml_edit::Item::ArrayOfTables(hotbar));
585        }
586        Ok(())
587    })?;
588    Ok(path)
589}
590
591pub fn config_toml_path(config_path: Option<&Path>) -> anyhow::Result<PathBuf> {
592    if let Some(path) = config_path {
593        return Ok(expand_path(path.to_string_lossy().as_ref()));
594    }
595    crate::config::resolve_load_config_path(None)?
596        .context("failed to resolve the active config.toml path")
597}
598
599#[cfg(test)]
600mod tests {
601
602    use super::*;
603
604    use std::env;
605
606    use std::fs;
607
608    use std::path::Path;
609
610    use super::test_support::*;
611
612    struct EnvGuard {
613        _home: crate::test_support::EnvVarGuard,
614        _userprofile: crate::test_support::EnvVarGuard,
615        _codewhale_home: crate::test_support::EnvVarGuard,
616        _codewhale_config_path: crate::test_support::EnvVarGuard,
617        _deepseek_config_path: crate::test_support::EnvVarGuard,
618        _lock: crate::test_support::TestEnvLock,
619    }
620
621    impl EnvGuard {
622        fn new(home: &Path) -> Self {
623            let lock = crate::test_support::lock_test_env();
624            let config_path = home.join(".deepseek").join("config.toml");
625            Self {
626                _home: crate::test_support::EnvVarGuard::set("HOME", home),
627                _userprofile: crate::test_support::EnvVarGuard::set("USERPROFILE", home),
628                _codewhale_home: crate::test_support::EnvVarGuard::remove("CODEWHALE_HOME"),
629                _codewhale_config_path: crate::test_support::EnvVarGuard::remove(
630                    "CODEWHALE_CONFIG_PATH",
631                ),
632                _deepseek_config_path: crate::test_support::EnvVarGuard::set(
633                    "DEEPSEEK_CONFIG_PATH",
634                    &config_path,
635                ),
636                _lock: lock,
637            }
638        }
639    }
640
641    fn temp_root(prefix: &str) -> std::path::PathBuf {
642        crate::test_support::test_scratch_dir(prefix)
643    }
644
645    #[test]
646    fn persist_status_items_writes_tui_section_to_config_toml() {
647        let temp_root = temp_root("codewhale-statusline-persist");
648        fs::create_dir_all(&temp_root).unwrap();
649        let _guard = EnvGuard::new(&temp_root);
650
651        let items = vec![
652            crate::config::StatusItem::Mode,
653            crate::config::StatusItem::Model,
654            crate::config::StatusItem::Cost,
655        ];
656
657        let path = persist_status_items(&items).expect("persist should succeed");
658        let body = fs::read_to_string(&path).expect("written file should be readable");
659        assert!(body.contains("[tui]"), "expected [tui] section in {body}");
660        assert!(
661            body.contains("status_items"),
662            "expected status_items key in {body}"
663        );
664        assert!(body.contains("\"mode\""), "expected mode key in {body}");
665        assert!(body.contains("\"cost\""), "expected cost key in {body}");
666    }
667
668    #[test]
669    fn config_toml_path_uses_codewhale_home_for_fresh_installs() {
670        let temp_root = temp_root("codewhale-config-path-fresh");
671        fs::create_dir_all(&temp_root).unwrap();
672        let _guard = EnvGuard::new(&temp_root);
673
674        unsafe {
675            env::remove_var("DEEPSEEK_CONFIG_PATH");
676        }
677
678        assert_eq!(
679            config_toml_path(None).unwrap(),
680            temp_root.join(".codewhale").join("config.toml")
681        );
682    }
683
684    #[test]
685    fn config_toml_path_preserves_legacy_config_when_it_exists() {
686        let temp_root = temp_root("codewhale-config-path-legacy");
687        let legacy_config = temp_root.join(".deepseek").join("config.toml");
688        fs::create_dir_all(legacy_config.parent().unwrap()).unwrap();
689        fs::write(&legacy_config, "").unwrap();
690        let _guard = EnvGuard::new(&temp_root);
691
692        unsafe {
693            env::remove_var("DEEPSEEK_CONFIG_PATH");
694        }
695
696        assert_eq!(config_toml_path(None).unwrap(), legacy_config);
697    }
698
699    #[test]
700    fn config_toml_path_ignores_legacy_config_when_codewhale_home_is_explicit() {
701        let temp_root = temp_root("codewhale-config-path-explicit-home");
702        let explicit_home = temp_root.join("isolated-codewhale");
703        let legacy_config = temp_root.join(".deepseek").join("config.toml");
704        fs::create_dir_all(legacy_config.parent().unwrap()).unwrap();
705        fs::write(&legacy_config, "").unwrap();
706        let _guard = EnvGuard::new(&temp_root);
707
708        unsafe {
709            env::remove_var("DEEPSEEK_CONFIG_PATH");
710            env::set_var("CODEWHALE_HOME", &explicit_home);
711        }
712
713        assert_eq!(
714            config_toml_path(None).unwrap(),
715            explicit_home.join("config.toml")
716        );
717    }
718
719    #[test]
720    fn config_toml_path_prefers_codewhale_env_over_legacy_env() {
721        let temp_root = temp_root("codewhale-config-path-env");
722        fs::create_dir_all(&temp_root).unwrap();
723        let _guard = EnvGuard::new(&temp_root);
724        let preferred = temp_root.join("preferred.toml");
725        let legacy = temp_root.join("legacy.toml");
726
727        unsafe {
728            env::set_var("CODEWHALE_CONFIG_PATH", &preferred);
729            env::set_var("DEEPSEEK_CONFIG_PATH", &legacy);
730        }
731
732        let expected = preferred
733            .parent()
734            .expect("preferred path has a parent")
735            .canonicalize()
736            .expect("preferred parent should canonicalize")
737            .join("preferred.toml");
738        assert_eq!(config_toml_path(None).unwrap(), expected);
739    }
740
741    #[test]
742    fn config_toml_path_keeps_missing_env_target_authoritative() {
743        let temp_root = temp_root("codewhale-config-path-missing-env-fallback");
744        let home_config = temp_root.join(".codewhale").join("config.toml");
745        fs::create_dir_all(home_config.parent().unwrap()).unwrap();
746        fs::write(&home_config, "# existing fallback\n").unwrap();
747        let _guard = EnvGuard::new(&temp_root);
748        let missing_env = temp_root.join("override").join("missing.toml");
749
750        unsafe {
751            env::set_var("DEEPSEEK_CONFIG_PATH", &missing_env);
752        }
753
754        assert_eq!(config_toml_path(None).unwrap(), missing_env);
755        assert!(home_config.exists());
756        assert!(!missing_env.exists());
757    }
758
759    #[test]
760    fn persist_status_items_preserves_existing_unrelated_keys() {
761        let temp_root = temp_root("codewhale-statusline-preserve");
762        fs::create_dir_all(&temp_root).unwrap();
763        let _guard = EnvGuard::new(&temp_root);
764
765        let path = temp_root.join(".deepseek").join("config.toml");
766        fs::create_dir_all(path.parent().unwrap()).unwrap();
767        fs::write(
768            &path,
769            "api_key = \"sentinel-key\"\nmodel = \"deepseek-v4-pro\"\n",
770        )
771        .unwrap();
772
773        let written = persist_status_items(&[crate::config::StatusItem::Mode])
774            .expect("persist should succeed");
775        let body = fs::read_to_string(&written).expect("written file should be readable");
776        assert!(
777            body.contains("api_key = \"sentinel-key\""),
778            "round-trip lost api_key: {body}"
779        );
780        assert!(
781            body.contains("model = \"deepseek-v4-pro\""),
782            "round-trip lost model: {body}"
783        );
784        assert!(
785            body.contains("status_items"),
786            "expected status_items in {body}"
787        );
788    }
789
790    #[test]
791    fn persist_bool_key_preserves_comments() {
792        let temp_root = temp_root("codewhale-persist-comments");
793        fs::create_dir_all(&temp_root).unwrap();
794        let _guard = EnvGuard::new(&temp_root);
795
796        let path = temp_root.join(".deepseek").join("config.toml");
797        fs::create_dir_all(path.parent().unwrap()).unwrap();
798        fs::write(
799            &path,
800            "# my note\nmodel = \"deepseek-v4-flash\"\n# disabled = true\n",
801        )
802        .unwrap();
803
804        let written = persist_root_bool_key(Some(&path), "allow_shell", true)
805            .expect("persist should succeed");
806        let body = fs::read_to_string(&written).expect("written file should be readable");
807        assert!(body.contains("# my note"), "prefix comment lost: {body}");
808        assert!(
809            body.contains("# disabled = true"),
810            "disabled key lost: {body}"
811        );
812        assert!(
813            body.contains("allow_shell = true"),
814            "new key not written: {body}"
815        );
816    }
817
818    #[test]
819    fn persist_table_bool_key_updates_existing_memory_enabled() {
820        let temp_root = temp_root("codewhale-persist-memory-update");
821        fs::create_dir_all(&temp_root).unwrap();
822        let _guard = EnvGuard::new(&temp_root);
823
824        let path = temp_root.join(".deepseek").join("config.toml");
825        fs::create_dir_all(path.parent().unwrap()).unwrap();
826        fs::write(&path, "allow_shell = true\n\n[memory]\nenabled = true\n").unwrap();
827
828        let written = persist_table_bool_key(Some(&path), "memory", "enabled", false)
829            .expect("persist should succeed");
830        let body = fs::read_to_string(&written).expect("written file should be readable");
831        assert!(
832            body.contains("enabled = false"),
833            "memory enabled should be false: {body}"
834        );
835        assert!(
836            !body.contains("enabled = true"),
837            "memory enabled should not still be true: {body}"
838        );
839    }
840
841    #[test]
842    fn persist_memory_enabled_round_trips_through_config_load() {
843        let temp_root = temp_root("codewhale-persist-memory-roundtrip");
844        fs::create_dir_all(&temp_root).unwrap();
845        let _guard = EnvGuard::new(&temp_root);
846
847        let path = temp_root.join(".deepseek").join("config.toml");
848        fs::create_dir_all(path.parent().unwrap()).unwrap();
849        // Initial config has memory enabled = true
850        fs::write(&path, "allow_shell = true\n\n[memory]\nenabled = true\n").unwrap();
851
852        // Verify initial state
853        let cfg0 = crate::config::Config::load(Some(path.clone()), None)
854            .expect("initial config should load");
855        assert!(cfg0.memory_enabled(), "memory should be enabled initially");
856
857        // Persist memory.enabled = false (what the GUI's set_config endpoint does)
858        persist_table_bool_key(Some(&path), "memory", "enabled", false)
859            .expect("persist should succeed");
860
861        // Reload config from disk and verify memory_enabled() reflects the change
862        let cfg1 = crate::config::Config::load(Some(path.clone()), None)
863            .expect("reloaded config should load");
864        assert!(
865            !cfg1.memory_enabled(),
866            "memory should be disabled after persisting false"
867        );
868    }
869
870    #[test]
871    fn persist_custom_provider_writes_named_openai_compatible_table() {
872        let temp_root = temp_root("codewhale-custom-provider-persist");
873        fs::create_dir_all(&temp_root).unwrap();
874        let _guard = EnvGuard::new(&temp_root);
875
876        let path = temp_root.join(".codewhale").join("config.toml");
877        let written = persist_custom_provider(
878            Some(&path),
879            "acme_ai",
880            "https://api.acme.example/v1/",
881            Some("acme/code-1"),
882            Some("ACME_API_KEY"),
883        )
884        .expect("custom provider should persist");
885        let body = fs::read_to_string(&written).expect("written file should be readable");
886
887        assert!(body.contains("provider = \"acme_ai\""), "{body}");
888        assert!(body.contains("[providers.acme_ai]"), "{body}");
889        assert!(body.contains("kind = \"openai-compatible\""), "{body}");
890        assert!(
891            body.contains("base_url = \"https://api.acme.example/v1\""),
892            "{body}"
893        );
894        assert!(body.contains("model = \"acme/code-1\""), "{body}");
895        assert!(body.contains("api_key_env = \"ACME_API_KEY\""), "{body}");
896        assert!(
897            !body.contains("sk-"),
898            "helper must not persist raw secret values: {body}"
899        );
900
901        let loaded =
902            crate::config::Config::load(Some(written.clone()), None).expect("config should load");
903        assert_eq!(loaded.provider.as_deref(), Some("acme_ai"));
904        assert_eq!(
905            loaded.active_provider_identity().unwrap().provider,
906            codewhale_config::ProviderKind::Custom
907        );
908        let entry = loaded
909            .providers
910            .as_ref()
911            .and_then(|providers| providers.custom_provider_config("acme_ai"))
912            .expect("custom provider entry");
913        assert!(entry.is_openai_compatible_custom());
914        assert_eq!(
915            entry.base_url.as_deref(),
916            Some("https://api.acme.example/v1")
917        );
918        assert_eq!(entry.model.as_deref(), Some("acme/code-1"));
919        assert_eq!(entry.api_key_env.as_deref(), Some("ACME_API_KEY"));
920
921        let dispatcher = codewhale_config::ConfigStore::load(Some(written))
922            .expect("the dispatcher must parse the exact config written by the TUI");
923        assert_eq!(
924            dispatcher.config.provider,
925            codewhale_config::ProviderKind::Custom
926        );
927        assert_eq!(dispatcher.config.provider_id(), "acme_ai");
928    }
929
930    #[test]
931    fn persist_custom_provider_rejects_builtin_or_invalid_names() {
932        let temp_root = temp_root("codewhale-custom-provider-invalid");
933        fs::create_dir_all(&temp_root).unwrap();
934        let _guard = EnvGuard::new(&temp_root);
935        let path = temp_root.join(".codewhale").join("config.toml");
936
937        let builtin = persist_custom_provider(
938            Some(&path),
939            "openrouter",
940            "https://api.example.invalid/v1",
941            None,
942            None,
943        )
944        .expect_err("built-in names should be rejected");
945        assert!(builtin.to_string().contains("built-in provider"));
946
947        let bad_chars = persist_custom_provider(
948            Some(&path),
949            "my provider",
950            "https://api.example.invalid/v1",
951            None,
952            None,
953        )
954        .expect_err("space in name should be rejected");
955        assert!(bad_chars.to_string().contains("letters, numbers"));
956    }
957
958    #[test]
959    fn persist_local_custom_provider_records_keyless_auth() {
960        let temp_root = temp_root("codewhale-custom-provider-local-keyless");
961        fs::create_dir_all(&temp_root).unwrap();
962        let _guard = EnvGuard::new(&temp_root);
963        let path = temp_root.join(".codewhale").join("config.toml");
964
965        let written = persist_custom_provider(
966            Some(&path),
967            "ds4",
968            "http://127.0.0.1:8000/v1",
969            Some("deepseek-v4-flash"),
970            None,
971        )
972        .expect("DS4 preset should persist");
973        let body = fs::read_to_string(&written).expect("written config");
974
975        assert!(body.contains("provider = \"ds4\""), "{body}");
976        assert!(body.contains("auth_mode = \"none\""), "{body}");
977        assert!(body.contains("context_window = 100000"), "{body}");
978        assert!(!body.contains("api_key"), "{body}");
979    }
980
981    #[test]
982    fn persist_hotbar_bindings_writes_primary_config_path_for_fresh_installs() {
983        let temp_root = temp_root("codewhale-hotbar-persist-fresh");
984        fs::create_dir_all(&temp_root).unwrap();
985        let _guard = EnvGuard::new(&temp_root);
986
987        unsafe {
988            env::remove_var("DEEPSEEK_CONFIG_PATH");
989        }
990
991        let bindings = vec![codewhale_config::HotbarBindingToml {
992            slot: 1,
993            action: "mode.plan".to_string(),
994            label: Some("Plan".to_string()),
995        }];
996        let path = persist_hotbar_bindings(None, &bindings).expect("persist should succeed");
997
998        assert_eq!(path, temp_root.join(".codewhale").join("config.toml"));
999        let body = fs::read_to_string(&path).expect("written file should be readable");
1000        assert!(body.contains("[[hotbar]]"), "hotbar table missing: {body}");
1001        let parsed: codewhale_config::ConfigToml =
1002            toml::from_str(&body).expect("written hotbar config should parse");
1003        assert_eq!(parsed.hotbar, Some(bindings));
1004    }
1005
1006    #[test]
1007    fn persist_default_hotbar_bindings_round_trips_for_hotbar_on() {
1008        // #3807: `/hotbar on` persists the explicit default slots (an absent key
1009        // now means hidden), and they read back as the eight recommended slots.
1010        let temp_root = temp_root("codewhale-hotbar-on-defaults");
1011        fs::create_dir_all(&temp_root).unwrap();
1012        let _guard = EnvGuard::new(&temp_root);
1013
1014        let defaults = codewhale_config::default_hotbar_bindings_toml();
1015        assert_eq!(defaults.len(), codewhale_config::HOTBAR_SLOT_COUNT as usize);
1016
1017        let path = persist_hotbar_bindings(None, &defaults).expect("persist should succeed");
1018        let body = fs::read_to_string(&path).expect("written file should be readable");
1019        assert!(body.contains("[[hotbar]]"), "hotbar table missing: {body}");
1020
1021        let parsed: codewhale_config::ConfigToml =
1022            toml::from_str(&body).expect("written hotbar config should parse");
1023        assert_eq!(parsed.hotbar, Some(defaults));
1024
1025        // The persisted defaults resolve back to all eight recommended slots.
1026        let resolved = parsed.resolve_hotbar_bindings(&codewhale_config::DEFAULT_HOTBAR_ACTIONS);
1027        assert_eq!(
1028            resolved.bindings,
1029            codewhale_config::default_hotbar_bindings()
1030        );
1031    }
1032
1033    #[test]
1034    fn persist_hotbar_bindings_preserves_comments_and_replaces_existing_tables() {
1035        let temp_root = temp_root("codewhale-hotbar-persist-comments");
1036        fs::create_dir_all(&temp_root).unwrap();
1037        let _guard = EnvGuard::new(&temp_root);
1038
1039        let path = temp_root.join(".codewhale").join("config.toml");
1040        fs::create_dir_all(path.parent().unwrap()).unwrap();
1041        fs::write(
1042            &path,
1043            r#"# model note
1044model = "deepseek-v4-flash"
1045
1046[[hotbar]]
1047slot = 1
1048action = "mode.plan"
1049label = "Plan"
1050
1051# notification note
1052[notifications]
1053enabled = true
1054"#,
1055        )
1056        .unwrap();
1057
1058        let bindings = vec![codewhale_config::HotbarBindingToml {
1059            slot: 2,
1060            action: "session.compact".to_string(),
1061            label: Some("Compact".to_string()),
1062        }];
1063        let written =
1064            persist_hotbar_bindings(Some(&path), &bindings).expect("persist should succeed");
1065        let body = fs::read_to_string(&written).expect("written file should be readable");
1066
1067        assert!(body.contains("# model note"), "prefix comment lost: {body}");
1068        assert!(
1069            body.contains("# notification note"),
1070            "section comment lost: {body}"
1071        );
1072        assert!(
1073            !body.contains("mode.plan"),
1074            "old hotbar table was not replaced: {body}"
1075        );
1076        assert!(body.contains("[[hotbar]]"), "hotbar table missing: {body}");
1077        assert!(
1078            body.contains("action = \"session.compact\""),
1079            "new action missing: {body}"
1080        );
1081        let parsed: codewhale_config::ConfigToml =
1082            toml::from_str(&body).expect("written hotbar config should parse");
1083        assert_eq!(parsed.hotbar, Some(bindings));
1084    }
1085
1086    #[test]
1087    fn persist_hotbar_bindings_writes_empty_array_to_disable_defaults() {
1088        let temp_root = temp_root("codewhale-hotbar-persist-empty");
1089        fs::create_dir_all(&temp_root).unwrap();
1090        let _guard = EnvGuard::new(&temp_root);
1091
1092        let path = temp_root.join(".codewhale").join("config.toml");
1093        fs::create_dir_all(path.parent().unwrap()).unwrap();
1094
1095        let written = persist_hotbar_bindings(Some(&path), &[]).expect("persist should succeed");
1096        let body = fs::read_to_string(&written).expect("written file should be readable");
1097
1098        assert!(body.contains("hotbar = []"), "empty hotbar missing: {body}");
1099        let parsed: codewhale_config::ConfigToml =
1100            toml::from_str(&body).expect("written hotbar config should parse");
1101        assert_eq!(parsed.hotbar, Some(Vec::new()));
1102    }
1103
1104    // ------------------------------------------------------------------
1105    // Golden-file coverage for the shared toml_edit mutation path
1106    // (findings #18/#19/#20): unrelated comments, ordering, and quoted
1107    // provider tables must survive every supported mutation.
1108    // ------------------------------------------------------------------
1109
1110    const GOLDEN_CONFIG: &str = r#"# CodeWhale golden config fixture, top note.
1111# api_key = "sk-placeholder" (uncomment to set the key by hand)
1112model = "deepseek-v4-pro" # pinned for release QA
1113
1114# workspace trust note
1115[projects."/Users/example/work"]
1116trust_level = "trusted" # granted manually
1117
1118# providers note
1119[providers.openrouter]
1120base_url = "https://openrouter.ai/api/v1" # keep in sync with docs
1121
1122[providers."quoted.provider"]
1123base_url = "https://quoted.example/v1"
1124
1125[[hotbar]]
1126slot = 1
1127action = "mode.plan"
1128"#;
1129
1130    fn write_golden_config(path: &Path) {
1131        fs::create_dir_all(path.parent().unwrap()).unwrap();
1132        fs::write(path, GOLDEN_CONFIG).unwrap();
1133    }
1134
1135    #[test]
1136    fn golden_replacing_existing_root_value_only_touches_that_value() {
1137        let temp_root = temp_root("codewhale-golden-root-value");
1138        fs::create_dir_all(&temp_root).unwrap();
1139        let _guard = EnvGuard::new(&temp_root);
1140        let path = temp_root.join(".deepseek").join("config.toml");
1141        write_golden_config(&path);
1142
1143        persist_root_string_key(Some(&path), "model", "deepseek-v4-flash")
1144            .expect("persist should succeed");
1145
1146        let body = fs::read_to_string(&path).unwrap();
1147        // The fixture is a pre-migration home config, so this first write also
1148        // commits the one-way route-preference migration receipt in the same
1149        // atomic replacement. That stamp and the model value are the only two
1150        // permitted edits: comments, ordering and quoted tables stay byte-exact.
1151        let expected = GOLDEN_CONFIG.replace(
1152            "model = \"deepseek-v4-pro\" # pinned for release QA",
1153            "model = \"deepseek-v4-flash\" # pinned for release QA\nroute_preferences_version = 1",
1154        );
1155        assert_eq!(
1156            body, expected,
1157            "only the model value and the migration stamp may change"
1158        );
1159    }
1160
1161    #[test]
1162    fn golden_mutations_preserve_unrelated_comments_order_and_quoted_tables() {
1163        let temp_root = temp_root("codewhale-golden-mutations");
1164        fs::create_dir_all(&temp_root).unwrap();
1165        let _guard = EnvGuard::new(&temp_root);
1166        let path = temp_root.join(".deepseek").join("config.toml");
1167        write_golden_config(&path);
1168
1169        persist_root_bool_key(Some(&path), "allow_shell", true).unwrap();
1170        persist_table_value_key(Some(&path), "tui", "scrollback_lines", 4000_i64.into()).unwrap();
1171        persist_table_string_key(Some(&path), "memory", "backend", "native").unwrap();
1172        persist_subagents_bool_key(Some(&path), "enabled", true).unwrap();
1173        persist_route_base_url(
1174            Some(&path),
1175            &selection_identity(&path, "openrouter"),
1176            "https://openrouter.example/v2",
1177        )
1178        .unwrap();
1179        persist_status_items(&[crate::config::StatusItem::Mode]).unwrap();
1180        persist_hotbar_bindings(
1181            Some(&path),
1182            &[codewhale_config::HotbarBindingToml {
1183                slot: 2,
1184                action: "session.compact".to_string(),
1185                label: None,
1186            }],
1187        )
1188        .unwrap();
1189
1190        let body = fs::read_to_string(&path).unwrap();
1191        for comment in [
1192            "# CodeWhale golden config fixture, top note.",
1193            "# api_key = \"sk-placeholder\" (uncomment to set the key by hand)",
1194            "# pinned for release QA",
1195            "# workspace trust note",
1196            "# granted manually",
1197            "# providers note",
1198            "# keep in sync with docs",
1199        ] {
1200            assert!(body.contains(comment), "comment lost: {comment}\n{body}");
1201        }
1202        // Updated in place, keeping the trailing comment on the same line.
1203        assert!(
1204            body.contains("base_url = \"https://openrouter.example/v2\" # keep in sync with docs"),
1205            "{body}"
1206        );
1207        assert!(body.contains("[providers.\"quoted.provider\"]"), "{body}");
1208        assert!(
1209            !body.contains("mode.plan"),
1210            "old hotbar entry must be replaced: {body}"
1211        );
1212
1213        // Original section order is intact.
1214        let model_at = body.find("model = ").unwrap();
1215        let projects_at = body.find("[projects.").unwrap();
1216        let providers_at = body.find("[providers.openrouter]").unwrap();
1217        assert!(
1218            model_at < projects_at && projects_at < providers_at,
1219            "{body}"
1220        );
1221
1222        let parsed: toml::Value = toml::from_str(&body).unwrap();
1223        assert_eq!(
1224            parsed.get("allow_shell").and_then(toml::Value::as_bool),
1225            Some(true)
1226        );
1227        assert_eq!(
1228            parsed
1229                .get("tui")
1230                .and_then(|t| t.get("scrollback_lines"))
1231                .and_then(toml::Value::as_integer),
1232            Some(4000)
1233        );
1234        assert_eq!(
1235            parsed
1236                .get("memory")
1237                .and_then(|t| t.get("backend"))
1238                .and_then(toml::Value::as_str),
1239            Some("native")
1240        );
1241        assert_eq!(
1242            parsed
1243                .get("subagents")
1244                .and_then(|t| t.get("enabled"))
1245                .and_then(toml::Value::as_bool),
1246            Some(true)
1247        );
1248    }
1249
1250    #[test]
1251    fn set_document_value_inserts_api_key_even_when_a_comment_mentions_it() {
1252        // Finding #20 at the primitive level: the old string scan treated a
1253        // comment mentioning api_key as an existing assignment and skipped
1254        // the insert entirely.
1255        let temp_root = temp_root("codewhale-golden-api-key-comment");
1256        fs::create_dir_all(&temp_root).unwrap();
1257        let _guard = EnvGuard::new(&temp_root);
1258        let path = temp_root.join(".deepseek").join("config.toml");
1259        write_golden_config(&path);
1260
1261        mutate_config_document(&path, |doc| {
1262            set_document_value(doc, &["api_key"], "sk-fresh")
1263        })
1264        .expect("mutation should succeed");
1265
1266        let body = fs::read_to_string(&path).unwrap();
1267        assert!(
1268            body.contains("# api_key = \"sk-placeholder\""),
1269            "comment lost: {body}"
1270        );
1271        let parsed: toml::Value = toml::from_str(&body).unwrap();
1272        assert_eq!(
1273            parsed.get("api_key").and_then(toml::Value::as_str),
1274            Some("sk-fresh"),
1275            "real key must be inserted despite the comment: {body}"
1276        );
1277    }
1278
1279    #[test]
1280    fn unset_document_value_reports_removal_and_tolerates_missing_parents() {
1281        let mut doc = "model = \"deepseek-v4-pro\"\n"
1282            .parse::<toml_edit::DocumentMut>()
1283            .unwrap();
1284        assert!(!unset_document_value(&mut doc, &["providers", "openrouter", "api_key"]).unwrap());
1285        assert!(!unset_document_value(&mut doc, &["model", "nested"]).unwrap());
1286        assert!(unset_document_value(&mut doc, &["model"]).unwrap());
1287        assert!(!unset_document_value(&mut doc, &["model"]).unwrap());
1288    }
1289
1290    #[test]
1291    fn unset_last_root_value_preserves_its_leading_comment() {
1292        let mut doc = "# keep this explanation\napproval_policy = \"on-request\"\n"
1293            .parse::<toml_edit::DocumentMut>()
1294            .unwrap();
1295
1296        assert!(unset_document_value(&mut doc, &["approval_policy"]).unwrap());
1297
1298        let saved = doc.to_string();
1299        assert!(saved.contains("# keep this explanation"), "{saved:?}");
1300        assert!(!saved.contains("approval_policy"), "{saved:?}");
1301    }
1302
1303    #[test]
1304    fn set_document_value_rejects_non_table_parents() {
1305        let mut doc = "model = \"deepseek-v4-pro\"\n"
1306            .parse::<toml_edit::DocumentMut>()
1307            .unwrap();
1308        let err = set_document_value(&mut doc, &["model", "nested"], "x")
1309            .expect_err("scalar parent must be rejected");
1310        assert!(err.to_string().contains("must be a table"), "{err}");
1311    }
1312
1313    #[test]
1314    fn remove_document_key_recursive_strips_nested_and_quoted_tables() {
1315        let mut doc = r#"# root note
1316api_key = "root"
1317api_key_env = "KEEP_ENV"
1318
1319[providers.openrouter]
1320api_key = "or"
1321base_url = "https://openrouter.ai/api/v1"
1322
1323[providers."quoted.provider"]
1324api_key = "quoted"
1325
1326[[hotbar]]
1327slot = 1
1328"#
1329        .parse::<toml_edit::DocumentMut>()
1330        .unwrap();
1331
1332        remove_document_key_recursive(doc.as_table_mut(), "api_key");
1333
1334        let body = doc.to_string();
1335        assert!(!body.contains("api_key = "), "{body}");
1336        assert!(body.contains("# root note"), "{body}");
1337        assert!(body.contains("api_key_env = \"KEEP_ENV\""), "{body}");
1338        assert!(body.contains("base_url"), "{body}");
1339        assert!(body.contains("[[hotbar]]"), "{body}");
1340    }
1341
1342    #[test]
1343    fn persist_custom_provider_unsets_removed_optional_fields() {
1344        let temp_root = temp_root("codewhale-custom-provider-unset");
1345        fs::create_dir_all(&temp_root).unwrap();
1346        let _guard = EnvGuard::new(&temp_root);
1347        let path = temp_root.join(".codewhale").join("config.toml");
1348
1349        persist_custom_provider(
1350            Some(&path),
1351            "acme_ai",
1352            "https://api.acme.example/v1",
1353            Some("acme/code-1"),
1354            Some("ACME_API_KEY"),
1355        )
1356        .expect("first persist should succeed");
1357        persist_custom_provider(
1358            Some(&path),
1359            "acme_ai",
1360            "https://api.acme.example/v2",
1361            None,
1362            None,
1363        )
1364        .expect("second persist should succeed");
1365
1366        let body = fs::read_to_string(&path).unwrap();
1367        let parsed: toml::Value = toml::from_str(&body).unwrap();
1368        let entry = parsed
1369            .get("providers")
1370            .and_then(|providers| providers.get("acme_ai"))
1371            .expect("provider entry");
1372        assert_eq!(
1373            entry.get("base_url").and_then(toml::Value::as_str),
1374            Some("https://api.acme.example/v2")
1375        );
1376        assert!(entry.get("model").is_none(), "model must be unset: {body}");
1377        assert!(
1378            entry.get("api_key_env").is_none(),
1379            "api_key_env must be unset: {body}"
1380        );
1381    }
1382
1383    #[cfg(unix)]
1384    #[test]
1385    fn config_writes_land_with_owner_only_permissions() {
1386        use std::os::unix::fs::PermissionsExt;
1387
1388        let temp_root = temp_root("codewhale-persist-perms");
1389        fs::create_dir_all(&temp_root).unwrap();
1390        let _guard = EnvGuard::new(&temp_root);
1391        let path = temp_root.join(".deepseek").join("config.toml");
1392        write_golden_config(&path);
1393        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
1394
1395        persist_root_bool_key(Some(&path), "allow_shell", true).expect("persist should succeed");
1396
1397        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1398        assert_eq!(mode, 0o600, "config.toml can hold api keys");
1399    }
1400
1401    /// The active model must be one answer, not two.
1402    #[test]
1403    fn the_dispatcher_and_the_tui_resolve_the_same_active_model() {
1404        // (case, config body, what both chains must answer)
1405        let cases: &[(&str, &str, &str)] = &[
1406            (
1407                "a non-DeepSeek provider honours the user's chosen model",
1408                "provider = \"zai\"\ndefault_text_model = \"GLM-4.6\"\n\n[providers.zai]\napi_key = \"k\"\n",
1409                "GLM-4.6",
1410            ),
1411            (
1412                "a stale DeepSeek id must not be forwarded to a native non-DeepSeek endpoint",
1413                "provider = \"zai\"\ndefault_text_model = \"deepseek-chat\"\n\n[providers.zai]\napi_key = \"k\"\n",
1414                codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL,
1415            ),
1416            (
1417                "no root default falls through to the provider default",
1418                "provider = \"zai\"\n\n[providers.zai]\napi_key = \"k\"\n",
1419                codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL,
1420            ),
1421            (
1422                "a provider-scoped model outranks the root default",
1423                "provider = \"zai\"\ndefault_text_model = \"GLM-4.6\"\n\n[providers.zai]\napi_key = \"k\"\nmodel = \"GLM-4.5-Air\"\n",
1424                "GLM-4.5-Air",
1425            ),
1426            (
1427                "DeepSeek itself keeps honouring the root default",
1428                "provider = \"deepseek\"\ndefault_text_model = \"deepseek-v4-pro\"\n\n[providers.deepseek]\napi_key = \"k\"\n",
1429                "deepseek-v4-pro",
1430            ),
1431            (
1432                "a vendor-locked endpoint refuses a DeepSeek id (#3227)",
1433                "provider = \"xai\"\ndefault_text_model = \"deepseek-v4-pro\"\n\n[providers.xai]\napi_key = \"k\"\n",
1434                codewhale_config::descriptors::defaults::DEFAULT_XAI_MODEL,
1435            ),
1436            (
1437                "an aggregator legitimately serves DeepSeek ids",
1438                "provider = \"openrouter\"\ndefault_text_model = \"deepseek/deepseek-v4-pro\"\n\n[providers.openrouter]\napi_key = \"k\"\n",
1439                "deepseek/deepseek-v4-pro",
1440            ),
1441            (
1442                "a local runtime passes its own tag through",
1443                "provider = \"ollama\"\ndefault_text_model = \"qwen3-coder:30b\"\n",
1444                "qwen3-coder:30b",
1445            ),
1446            (
1447                "a custom base URL keeps full pass-through (#1519)",
1448                "provider = \"zai\"\ndefault_text_model = \"deepseek-chat\"\n\n[providers.zai]\napi_key = \"k\"\nbase_url = \"https://proxy.example.invalid/v1\"\n",
1449                "deepseek-chat",
1450            ),
1451        ];
1452
1453        for (case, body, expected) in cases {
1454            let temp_root = temp_root("codewhale-model-chain-agreement");
1455            fs::create_dir_all(&temp_root).unwrap();
1456            let _guard = EnvGuard::new(&temp_root);
1457            let _model_guard = ModelEnvGuard::new();
1458            let path = temp_root.join(".deepseek").join("config.toml");
1459            fs::create_dir_all(path.parent().unwrap()).unwrap();
1460            fs::write(&path, body).unwrap();
1461
1462            let tui = crate::config::Config::load(Some(path.clone()), None)
1463                .expect("the TUI must parse this config");
1464            let tui_model = tui.default_model();
1465
1466            let dispatcher = codewhale_config::ConfigStore::load(Some(path.clone()))
1467                .expect("the dispatcher must parse the same config");
1468            let runtime = dispatcher
1469                .config
1470                .resolve_runtime_options(&codewhale_config::CliRuntimeOverrides::default());
1471
1472            assert_eq!(
1473                tui_model, *expected,
1474                "{case}: the TUI chain (what actually reaches the provider) is wrong"
1475            );
1476            assert_eq!(
1477                runtime.model, *expected,
1478                "{case}: the dispatcher chain (what `model resolve` reports) is wrong"
1479            );
1480
1481            let _ = fs::remove_dir_all(&temp_root);
1482        }
1483    }
1484}
1485
1486#[cfg(any(test, feature = "test-support"))]
1487pub mod test_support;