eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Which keys a config file sets that this build does not read.
//!
//! Found while verifying M1: a misplaced `${VAR}` was reported as `web.api_key`, and the mistake was
//! obvious only by accident — `api_key` under `[web]` had been ignored in silence. Nothing here is
//! fatal, deliberately: a profile overlay or a plugin's provider profile may legitimately carry a
//! key a given build does not know yet, so this is a report, not a parse error.
//!
//! The schema comes from the **loaded config serialised back to TOML**, not from a list written by
//! hand. A key the file sets and no struct field holds is dropped by that round trip, so the
//! difference between the two trees is exactly the set of keys nothing reads — and a field added
//! later is known to this check the moment it exists, with no second place to update. The one blind
//! spot is a field that serialises to nothing at all when unset (`skip_serializing_if`), which is
//! what [`KNOWN_WHEN_EMPTY`] is for.

use super::Config;
use std::fmt;

/// A key in a config file that no part of [`Config`] reads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownKey {
    /// Dotted table path, `""` at the top level, `provider.route` for an entry of
    /// `[[provider.route]]`.
    pub table: String,
    /// Which entry of that array, when the key sits inside `[[…]]`.
    pub row: Option<usize>,
    /// The key as written.
    pub key: String,
    /// Where the same key *is* read, when it is read somewhere. This is the answer to a key under
    /// the wrong table, which is the mistake that started this.
    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),
        }
    }
}

/// Fields that exist and are read, but serialise to nothing when unset, so the round trip cannot
/// see them: `(table, key)`. Empty is not the same as absent, and a config that writes
/// `fallback = []` is writing a real key.
/// Keys that are read, but *disappear* from the loaded config when they hold an empty value.
///
/// Two reasons, one effect: `empty_is_none` turns `""` into `None` (a shipped config writes every
/// secret, path and route as `""` or `"${VAR:-}"`, and an empty one means "not in use"), and the
/// `Option` fields that a route or a hook owns are only visible when set. The comparison below is
/// against the *loaded* config, so without this list the shipped file would report seven of its own
/// keys as spellings nothing reads.
///
/// Adding a key here is a claim that an empty value means something; a key that is genuinely
/// misspelled still shows up, because the spelling has to be one the struct holds.
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"),
];

/// The one table whose entries carry another table's whole surface.
///
/// [`RouteConfig`](crate::config::RouteConfig) is `#[serde(flatten)] ProviderConfig`, so every key
/// `[provider]` reads is read on a route too — `apply_key_env` resolves `api_key` and
/// `api_key_env` there with the same function, which is why a working key on a route used to be
/// reported as a spelling nothing reads (`#496`).
const ROUTE_TABLE: &str = "provider.route";
/// What a route entry inherits from.
const ROUTE_BASE_TABLE: &str = "provider";

/// Whether `key` under `path` is a key that exists and is read but serialises to nothing when it
/// holds an empty value, so the round trip below cannot see it.
///
/// A route entry answers to `[provider]`'s list as well as its own: the flatten is what makes the
/// route's `api_key = ""` mean "not in use" rather than "a spelling nothing reads".
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 {
    /// Every key in `value` this build does not read, table by table as the parser hands them
    /// over (sorted, not in the order the file wrote them — `toml::Table` is a map).
    ///
    /// `value` is one file as written — the base config, or a profile's overlay. `self` supplies the
    /// shape, so pass the config that was actually loaded: a file that sets `model` is only known
    /// to be right because the struct has the field.
    pub fn unknown_keys(&self, value: &toml::Value) -> Vec<UnknownKey> {
        let Ok(known) = toml::Value::try_from(self) else {
            // A config that cannot be serialised cannot describe its own shape. Say nothing rather
            // than report every key in the file as unknown.
            return Vec::new();
        };
        let mut out = Vec::new();
        walk(value, &known, "", None, &mut out);
        // Hints come from a JSON round trip, not the TOML one: serde_json keeps a `None` field as
        // `null` instead of dropping it, so `api_key` under `[provider]` is visible here even in a
        // config that sets no key. TOML is still what decides the walk above, because it is the
        // language the file is written in.
        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();
                // Several tables read this key (`model` is under `provider` and under every route):
                // the shortest path is the one a user meant.
                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,
                    }),
                }
            }
        }
        // `[[table]]` entries line up one for one: a key nobody reads is dropped from the entry it
        // was written in, not from the array, so the indexes stay aligned.
        (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);
            }
        }
        _ => {}
    }
}

/// `(key, table)` for every key the shapes declare, from the JSON round trip. `serde_json` keeps a
/// `None` field as `null` rather than dropping it, which is the difference between this and the
/// TOML walk.
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);
            }
        }
        _ => {}
    }
}

/// Read one config file and report the keys in it that `cfg` does not read.
///
/// The file is parsed as TOML and nothing more: a config whose types are wrong never gets here,
/// because `cfg` had to load for the shape to exist, and that load would have failed first.
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() {
        // The M1 accident: `api_key` belongs under `[provider]`, and under `[web]` it was silently
        // ignored — which is how a config looks correct and sends no key.
        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() {
        // `[sessions]` has no `store` table, so the whole table is the unknown thing; a typo inside
        // a table that does exist is named by its own 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() {
        // `model` is a string; here it is a table. Serde reports that on load with the key and the
        // type, so this check must not also claim the key is unknown.
        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() {
        // `fallback`, `aux`, `delegate` and `route` are `skip_serializing_if`, so a round trip
        // cannot see them. Writing them empty must not be called a typo.
        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`"]);
    }

    /// `#496`: a route is `#[serde(flatten)] ProviderConfig`, and `apply_key_env` resolves
    /// `api_key`/`api_key_env` on every route with the function `[provider]` uses. A key whose
    /// value is empty drops out of the loaded config, so the round trip cannot see it — the route
    /// has to inherit the list of keys that still mean something when they hold nothing.
    #[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}");
        }
    }

    /// The half the report was actually about: a route that carries the key it needs. The literal
    /// is deliberately not shaped like a vendor token, so nothing redacts the fixture.
    #[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]);
    }

    /// The bug was a false finding, so the fix must not turn the check off: an inherited key
    /// spelled wrong is still a key nothing reads.
    #[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() {
        // `[hooks.<name>]` is a `flatten` map whose keys are hook names, and `hooks::validate`
        // already names the field that is wrong inside one.
        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() {
        // The drift guard: every key the shipped starter file documents must be one this build
        // reads, so a field renamed without the starter following it fails here.
        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");
    }
}