1use std::path::PathBuf;
13
14use anyhow::Result;
15use codewhale_config::ConfigToml;
16use codewhale_config::settings_schema::SETTINGS_SCHEMA;
17
18use crate::config::Config;
19use crate::settings::Settings;
20
21const OTHER_READER_ROOT_KEYS: &[&str] = &[
32 "profiles",
33 "base_url",
34 "baseUrl",
35 "api_key",
36 "apiKey",
37 "projects",
38 "workspace",
39 "route_preferences_version",
40 "route_preferences_migration",
41 "mcp.server_definitions",
42 "stream_chunk_timeout_secs",
43 "tui.stream_chunk_timeout_secs",
44];
45
46const TABLE_ROOT_KEYS: &[&str] = &["profiles", "projects", "workspace"];
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum ConfigKeyHome {
55 ConfigToml,
58 SettingsToml,
60 Unknown,
62}
63
64#[must_use]
68pub fn config_key_home(key: &str) -> ConfigKeyHome {
69 let key = key.trim();
70 if key.contains('.') || is_config_toml_root_key(key) {
71 ConfigKeyHome::ConfigToml
72 } else if Settings::canonical_key(key).is_some() {
73 ConfigKeyHome::SettingsToml
74 } else {
75 ConfigKeyHome::Unknown
76 }
77}
78
79fn is_config_toml_root_key(key: &str) -> bool {
81 tui_config_fields().contains(&key)
82 || OTHER_READER_ROOT_KEYS.contains(&key)
83 || is_config_toml_typed_field(key)
84}
85
86fn tui_config_fields() -> &'static [&'static str] {
89 static FIELDS: std::sync::OnceLock<&'static [&'static str]> = std::sync::OnceLock::new();
90 FIELDS.get_or_init(struct_fields::<Config>)
91}
92
93fn is_config_toml_typed_field(key: &str) -> bool {
98 let mut probe = toml::Table::new();
99 probe.insert(key.to_string(), toml::Value::Integer(0));
100 match toml::Value::Table(probe).try_into::<ConfigToml>() {
101 Ok(config) => !config.extras.contains_key(key),
102 Err(_) => true,
103 }
104}
105
106fn struct_fields<T: serde::de::DeserializeOwned>() -> &'static [&'static str] {
109 struct Probe(Option<&'static [&'static str]>);
110
111 impl<'de> serde::Deserializer<'de> for &mut Probe {
112 type Error = serde::de::value::Error;
113
114 fn deserialize_any<V: serde::de::Visitor<'de>>(
115 self,
116 _visitor: V,
117 ) -> Result<V::Value, Self::Error> {
118 Err(serde::de::Error::custom("field probe"))
119 }
120
121 fn deserialize_struct<V: serde::de::Visitor<'de>>(
122 self,
123 _name: &'static str,
124 fields: &'static [&'static str],
125 _visitor: V,
126 ) -> Result<V::Value, Self::Error> {
127 self.0 = Some(fields);
128 Err(serde::de::Error::custom("field probe"))
129 }
130
131 serde::forward_to_deserialize_any! {
132 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
133 bytes byte_buf option unit unit_struct newtype_struct seq tuple
134 tuple_struct map enum identifier ignored_any
135 }
136 }
137
138 let mut probe = Probe(None);
139 let _ = T::deserialize(&mut probe);
140 probe.0.unwrap_or(&[])
141}
142
143fn settable_keys() -> impl Iterator<Item = &'static str> {
146 SETTINGS_SCHEMA
147 .iter()
148 .map(|def| def.key)
149 .filter(|key| {
150 codewhale_config::notifications::in_namespace(key)
151 || key.starts_with("stream.")
152 || (!key.contains('.') && config_key_home(key) != ConfigKeyHome::Unknown)
153 })
154 .chain(
157 tui_config_fields()
158 .iter()
159 .copied()
160 .filter(|key| !key.chars().any(|c| c.is_ascii_uppercase())),
161 )
162 .chain(
163 OTHER_READER_ROOT_KEYS
164 .iter()
165 .copied()
166 .filter(|key| !key.contains('.') && !TABLE_ROOT_KEYS.contains(key)),
167 )
168}
169
170pub fn nearest_key<'a>(
172 query: &str,
173 candidates: impl IntoIterator<Item = &'a str>,
174) -> Option<&'a str> {
175 candidates
176 .into_iter()
177 .filter_map(|candidate| {
178 codewhale_config::suggest::best_suggestion_score(query, [candidate])
179 .map(|score| (score, candidate))
180 })
181 .min_by_key(|(score, _)| *score)
182 .map(|(_, candidate)| candidate)
183}
184
185#[must_use]
187pub fn unknown_config_key_message(key: &str) -> String {
188 let hint = nearest_key(key, settable_keys())
189 .map(|candidate| format!(" Did you mean `{candidate}`?"))
190 .unwrap_or_default();
191 format!(
192 "unknown config key `{key}`: nothing reads it, so it was not saved.{hint} \
193 Run `codewhale config list` for config.toml keys or `/settings text` for settings."
194 )
195}
196
197pub fn resolved_stream_config(config: &ConfigToml) -> Result<toml::Value> {
202 let document = toml::Value::try_from(config)?;
203 let mut transport = toml::Table::new();
206 for key in ["stream", "tui"] {
207 if let Some(value) = document.get(key) {
208 transport.insert(key.to_string(), value.clone());
209 }
210 }
211 let config: Config = toml::Value::Table(transport).try_into()?;
212 Ok(toml::Value::try_from(config.resolved_stream_settings())?)
213}
214
215pub fn set_settings_value(key: &str, value: &str) -> Result<PathBuf> {
218 Settings::transact(|settings| settings.set(key, value))?;
219 Settings::path()
220}
221
222pub fn settings_value(key: &str) -> Result<Option<String>> {
225 Ok(Settings::load_persisted()?.value(key))
226}
227
228pub fn settings_toml_keys() -> impl Iterator<Item = &'static str> {
233 SETTINGS_SCHEMA
234 .iter()
235 .map(|def| def.key)
236 .filter(|key| Settings::canonical_key(key) == Some(*key))
237}
238
239pub fn config_toml_value(key: &str, value: &str) -> Result<Option<toml::Value>> {
256 let key = key.trim();
257 if TABLE_ROOT_KEYS.contains(&key) {
258 anyhow::bail!(
259 "`{key}` is a table of entries, so `config set {key}` would replace all of \
260 them; nothing was saved. Edit the [{key}.<name>] table in config.toml instead."
261 );
262 }
263 codewhale_config::check_config_toml_choice(key, value)?;
264 if key == "reasoning_effort" {
265 let effort = codewhale_config::settings_schema::canonical_reasoning_effort(value)
266 .map_err(|error| anyhow::anyhow!("invalid value for '{key}': {error}"))?;
267 return Ok(Some(toml::Value::String(effort.to_string())));
268 }
269 if key.contains('.')
270 || codewhale_config::setting(key).is_some()
271 || !tui_config_fields().contains(&key)
272 || is_config_toml_typed_field(key)
273 {
274 return Ok(None);
275 }
276 let text = toml::Value::String(value.to_string());
277 if tui_config_accepts(key, &text) {
278 return Ok(None);
279 }
280 let trimmed = value.trim();
281 let candidates = [
282 crate::settings::parse_bool(trimmed)
283 .ok()
284 .map(toml::Value::Boolean),
285 trimmed.parse::<i64>().ok().map(toml::Value::Integer),
286 trimmed
287 .parse::<f64>()
288 .ok()
289 .filter(|number| number.is_finite())
290 .map(toml::Value::Float),
291 ];
292 candidates
293 .into_iter()
294 .flatten()
295 .find(|candidate| tui_config_accepts(key, candidate))
296 .map(Some)
297 .ok_or_else(|| {
298 anyhow::anyhow!(
299 "invalid value '{value}' for '{key}': its config.toml reader does not accept \
300 it. Edit `{key}` in config.toml with a TOML value of the documented type. \
301 No value was changed."
302 )
303 })
304}
305
306fn tui_config_accepts(key: &str, value: &toml::Value) -> bool {
308 let mut probe = toml::Table::new();
309 probe.insert(key.to_string(), value.clone());
310 toml::Value::Table(probe).try_into::<Config>().is_ok()
311}
312
313#[must_use]
316pub fn unread_config_keys<'a>(root_keys: impl IntoIterator<Item = &'a str>) -> Vec<String> {
317 root_keys
318 .into_iter()
319 .filter(|key| !is_config_toml_root_key(key))
320 .map(|key| {
321 if Settings::canonical_key(key).is_some() {
322 format!(
323 "`{key}` belongs in settings.toml; config.toml's copy is never read \
324 (move it: `codewhale config set {key} <value>`, then \
325 `codewhale config unset {key}`)"
326 )
327 } else {
328 let hint = nearest_key(key, settable_keys())
329 .map(|candidate| format!("; did you mean `{candidate}`?"))
330 .unwrap_or_default();
331 format!("`{key}` is not read by anything{hint}")
332 }
333 })
334 .collect()
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 #[test]
342 fn config_key_home_routes_by_reader() {
343 assert_eq!(config_key_home("calm_mode"), ConfigKeyHome::SettingsToml);
345 assert_eq!(config_key_home("calm"), ConfigKeyHome::SettingsToml);
346 assert_eq!(
347 config_key_home("tool_collapse"),
348 ConfigKeyHome::SettingsToml
349 );
350 for key in [
352 "provider",
353 "api_key",
354 "verbosity",
355 "log_level",
356 "hook_sinks",
357 "allow_shell",
358 "max_subagents",
359 "skills_dir",
360 "tui",
361 "features",
362 "profiles",
363 "projects",
364 "stream_chunk_timeout_secs",
365 ] {
366 assert_eq!(config_key_home(key), ConfigKeyHome::ConfigToml, "{key}");
367 }
368 assert_eq!(config_key_home("sandbox_mode"), ConfigKeyHome::ConfigToml);
370 assert_eq!(
371 config_key_home("reasoning_effort"),
372 ConfigKeyHome::ConfigToml
373 );
374 assert_eq!(
376 config_key_home("providers.deepseek.model"),
377 ConfigKeyHome::ConfigToml
378 );
379 assert_eq!(config_key_home("totally_bogus_key"), ConfigKeyHome::Unknown);
380 }
381
382 #[test]
383 fn every_shipped_example_root_key_is_read_by_something() {
384 let example: toml::Table =
385 toml::from_str(include_str!("../../../config.example.toml")).expect("example parses");
386 let unread = unread_config_keys(example.keys().map(String::as_str));
387 assert!(unread.is_empty(), "{unread:#?}");
388 }
389
390 #[test]
391 fn unknown_config_key_message_suggests_from_current_keys() {
392 let message = unknown_config_key_message("calm_mod");
393 assert!(message.contains("Did you mean `calm_mode`?"), "{message}");
394 assert!(message.contains("not saved"), "{message}");
395
396 let message = unknown_config_key_message("zzqqxxyy");
397 assert!(!message.contains("Did you mean"), "{message}");
398 }
399
400 #[test]
401 fn config_toml_value_types_fields_by_their_reader() {
402 assert_eq!(
404 config_toml_value("yolo", "true").unwrap(),
405 Some(toml::Value::Boolean(true))
406 );
407 assert_eq!(
408 config_toml_value("strict_tool_mode", "off").unwrap(),
409 Some(toml::Value::Boolean(false))
410 );
411 assert_eq!(
412 config_toml_value("max_subagents", " 4 ").unwrap(),
413 Some(toml::Value::Integer(4))
414 );
415 assert_eq!(
416 config_toml_value("mcp_oauth_callback_port", "8765").unwrap(),
417 Some(toml::Value::Integer(8765))
418 );
419 for (key, value) in [
421 ("yolo", "flase"),
422 ("max_subagents", "lots"),
423 ("mcp_oauth_callback_port", "70000"),
424 ] {
425 let error = config_toml_value(key, value).expect_err(key);
426 assert!(
427 format!("{error:#}").contains(&format!("invalid value '{value}' for '{key}'")),
428 "{error:#}"
429 );
430 }
431 assert_eq!(
434 config_toml_value("skills_dir", "/tmp/skills").unwrap(),
435 None
436 );
437 assert_eq!(config_toml_value("allow_shell", "on").unwrap(), None);
438 assert_eq!(
439 config_toml_value("providers.deepseek.model", "x").unwrap(),
440 None
441 );
442
443 for (alias, canonical) in [("none", "off"), ("mid", "medium"), ("maximum", "max")] {
445 assert_eq!(
446 config_toml_value("reasoning_effort", alias).unwrap(),
447 Some(toml::Value::String(canonical.into())),
448 "{alias}"
449 );
450 }
451 assert!(config_toml_value("reasoning_effort", "bogus").is_err());
452 }
453
454 #[test]
455 fn config_toml_value_refuses_values_the_loader_rejects() {
456 for (key, value) in [
457 ("approval_policy", " On-Request "),
458 ("approval_policy", "never"),
459 ("sandbox_mode", "workspace-write"),
460 ("verbosity", "concise"),
461 ] {
462 assert_eq!(
463 config_toml_value(key, value).unwrap(),
464 None,
465 "{key}={value}"
466 );
467 }
468 for (key, value, fix) in [
469 ("approval_policy", "ask", "on-request"),
470 ("sandbox_mode", "full", "read-only"),
471 ("verbosity", "quiet", "normal"),
472 ] {
473 let error = format!("{:#}", config_toml_value(key, value).expect_err(key));
474 assert!(
475 error.contains(&format!("invalid value '{value}' for '{key}'")),
476 "{error}"
477 );
478 assert!(
479 error.contains(&format!("fix: codewhale config set {key} {fix}")),
480 "{error}"
481 );
482 }
483 let error = format!(
484 "{:#}",
485 config_toml_value("approval_policy", "ask").unwrap_err()
486 );
487 assert!(error.contains("on-request, untrusted, never"), "{error}");
488 assert!(error.contains("settings.toml"), "{error}");
489 }
490
491 #[test]
492 fn settings_toml_keys_are_user_settable_only() {
493 let keys: Vec<&str> = settings_toml_keys().collect();
494 assert!(keys.contains(&"calm_mode"), "{keys:?}");
495 assert!(keys.contains(&"auto_compact"), "{keys:?}");
496 for internal in [
497 "feature_intro_shown",
498 "yolo_deprecation_shown",
499 "mcp_open",
500 "fast_model",
501 "effective_auto_compact",
502 ] {
503 assert!(!keys.contains(&internal), "{internal} is not settable");
504 }
505 }
506
507 #[test]
508 fn scalar_set_of_a_table_root_key_is_refused() {
509 for key in TABLE_ROOT_KEYS {
512 assert_eq!(config_key_home(key), ConfigKeyHome::ConfigToml, "{key}");
513 let error = config_toml_value(key, "/some/path").expect_err(key);
514 assert!(error.to_string().contains("nothing was saved"), "{error}");
515 }
516 }
517
518 #[test]
519 fn config_set_and_loader_accept_the_same_closed_vocabulary() {
520 for (key, value, valid) in [
521 ("approval_policy", " ON-REQUEST ", true),
522 ("approval_policy", "ask", false),
523 ("verbosity", " CONCISE ", true),
524 ("verbosity", "quiet", false),
525 ("sandbox_mode", " WORKSPACE-WRITE ", true),
526 ("sandbox_mode", "full", false),
527 ] {
528 let mut config = crate::config::Config::default();
529 match key {
530 "approval_policy" => config.approval_policy = Some(value.to_string()),
531 "verbosity" => config.verbosity = Some(value.to_string()),
532 "sandbox_mode" => config.sandbox_mode = Some(value.to_string()),
533 _ => unreachable!(),
534 }
535 assert_eq!(config_toml_value(key, value).is_ok(), valid, "{key}");
536 assert_eq!(config.validate().is_ok(), valid, "{key}");
537 }
538 }
539
540 #[test]
541 fn loader_choice_errors_redact_pasted_keys_but_keep_ordinary_typos() {
542 let token = ["sk-live-", "Z7qX4mNb2Vc9Lk3PwR8t"].concat();
543 for (key, correction) in [
544 ("approval_policy", "on-request"),
545 ("verbosity", "normal"),
546 ("sandbox_mode", "workspace-write"),
547 ] {
548 for value in [token.as_str(), "misspelled-choice"] {
549 let mut config = crate::config::Config::default();
550 match key {
551 "approval_policy" => config.approval_policy = Some(value.to_string()),
552 "verbosity" => config.verbosity = Some(value.to_string()),
553 "sandbox_mode" => config.sandbox_mode = Some(value.to_string()),
554 _ => unreachable!(),
555 }
556 let error = config.validate().expect_err("invalid choice");
557 let diagnostic = crate::config::SafeConfigDiagnostic::find_in(&error)
558 .expect("shared choice validation keeps the structured diagnostic");
559 let shareable = diagnostic.display_message();
560 assert!(shareable.starts_with(&format!("Invalid {key} (value not shown):")));
561 assert!(!shareable.contains(value), "{shareable}");
562 let fix = diagnostic
563 .fix()
564 .expect("invalid choices keep a recovery action");
565 assert!(
566 fix.starts_with(&format!("codewhale config set {key} {correction} (if ")),
567 "{fix}"
568 );
569 assert!(
570 fix.contains("profile") && fix.contains("managed config"),
571 "{fix}"
572 );
573 if key != "verbosity" {
574 assert!(
575 fix.contains(&format!("CODEWHALE_{}", key.to_ascii_uppercase())),
576 "{fix}"
577 );
578 }
579 let error = error.to_string();
580 assert!(!error.contains(&token));
581 assert!(error.contains("expected"));
582 assert!(error.contains(if value == token {
583 "[redacted]"
584 } else {
585 "misspelled-choice"
586 }));
587 }
588 }
589 }
590
591 #[test]
592 fn documented_user_workspace_entry_is_read() {
593 let documented: toml::Table =
595 toml::from_str("[workspace.'/absolute/path/to/project']\nallow_shell = true\n")
596 .expect("documented block parses");
597 let unread = unread_config_keys(documented.keys().map(String::as_str));
598 assert!(unread.is_empty(), "{unread:#?}");
599 }
600
601 #[test]
602 fn unread_config_keys_names_misplaced_settings_and_unknown_keys() {
603 let findings = unread_config_keys(["verbosity", "calm_mode", "totally_bogus_key", "tui"]);
604 assert_eq!(findings.len(), 2, "{findings:#?}");
605 assert!(
606 findings[0].contains("`calm_mode` belongs in settings.toml"),
607 "{findings:#?}"
608 );
609 assert!(
610 findings[1].contains("`totally_bogus_key` is not read by anything"),
611 "{findings:#?}"
612 );
613 }
614 #[test]
615 fn stream_dump_uses_runtime_resolution_without_exposing_other_config() {
616 let _env = crate::test_support::lock_test_env();
617 let _open =
618 crate::test_support::EnvVarGuard::set("CODEWHALE_STREAM_OPEN_TIMEOUT_SECS", "88");
619 let _pin = crate::test_support::EnvVarGuard::set("CODEWHALE_FORCE_HTTP1", "1");
620 let config: ConfigToml = toml::from_str("[providers.deepseek]\napi_key='fixture-secret'\n[tui]\nstream_max_resumes=6\n[stream]\nhttp2_keep_alive_timeout_secs=0\n").unwrap();
621 let stream = resolved_stream_config(&config).unwrap();
622 assert_eq!(stream["open_timeout_secs"].as_integer(), Some(88));
623 assert_eq!(stream["max_resumes"].as_integer(), Some(6));
624 assert_eq!(stream["force_http1"].as_bool(), Some(true));
625 assert_eq!(
626 stream["http2_keep_alive_timeout_secs"].as_integer(),
627 Some(20)
628 );
629 assert!(!stream.to_string().contains("fixture-secret"));
630 assert!(unread_config_keys(["stream"]).is_empty());
631 for key in stream.as_table().unwrap().keys() {
632 assert!(
633 codewhale_config::setting(&format!("stream.{key}")).is_some(),
634 "{key}"
635 );
636 }
637 assert_eq!(
638 config.extras["stream"].as_table().unwrap().len(),
639 1,
640 "dump never persists resolved defaults"
641 );
642 }
643}