use super::Config;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownKey {
pub table: String,
pub row: Option<usize>,
pub key: String,
pub hint: Option<String>,
}
impl fmt::Display for UnknownKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (&self.row, self.table.is_empty()) {
(Some(i), _) => write!(f, "[[{}]] entry {}, `{}`", self.table, i + 1, self.key),
(None, true) => write!(f, "top level, `{}`", self.key),
(None, false) => write!(f, "[{}], `{}`", self.table, self.key),
}
}
}
const KNOWN_WHEN_EMPTY: &[(&str, &str)] = &[
("provider", "fallback"),
("provider", "aux"),
("provider", "delegate"),
("provider", "route"),
("provider", "api_key"),
("provider", "api_key_env"),
("provider", "profile"),
("provider", "reasoning_effort"),
("agent", "output_schema"),
("web", "auth_token"),
("web", "default_profile"),
("update", "remote"),
("update", "releases"),
];
const ROUTE_TABLE: &str = "provider.route";
const ROUTE_BASE_TABLE: &str = "provider";
fn known_when_empty(path: &str, key: &str) -> bool {
KNOWN_WHEN_EMPTY.contains(&(path, key))
|| (path == ROUTE_TABLE && KNOWN_WHEN_EMPTY.contains(&(ROUTE_BASE_TABLE, key)))
}
impl Config {
pub fn unknown_keys(&self, value: &toml::Value) -> Vec<UnknownKey> {
let Ok(known) = toml::Value::try_from(self) else {
return Vec::new();
};
let mut out = Vec::new();
walk(value, &known, "", None, &mut out);
let hints = serde_json::to_value(self).ok().map(|json| {
let mut paths = Vec::new();
json_tables_with(&json, None, "", &mut paths);
paths
});
if let Some(paths) = hints {
for unknown in &mut out {
let mut found: Vec<&str> = paths
.iter()
.filter(|(key, table)| *key == unknown.key && **table != unknown.table)
.map(|(_, table)| table.as_str())
.collect();
found.sort_by_key(|t| t.len());
unknown.hint = found.first().map(std::string::ToString::to_string);
}
}
out
}
}
fn walk(
file: &toml::Value,
known: &toml::Value,
path: &str,
row: Option<usize>,
out: &mut Vec<UnknownKey>,
) {
match (file, known) {
(toml::Value::Table(from_file), toml::Value::Table(read)) => {
for (key, value) in from_file {
match read.get(key) {
Some(known_value) => {
let below = if path.is_empty() {
key.to_string()
} else {
format!("{path}.{key}")
};
walk(value, known_value, &below, row, out);
}
None if known_when_empty(path, key.as_str()) => {}
None => out.push(UnknownKey {
table: path.to_string(),
row,
key: key.clone(),
hint: None,
}),
}
}
}
(toml::Value::Array(from_file), toml::Value::Array(read))
if from_file.len() == read.len() =>
{
for (i, (a, b)) in from_file.iter().zip(read).enumerate() {
walk(a, b, path, Some(i), out);
}
}
_ => {}
}
}
fn json_tables_with(
value: &serde_json::Value,
key_wanted: Option<&str>,
path: &str,
out: &mut Vec<(String, String)>,
) {
match value {
serde_json::Value::Object(map) => {
for (k, v) in map {
let below = if path.is_empty() {
k.clone()
} else {
format!("{path}.{k}")
};
if key_wanted.is_none_or(|wanted| wanted == k) {
out.push((k.clone(), path.to_string()));
}
json_tables_with(v, key_wanted, &below, out);
}
}
serde_json::Value::Array(items) => {
for v in items {
json_tables_with(v, key_wanted, path, out);
}
}
_ => {}
}
}
pub fn unknown_keys_in_file(
path: &std::path::Path,
cfg: &Config,
) -> super::Result<Vec<UnknownKey>> {
let text = std::fs::read_to_string(path).map_err(|e| super::Error::io(path, e))?;
let value: toml::Value = toml::from_str(&text).map_err(|message| super::Error::Parse {
path: path.to_path_buf(),
message: message.to_string(),
})?;
Ok(cfg.unknown_keys(&value))
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(config: &str) -> Vec<String> {
let value: toml::Value = toml::from_str(config).unwrap();
let cfg: Config = value.clone().try_into().unwrap();
cfg.unknown_keys(&value)
.iter()
.map(std::string::ToString::to_string)
.collect()
}
#[test]
fn a_key_nothing_reads_is_named_with_the_table_it_sits_in() {
let found = keys("[tools]\nworkspace_root = \"/tmp\"\nbogus_setting = 5\n");
assert_eq!(found, ["[tools], `bogus_setting`"]);
}
#[test]
fn a_key_in_the_wrong_table_says_where_it_is_read() {
let value: toml::Value =
toml::from_str("[provider]\nmodel = \"m\"\n[web]\napi_key = \"x\"\n").unwrap();
let cfg: Config = value.clone().try_into().unwrap();
let found = cfg.unknown_keys(&value);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].key, "api_key");
assert_eq!(found[0].table, "web");
assert_eq!(found[0].hint.as_deref(), Some("provider"));
}
#[test]
fn a_nested_table_and_the_top_level_are_both_reported_by_path() {
let found = keys("top_level_typo = 1\n[sessions]\nstore = { nope = 2 }\n");
assert_eq!(
found,
["[sessions], `store`", "top level, `top_level_typo`"],
"{found:?}"
);
}
#[test]
fn a_type_that_does_not_match_is_left_to_the_parser() {
let value: toml::Value = toml::from_str("[provider]\nmodel = { nope = 1 }\n").unwrap();
let cfg = Config::default();
assert!(cfg.unknown_keys(&value).is_empty());
}
#[test]
fn the_keys_that_serialise_to_nothing_when_unset_are_still_known() {
for line in [
"fallback = []",
"aux = \"a\"",
"delegate = \"b\"",
"route = []",
] {
let text = format!("[provider]\n{line}\n");
assert_eq!(keys(&text), [] as [String; 0], "{line}");
}
}
#[test]
fn a_route_entry_is_checked_without_losing_the_other_entries() {
let found = keys(
"[[provider.route]]\nname = \"a\"\nmodel = \"m\"\n\n\
[[provider.route]]\nname = \"b\"\nmodel = \"m\"\ntempo = 0.2\n",
);
assert_eq!(found, ["[[provider.route]] entry 2, `tempo`"]);
}
#[test]
fn a_route_entry_reads_the_keys_provider_reads_even_when_they_hold_nothing() {
for line in [
"api_key = \"\"",
"api_key_env = \"\"",
"profile = \"\"",
"reasoning_effort = \"\"",
"fallback = []",
] {
let text = format!(
"[[provider.route]]\nname = \"a\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n{line}\n"
);
assert_eq!(keys(&text), [] as [String; 0], "{line}");
}
}
#[test]
fn a_route_entry_with_a_key_and_one_with_a_named_variable_report_nothing() {
let found = keys(
"[[provider.route]]\nname = \"a\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
api_key = \"a-literal-key\"\n\n\
[[provider.route]]\nname = \"b\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
api_key_env = \"A_KEY\"\n",
);
assert_eq!(found, [] as [String; 0]);
}
#[test]
fn a_misspelled_inherited_key_on_a_route_is_still_reported() {
let found = keys(
"[[provider.route]]\nname = \"a\"\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
timeout_sec = 60\n",
);
assert_eq!(found, ["[[provider.route]] entry 1, `timeout_sec`"]);
}
#[test]
fn hooks_are_the_parsers_business_and_are_not_reported_here() {
let found = keys(
"[hooks]\norder = [\"pre_tool\"]\n\n[hooks.pre_tool]\ncommand = \"x\"\nwhat = 1\n",
);
assert_eq!(found, [] as [String; 0]);
}
#[test]
fn the_starter_config_is_clean() {
let found = keys(&crate::config::starter_config().unwrap());
assert_eq!(found, [] as [String; 0]);
}
#[test]
fn the_shipped_profile_starter_is_clean_too() {
let found = keys(crate::config::STARTER_PROFILE_CONFIG);
assert_eq!(found, [] as [String; 0], "profile starter");
}
}