Skip to main content

eclipse_core/config/
settings.rs

1//! The settings catalogue, and the one setter all three surfaces use.
2//!
3//! M24 exists because every setting was a file edit: `config` could write a starter file, show
4//! the result and check the keys nothing reads, but it could not change *one key*, so the answer
5//! to "how do I change this" was a document. This module is the missing half.
6//!
7//! # Where the list of keys comes from
8//!
9//! Not from a list written by hand. `Config::default()` serialised to TOML *is* the schema: every
10//! table and key a struct holds, with the value a build uses when the file says nothing. The
11//! loaded config serialised the same way is the effective value. So the catalogue is derived, and
12//! a field added later is settable the moment it exists — the same rule [`crate::config::check`]
13//! already follows for unknown keys, which is why the setter and the checker cannot disagree
14//! about what a key is called.
15//!
16//! Two shapes are deliberately **not** in the catalogue: a nested table (`provider.route` is a
17//! list of routes, `[hooks.<name>]` belongs to its hook) and an array of tables. They are
18//! structures, not values; a settings page that offers to "set" one has misunderstood it.
19//!
20//! # The one hand-written list, and why it is a test
21//!
22//! A field of type `Option<T>` that is `None` by default is *absent* from the serialised config,
23//! so the derivation cannot see it — and `provider.api_key` is exactly that. [`ABSENT_BY_DEFAULT`]
24//! declares those keys and their types, and
25//! `every_key_that_is_absent_by_default_is_real_and_settable` proves each one by setting it,
26//! parsing the result and reading the value back: an entry for a field that does not exist would
27//! be refused by the setter's own round-trip check.
28//!
29//! # Why the setter edits text instead of re-serialising
30//!
31//! Re-serialising would be simpler and would delete every comment the user wrote. `toml_set_value`
32//! replaces one line — or turns a commented `# key = …` into the real thing, or inserts the key
33//! under its section header — so ordering, comments and unrelated lines survive exactly. What is
34//! written is then **proved**: the edited text is parsed as a [`Config`] and the key is read back
35//! to equal what was asked for. A setter that can leave an unloadable config behind is worse than
36//! no setter.
37
38use super::{is_secret_key, Config};
39use std::fmt;
40
41/// When a changed key takes effect.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Applies {
44    /// The next run reads it. Every key the agent is built from: the provider, the tools, the
45    /// context files, the hooks.
46    NextRun,
47    /// The process that is serving reads it once, at startup: `[web]`, which is the address, the
48    /// token and the session lifetime of an `eclipse-web` that is already running, and `[gateway]`,
49    /// whose intervals are captured when `eclipse-gateway` starts (`#403`).
50    RestartProcess,
51}
52
53/// Which sections a running process has already read.
54///
55/// `[gateway]`'s intervals are captured when `eclipse-gateway` starts, so a change to one is not
56/// "next run" — the separate process has to come up again for it to matter (`#403`).
57fn applies_to(section: &str) -> Applies {
58    match section {
59        "web" | "gateway" => Applies::RestartProcess,
60        _ => Applies::NextRun,
61    }
62}
63
64impl Applies {
65    pub fn as_str(&self) -> &'static str {
66        match self {
67            Applies::NextRun => "next run",
68            Applies::RestartProcess => "restart the background process",
69        }
70    }
71}
72
73/// The type a key holds, used both to validate what was typed and to say what went wrong.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Kind {
76    Str,
77    Integer,
78    Float,
79    Bool,
80    List,
81    Datetime,
82}
83
84impl Kind {
85    fn of(value: &toml::Value) -> Kind {
86        match value {
87            toml::Value::String(_) => Kind::Str,
88            toml::Value::Integer(_) => Kind::Integer,
89            toml::Value::Float(_) => Kind::Float,
90            toml::Value::Boolean(_) => Kind::Bool,
91            toml::Value::Array(_) => Kind::List,
92            toml::Value::Datetime(_) => Kind::Datetime,
93            // A table is not a setting; the catalogue skips them, so this is unreachable in
94            // practice and named anyway rather than guessed at.
95            toml::Value::Table(_) => Kind::List,
96        }
97    }
98}
99
100impl Kind {
101    /// The spelling a surface switches on — `"bool"`, `"integer"` — as opposed to [`Display`],
102    /// which is the same thing in a sentence. A control is chosen from this, so it is a closed set
103    /// on the wire and cannot be a sentence a page has to pattern-match.
104    pub fn as_str(self) -> &'static str {
105        match self {
106            Kind::Str => "str",
107            Kind::Integer => "integer",
108            Kind::Float => "float",
109            Kind::Bool => "bool",
110            Kind::List => "list",
111            Kind::Datetime => "datetime",
112        }
113    }
114}
115
116impl fmt::Display for Kind {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(match self {
119            Kind::Str => "a string",
120            Kind::Integer => "an integer",
121            Kind::Float => "a number",
122            Kind::Bool => "true or false",
123            Kind::List => "a list",
124            Kind::Datetime => "a date",
125        })
126    }
127}
128
129/// Whether this is the empty string — the spelling that means "not in use".
130fn is_empty_string(value: &toml::Value) -> bool {
131    matches!(value, toml::Value::String(s) if s.is_empty())
132}
133
134/// One key a person can read and write: `[section] key`, its default and its current value.
135#[derive(Debug, Clone, PartialEq)]
136pub struct Setting {
137    pub section: String,
138    pub key: String,
139    /// What this build uses when the file does not set it. `None` for a key that is simply absent
140    /// until somebody sets it (`provider.api_key`), which is not the same as an empty string.
141    pub default: Option<toml::Value>,
142    /// What the loaded config holds now. `None` when the key is unset.
143    pub value: Option<toml::Value>,
144    pub kind: Kind,
145    /// A secret: never printed, never rendered to a page, only set.
146    pub secret: bool,
147    pub applies: Applies,
148    /// One line: what this key does. See [`about`].
149    pub about: &'static str,
150    /// The values it accepts when the set is closed. See [`choices`].
151    pub choices: &'static [&'static str],
152}
153
154impl Setting {
155    /// `provider.model` — the spelling `config set` takes and the surfaces show.
156    pub fn path(&self) -> String {
157        format!("{}.{}", self.section, self.key)
158    }
159
160    /// Whether the loaded value is the default, so a surface can say "not set here".
161    pub fn is_default(&self) -> bool {
162        self.value == self.default
163    }
164
165    /// The value as a person should see it: the TOML rendering, a redaction for a secret, or
166    /// `(not set)` for a key the file leaves alone.
167    pub fn rendered(&self) -> String {
168        if self.secret {
169            return "«redacted»".to_string();
170        }
171        match &self.value {
172            Some(value) => render(value),
173            None => "(not set)".to_string(),
174        }
175    }
176
177    /// The default in the same form [`Self::rendered`] uses, when this build has one for the key.
178    ///
179    /// Not every absent key has a default (an API key has none), which is why it is an `Option`
180    /// and why `config keys` prints nothing rather than `(not set)` twice.
181    pub fn rendered_default(&self) -> Option<String> {
182        if self.secret {
183            return None;
184        }
185        self.default.as_ref().map(render)
186    }
187}
188
189impl fmt::Display for Setting {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        write!(f, "{} = {}", self.path(), self.rendered())?;
192        if self.is_default() {
193            write!(f, " (default)")?;
194        }
195        if self.applies == Applies::RestartProcess {
196            write!(f, " [{}]", self.applies.as_str())?;
197        }
198        Ok(())
199    }
200}
201
202/// Keys that exist, are read, and serialise to nothing when unset: `(table, key, type)`.
203///
204/// A field of type `Option<T>` that is `None` by default has no TOML representation, so the
205/// derived catalogue cannot see it. This list is the exception, and the test below is what keeps
206/// it honest.
207pub(crate) const ABSENT_BY_DEFAULT: &[(&str, &str, Kind)] = &[
208    // `[provider]`: everything `provider.rs` reads and a default config does not write.
209    ("flares", "total_tokens", Kind::Integer),
210    ("provider", "api_key", Kind::Str),
211    ("provider", "api_key_env", Kind::Str),
212    ("provider", "aux", Kind::Str),
213    ("provider", "delegate", Kind::Str),
214    ("provider", "fallback", Kind::List),
215    ("provider", "temperature", Kind::Float),
216    ("provider", "max_tokens", Kind::Integer),
217    ("provider", "profile", Kind::Str),
218    ("provider", "top_p", Kind::Float),
219    ("provider", "seed", Kind::Integer),
220    ("provider", "stop", Kind::List),
221    ("provider", "reasoning_effort", Kind::Str),
222    ("provider", "parallel_tool_calls", Kind::Bool),
223    ("provider", "tool_choice", Kind::Str),
224    ("provider", "vision", Kind::Bool),
225    ("agent", "output_schema", Kind::Str),
226    ("tools", "workspace_root", Kind::Str),
227    ("sessions", "dir", Kind::Str),
228    ("attachments", "dir", Kind::Str),
229    ("plugins", "dir", Kind::Str),
230    ("plugins", "mcp_timeout_secs", Kind::Integer),
231    ("web", "auth_token", Kind::Str),
232    ("web", "default_profile", Kind::Str),
233    ("cli", "color", Kind::Bool),
234    ("cli", "markdown", Kind::Bool),
235    ("update", "remote", Kind::Str),
236    ("update", "releases", Kind::Str),
237];
238
239/// Fields that are deliberately *not* settings, each for a reason the catalogue's own rule gives:
240/// structures (a table of routes, a map of per-hook options) are not scalar settings; `dotenv` is
241/// what the loader *read*, not something a person sets; and the `serde(skip)` fields come from the
242/// invocation (`--profile`, `--route`, `--no-mcp`), which their doc comments say outright.
243///
244/// It sits here, beside the list it complements, but only the completeness test reads it.
245#[cfg(test)]
246const NOT_SETTINGS: &[&str] = &[
247    "provider.route",
248    "provider.extra_body",
249    "hooks.settings",
250    "dotenv",
251    "profile",
252    "route_pin",
253    "no_mcp",
254];
255
256/// A key that is absent by default but still has an answer this build stands behind.
257///
258/// `provider.reasoning_effort` is the one: `ProviderConfig::default()` leaves it `None` on purpose
259/// (`unset = do not send` is what keeps an undeclared backend from being handed a field it may
260/// 400 on), while the two shipped profiles declare `medium` as their default (`#276`). So the key
261/// has a default a person can read — the level a fresh install resolves — without the config struct
262/// claiming every backend understands it.
263fn absent_default(section: &str, key: &str) -> Option<toml::Value> {
264    match (section, key) {
265        ("provider", "reasoning_effort") => Some(toml::Value::String(
266            crate::reasoning::SHIPPED_DEFAULT.into(),
267        )),
268        _ => None,
269    }
270}
271
272/// A TOML value as one line: strings quoted and escaped, everything else as TOML writes it.
273fn render(value: &toml::Value) -> String {
274    match value {
275        toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
276        other => other.to_string(),
277    }
278}
279
280impl Config {
281    /// Every scalar key this build knows, defaults and current values included, sorted by path.
282    ///
283    /// Nested tables and arrays of tables are skipped: they are structures, not settings (see the
284    /// module doc). Arrays of scalars are settings and are included.
285    pub fn settings(&self) -> Vec<Setting> {
286        let Ok(defaults) = toml::Value::try_from(Config::default()) else {
287            return Vec::new();
288        };
289        let Ok(current) = toml::Value::try_from(self) else {
290            return Vec::new();
291        };
292        let mut out = Vec::new();
293        for (section, table) in defaults.as_table().into_iter().flatten() {
294            let loaded = current.get(section).and_then(toml::Value::as_table);
295            for (key, default) in table.as_table().into_iter().flatten() {
296                if matches!(default, toml::Value::Table(_)) {
297                    continue;
298                }
299                if default
300                    .as_array()
301                    .is_some_and(|items| items.iter().any(toml::Value::is_table))
302                {
303                    continue;
304                }
305                let value = loaded.and_then(|t| t.get(key)).cloned();
306                out.push(Setting {
307                    section: section.clone(),
308                    key: key.clone(),
309                    kind: Kind::of(default),
310                    default: Some(default.clone()),
311                    value,
312                    secret: is_secret_key(key),
313                    applies: applies_to(section),
314                    about: "",
315                    choices: &[],
316                });
317            }
318        }
319        for (section, key, kind) in ABSENT_BY_DEFAULT {
320            let value = current
321                .get(section)
322                .and_then(toml::Value::as_table)
323                .and_then(|t| t.get(*key))
324                .cloned();
325            out.push(Setting {
326                section: (*section).to_string(),
327                key: (*key).to_string(),
328                kind: *kind,
329                default: absent_default(section, key),
330                value,
331                secret: is_secret_key(key),
332                applies: applies_to(section),
333                about: "",
334                choices: &[],
335            });
336        }
337        out.sort_by_key(Setting::path);
338        out.dedup_by(|a, b| a.path() == b.path());
339        // The words come from the tables above, keyed by the path the row shows: one lookup, so a
340        // row cannot be explained by one surface and blank in another.
341        for setting in &mut out {
342            let path = setting.path();
343            setting.about = about(&path);
344            setting.choices = choices(&path);
345            if let Some(kind) = word_default(&path) {
346                setting.kind = kind;
347            }
348        }
349        out
350    }
351
352    /// The setting `path` names (`provider.model`), if this build has it.
353    pub fn setting(&self, path: &str) -> Option<Setting> {
354        self.settings()
355            .into_iter()
356            .find(|s| s.path() == path.trim())
357    }
358}
359
360/// Parse one value as a person typed it.
361///
362/// TOML first — so `3`, `true`, `["a", "b"]` and `0.5` mean what they look like — and a bare word
363/// that is not valid TOML is a **string**, so `config set provider.model gemma-4-12b` does what it
364/// says instead of failing on a missing quote. That is the one ambiguity here, and it is settled
365/// in the direction a person typing a value expects.
366pub fn parse_value(raw: &str) -> toml::Value {
367    let raw = raw.trim();
368    if let Ok(value) = format!("v = {raw}").parse::<toml::Value>() {
369        if let Some(inner) = value.get("v") {
370            return inner.clone();
371        }
372    }
373    toml::Value::String(raw.to_string())
374}
375
376/// Set `path` to `value` in this config text, returning the new text.
377///
378/// Refuses, with a reason, when the key is not one this build reads, when the value has the wrong
379/// type for it, or when the edited text does not load back with that value. Nothing is written to
380/// disk here: the caller decides where the text goes, which is what lets the same function serve
381/// the CLI, the dashboard and the interface.
382pub fn set_in_text(
383    text: &str,
384    path: &str,
385    value: &toml::Value,
386) -> std::result::Result<String, String> {
387    let schema = Config::default();
388    let Some(setting) = schema.setting(path) else {
389        return Err(unknown_setting(&schema, path));
390    };
391    // `#545`: three spellings the catalogue documents and this function used to refuse, because it
392    // compared the typed value against the type of the *stored* one. A whole number for a float key
393    // is the same number (`context.compact_at 0` turns compaction off); `0` and `-1` for a turn
394    // budget are how a person writes "no limit", which the file spells `unlimited`; and a list key
395    // typed as `a,b` is a list. Normalise to the spelling the file will hold before the kind check
396    // and before the readback, so both compare like with like.
397    let normalised;
398    let value = match (&setting.kind, value) {
399        (Kind::Float, toml::Value::Integer(n)) => {
400            normalised = toml::Value::Float(*n as f64);
401            &normalised
402        }
403        (_, toml::Value::Integer(n)) if *n <= 0 && word_default(&setting.path()).is_some() => {
404            normalised = toml::Value::String("unlimited".to_string());
405            &normalised
406        }
407        (Kind::List, toml::Value::String(raw)) => {
408            normalised = toml::Value::Array(
409                raw.split(',')
410                    .map(str::trim)
411                    .filter(|s| !s.is_empty())
412                    .map(|s| toml::Value::String(s.to_string()))
413                    .collect(),
414            );
415            &normalised
416        }
417        // `agent.prompt_blocks` is `auto`, `off` or a list, so its catalogue value is a word and a
418        // list never matched it: `a,b` was written as a string the loader then refused.
419        (_, toml::Value::String(raw)) if takes_a_list(&setting.path()) && raw.contains(',') => {
420            normalised = toml::Value::Array(
421                raw.split(',')
422                    .map(str::trim)
423                    .filter(|s| !s.is_empty())
424                    .map(|s| toml::Value::String(s.to_string()))
425                    .collect(),
426            );
427            &normalised
428        }
429        _ => value,
430    };
431    let typed = Kind::of(value);
432    // A number-spelled-as-a-word key takes either spelling: `40` and `unlimited` are the two things
433    // a person types for a turn budget, and neither is a mistake.
434    if typed != setting.kind
435        && !(setting.kind == Kind::Integer && is_unlimited(value))
436        && !(takes_a_list(&setting.path()) && typed == Kind::List)
437    {
438        return Err(format!(
439            "`{}` holds {} — {} is {}",
440            setting.path(),
441            setting.kind,
442            render(value),
443            typed
444        ));
445    }
446    let edited = super::toml_set_value(text, &setting.section, &setting.key, &render(value));
447    let checked = super::parse_text(&edited).map_err(|e| {
448        format!(
449            "that would not load, so nothing was saved: {}",
450            one_line(&e.to_string())
451        )
452    })?;
453    // `parse_text` reads the file; it does not run the route checks `load` runs. So a
454    // `vision.route` that names nothing was written happily and the *next* load failed (`#385`).
455    // Only the keys that name a route are checked here: refusing an unrelated edit because the
456    // file was already broken elsewhere would trap the person who is trying to fix it.
457    if names_a_route(&setting) {
458        checked.validate_routes().map_err(|e| {
459            format!(
460                "that would not load, so nothing was saved: {}",
461                one_line(&e.to_string())
462            )
463        })?;
464    }
465    // `[context]` is the other block whose keys are checked at load — a share outside 0..=1, a
466    // handoff too small to compile. Unchecked here, `config set context.compact_at 1.5` saved and
467    // every later command died in `load_with_profile` (#540).
468    if setting.section == "context" {
469        checked.context.validate().map_err(|e| {
470            format!(
471                "that would not load, so nothing was saved: {}",
472                one_line(&e.to_string())
473            )
474        })?;
475    }
476    match checked.setting(&setting.path()) {
477        Some(after) if after.value.as_ref() == Some(value) => Ok(edited),
478        // An empty value *is* absence (`empty_is_none`, `Dotenv::load`), so `key = ""` proves itself
479        // by loading as "not set". Without this arm every key whose shipped spelling is `""` could
480        // not be written at all — `config set … ""` and a migration adding `aux = ""` both fail on
481        // their own correct output.
482        Some(after) if is_empty_string(value) && after.value.is_none() => Ok(edited),
483        Some(after) => Err(format!(
484            "the file would read `{}` back as {}, not {}; nothing was saved",
485            setting.path(),
486            after.rendered(),
487            render(value)
488        )),
489        None => Err(format!(
490            "`{}` disappeared from the file when it was edited; nothing was saved",
491            setting.path()
492        )),
493    }
494}
495
496/// Set a list-valued key from `items` — `plugins.enabled = ["a", "b"]`.
497///
498/// The same proof as [`set_in_text`], and the reason it exists as its own function: a caller that
499/// has `Vec<String>` should not have to build a `toml::Value` to say so, and the CLI does not
500/// otherwise depend on the `toml` crate.
501pub fn set_list_in_text(
502    text: &str,
503    path: &str,
504    items: &[String],
505) -> std::result::Result<String, String> {
506    let value = toml::Value::Array(items.iter().cloned().map(toml::Value::String).collect());
507    set_in_text(text, path, &value)
508}
509
510/// One line per key: what it does, in words a person choosing it can use.
511///
512/// It lives here rather than in a doc comment because a doc comment is not a value at runtime, and
513/// the window, `/settings` in the composer and `eclipse config keys` all have to say the same thing
514/// (the rule the palette and the command table follow). A test asserts every key in
515/// [`Config::settings`] has one, so a new key cannot ship unexplained.
516pub fn about(path: &str) -> &'static str {
517    const ABOUT: &[(&str, &str)] = &[
518        // [agent]
519        ("agent.context_file_max_chars", "Truncate one context file past this many characters, keeping its head and tail; 0 = no per-file cap"),
520        ("agent.context_files_budget_chars", "Ceiling across every context file; whole files are dropped past it, broadest first"),
521        ("agent.max_consecutive_malformed_tool_calls", "Stop the run after this many consecutive tool calls that could not be used"),
522        ("agent.max_iterations", "How many model-and-tool round trips one turn may take"),
523        ("agent.output_schema", "A JSON Schema every reply must satisfy, as a path or inline JSON"),
524        ("agent.system_prompt", "The standing instructions every run starts with, added to the built-in prompt rather than replacing it"),
525        ("agent.trace_content", "Include prompts, arguments and results in trace spans"),
526        (
527            "agent.prompt_blocks",
528            "Standing prompt blocks after system_prompt: `auto` (per model family), a list of names, or `off`",
529        ),
530        // [cli]
531        (
532            "cli.approval",
533            "What an `ask` policy does: `ask` prompts, `auto` never does, `smart` asks a cheap model first and escalates when it is unsure",
534        ),
535        ("cli.clear_on_exit", "What an interactive exit does to the screen: `screen`, `all` or `off`"),
536        ("cli.color", "Colour on a terminal; unset means decide from the stream, and from `NO_COLOR`"),
537        ("cli.history_size", "How many commands the REPL remembers for arrow-up"),
538        ("cli.markdown", "Markdown in replies; unset means on when colour is on"),
539        // [context]
540        ("context.compact_at", "Share of the model's window at which a request is compacted, e.g. 0.85; 0 turns the threshold off"),
541        ("context.handoff_chars", "Hard cap, in characters, on the compiled handoff that stands in for the dropped middle"),
542        ("context.judge", "Ask one model one bounded question about why the dropped turns went the way they did"),
543        ("context.judge_timeout_secs", "How long that one call may take before the deterministic handoff ships without it"),
544        ("context.protect_last_n", "Turns kept verbatim at the tail; 0 is read as 1"),
545        ("context.window_tokens", "The window to assume when the endpoint advertises none; 0 assumes nothing"),
546        // [gateway]
547        ("gateway.api_session_ttl_hours", "How long a session made by `POST /v1/chat/completions` is kept"),
548        ("gateway.check_interval_hours", "How often the gateway runs the update check and logs what it found"),
549        // [hooks]
550        // An unlisted hook does not run at all (`hooks.rs`: it is drawn as "(off)"), which is the
551        // opposite of what this sentence used to say — an operator who wrote
552        // `order = ["recall-sessions"]` from it silently turned `redact-secrets` off (#537).
553        ("hooks.order", "The hooks that run, and in what order, by name; one that is not listed does not run, and `[]` runs none"),
554        // [plugins]
555        ("plugins.dir", "Root of the shared plugin directory (default `<config_dir>/plugins`)"),
556        ("plugins.enabled", "The plugins to load, by directory name; one that is not listed loads only as a wire profile"),
557        ("plugins.mcp_timeout_secs", "Ceiling on one MCP call, for `[[mcp]]` entries that state none of their own"),
558        // [provider]
559        ("provider.api_key", "A key written into the file; prefer `api_key_env` or `ECLIPSE_API_KEY`, which keep it out of it"),
560        ("provider.api_key_env", "Name of an environment variable holding the key"),
561        ("provider.aux", "The route that does the agent's own housekeeping — the summary of trimmed turns — and never the user's work"),
562        ("provider.base_url", "Base URL of an OpenAI-compatible API, up to the `/v1`"),
563        ("provider.context_budget_tokens", "Soft cap on the conversation sent to the model, in estimated tokens (characters / 4, a rough heuristic)"),
564        ("provider.delegate", "The route a `delegate` call's child agent runs on unless the call names one"),
565        ("provider.fallback", "The routes tried in order when a request fails for a transient reason"),
566        ("provider.max_retries", "Extra attempts after a request fails with 408, 429 or 5xx, or could not be sent (0 = never)"),
567        ("provider.max_tokens", "Cap on the reply, in tokens"),
568        ("provider.model", "The model every request asks for"),
569        ("provider.parallel_tool_calls", "Ask for several tool calls in one reply"),
570        ("provider.profile", "Wire profile: `openai` (default), `llamacpp`, or one a plugin declares"),
571        ("provider.reasoning_effort", "How much the model thinks, on backends that have the knob (`low`, `medium`, `high` …), or `omit` to put no reasoning field on the wire at all"),
572        ("provider.retry_after_send", "Also retry a request that failed after it went out — a dropped connection, or nothing for `timeout_secs`"),
573        ("provider.retry_base_delay_ms", "How long the first retry waits; each further attempt doubles it"),
574        ("provider.seed", "Ask for a reproducible sample, where the backend supports it"),
575        ("provider.stop", "Up to four sequences the reply stops at"),
576        ("provider.stream", "Ask for a token-by-token (SSE) reply"),
577        ("provider.temperature", "Sampling temperature, unset leaves whatever the server defaults to"),
578        ("provider.timeout_secs", "Ceiling on one request, from connect to last byte"),
579        ("provider.tool_choice", "`auto`, `none`, `required`, or one tool's name"),
580        ("provider.top_p", "Nucleus sampling: draw from the smallest set of tokens holding this much probability"),
581        ("provider.vision", "Declare whether this route's model can see images (overrides the wire profile)"),
582        // [attachments]
583        (
584            "attachments.dir",
585            "Where attached pictures are stored; defaults to `<state_dir>/attachments`"
586        ),
587        (
588            "attachments.max_total_bytes",
589            "Ceiling for every picture kept on disk, in bytes; the oldest are pruned when an attach would exceed it, and only then is an attach refused (0 = no ceiling)"
590        ),
591        // [sessions]
592        ("sessions.auto_prune", "Apply the retention limits when the CLI starts, before the first prompt"),
593        ("sessions.autotitle", "Name sessions: a name derived from the opening message, plus at most one small-model call"),
594        ("sessions.dir", "Where sessions are stored; defaults to `<state_dir>/sessions`"),
595        ("sessions.lock_wait_secs", "How long a run waits for another process to release the same session; 0 fails on the first refusal"),
596        ("sessions.retention_keep_count", "Default for `sessions prune --keep-count`: keep only the newest N; 0 = disabled"),
597        ("sessions.retention_keep_days", "Default for `sessions prune --keep-days`: delete sessions idle longer than this; 0 = disabled"),
598        // [skills]
599        ("skills.index_budget_chars", "Ceiling for the skill index in the system prompt, in characters"),
600        // [vision]
601        ("vision.mode", "A picture goes to the turn's model (`native`), to a route that describes it (`text`), or wherever the model's declared vision allows (`auto`)"),
602        ("vision.route", "The route that describes a picture, for `text` and for `auto`'s fallback; empty means there is none"),
603        ("vision.allow_cloud", "Let a picture be described by a route that is not on this machine"),
604        // [flares]
605        ("flares.count", "Default number of jobs for `flares run -n`; a local run starts from it (default 3)"),
606        ("flares.max_concurrent", "The most flares one run may have in flight, whatever the routes allow"),
607        ("flares.max_iterations", "Per flare, when the job does not say: what `delegate` gives a child"),
608        ("flares.total_iterations", "The run's own budget: what stops one wandering flare eating the others' turns"),
609        ("flares.total_tokens", "Optional spend cap for the whole run, in tokens; unset = the budgets are the ceiling"),
610        // [tools]
611        ("tools.concurrency", "How many of one turn's tool calls run at the same time; 1 runs them in order"),
612        ("tools.deferred", "Tools that stay callable but are not described in the request, so they cost no tokens until needed"),
613        ("tools.delegate", "The `delegate` tool's policy: hand a job to a child agent"),
614        ("tools.disabled", "Tools removed entirely, whatever their policy says"),
615        ("tools.execute_code", "The `execute_code` tool: a short program run from a temporary file, with a bridge to the tools"),
616        ("tools.fetch", "The `fetch` tool: one URL in, its text out"),
617        ("tools.fetch_html", "`text` renders HTML responses as plain text; `raw` returns the source"),
618        ("tools.fetch_timeout_secs", "Ceiling on one `fetch`"),
619        ("tools.max_output_bytes", "Tool output is cut to this many bytes before the model sees it"),
620        ("tools.memory", "The `memory` tool's policy: write a durable fact to MEMORY.md"),
621        ("tools.patch", "The `patch` tool's policy: a targeted edit of a file that already exists"),
622        ("tools.read_file", "The `read_file` tool"),
623        ("tools.rewrite_guard_bytes", "Above this size, `write_file` needs `force` to clobber an existing file"),
624        ("tools.script", "The `script` tool's policy: run a file from the scripts directory"),
625        ("tools.search_files", "The `search_files` tool's policy: a read-only walk of the workspace"),
626        ("tools.shell", "The `shell` tool: run a command on this machine"),
627        ("tools.shell_allowlist", "If set, `shell` may only run these program names, without a shell"),
628        ("tools.shell_ask", "Which `shell` commands ask first: `dangerous` asks only for the un-undoable ones"),
629        ("tools.shell_isolate", "What a `shell` command can reach: `off`, `process` (private PID namespace) or `fs` (bubblewrap)"),
630        ("tools.shell_isolate_hide", "Paths replaced by an empty directory in `fs` mode, so nothing in them can be read"),
631        ("tools.shell_isolate_network", "Whether `fs` isolation keeps the network"),
632        ("tools.shell_isolate_writable", "Extra paths bound read-write in `fs` mode, beyond the workspace and the scripts directory"),
633        ("tools.shell_timeout_secs", "Ceiling on one `shell` command"),
634        ("tools.tool_call", "Call a tool a search found, without it being described up front"),
635        ("tools.tool_describe", "Ask for a deferred tool's full schema"),
636        ("tools.tool_search", "The `tool_search` tool's policy: look for a deferred tool"),
637        ("tools.workspace_root", "The file tools are confined to this directory"),
638        ("tools.write_file", "The `write_file` tool"),
639        // [update]
640        ("update.check", "How often the update check asks: `daily`, `weekly` or `off`"),
641        ("update.releases", "Where the newest release is asked for, instead of the public GitHub repository"),
642        ("update.remote", "Where the latest commit is asked for, instead of the public GitHub repository"),
643        ("update.track", "Which branch a source install follows: `release` is main, `develop` is the branch work lands on"),
644        // [user]
645        ("user.file", "The user model file, relative to the config directory unless absolute"),
646        ("user.memory_budget_chars", "Ceiling for `MEMORY.md` in characters"),
647        ("user.memory_file", "The agent's memory file, resolved the same way"),
648        // [web]
649        ("web.auth_token", "The dashboard's login secret, generated by `config init`"),
650        ("web.default_profile", "The profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE` names one"),
651        ("web.host", "The address the dashboard binds; loopback only"),
652        ("web.port", "The port the dashboard listens on"),
653        ("web.session_ttl_hours", "How long a browser stays signed in"),
654    ];
655    ABOUT
656        .iter()
657        .find(|(key, _)| *key == path)
658        .map(|(_, about)| *about)
659        .unwrap_or("")
660}
661
662/// The values a key accepts, when the set is closed — the words a control can offer.
663///
664/// Empty for a key that takes what it takes: a path, a URL, a number. A `select` is only ever built
665/// from this list, so the page cannot invent an option the parser would then refuse.
666/// Keys whose default is *spelled as a word* while the key itself is a number.
667///
668/// `agent.max_iterations` serialises `usize::MAX` as `"unlimited"` — right for `config show`, wrong
669/// as a description of the type, and it made `config set agent.max_iterations 40` refuse a whole
670/// number for being the wrong kind. The word stays legal input; the kind a control reads is the
671/// number.
672fn word_default(path: &str) -> Option<Kind> {
673    match path {
674        "agent.max_iterations" => Some(Kind::Integer),
675        _ => None,
676    }
677}
678
679/// The words [`word_default`]'s key accepts instead of a number.
680const UNLIMITED: &[&str] = &[
681    "unlimited",
682    "none",
683    "null",
684    "inf",
685    "infinite",
686    "infinity",
687    "∞",
688];
689
690fn is_unlimited(value: &toml::Value) -> bool {
691    value
692        .as_str()
693        .is_some_and(|w| UNLIMITED.contains(&w.trim().to_ascii_lowercase().as_str()))
694}
695
696/// Keys that are a word *or* a list.
697///
698/// `agent.prompt_blocks` defaults to `auto` and also takes `["task-completion", …]`, so the kind
699/// the catalogue reads — from the default — is a string, and a list typed for it compared unequal
700/// and was refused (`#545`). The list is written as one; the two words stay legal.
701fn takes_a_list(path: &str) -> bool {
702    matches!(path, "agent.prompt_blocks")
703}
704
705pub fn choices(path: &str) -> &'static [&'static str] {
706    const ANY: &[&str] = &["deny", "ask", "allow"];
707    match path {
708        // A tool's policy, which is the same three words for every tool.
709        p if p.starts_with("tools.")
710            && matches!(
711                p.split_once('.').map(|(_, k)| k),
712                Some(
713                    "delegate"
714                        | "execute_code"
715                        | "fetch"
716                        | "memory"
717                        | "patch"
718                        | "read_file"
719                        | "script"
720                        | "search_files"
721                        | "shell"
722                        | "tool_call"
723                        | "tool_describe"
724                        | "tool_search"
725                        | "write_file"
726                )
727            ) =>
728        {
729            ANY
730        }
731        // Three values, so it gets a list like every other enumeration: without this the settings
732        // form and `config set vision.mode <TAB>` offered nothing for a key that only accepts
733        // these three words (`#424`).
734        "vision.mode" => &["native", "text", "auto"],
735        // `smart` shipped in #340 and was missing here, so the dashboard's select could not offer
736        // the mode the build supports (#546).
737        "cli.approval" => &["ask", "auto", "smart"],
738        "cli.clear_on_exit" => &["screen", "all", "off"],
739        "tools.fetch_html" => &["text", "raw"],
740        "tools.shell_ask" => &["dangerous", "always"],
741        "tools.shell_isolate" => &["off", "process", "fs"],
742        "update.check" => &["daily", "weekly", "off"],
743        "update.track" => &["release", "develop"],
744        _ => &[],
745    }
746}
747
748/// Whether this key names a provider route, in the shape the checks care about.
749fn names_a_route(setting: &Setting) -> bool {
750    names_a_route_path(&setting.path())
751}
752
753fn names_a_route_path(path: &str) -> bool {
754    // `provider.fallback` names routes as surely as `provider.aux` does, and an unchecked write of
755    // it broke every later load (#540).
756    path.starts_with("provider.route")
757        || matches!(
758            path,
759            "provider.aux" | "provider.delegate" | "provider.fallback" | "vision.route"
760        )
761}
762
763/// Comment `path` out of this config text, so the file falls back to its default.
764///
765/// Commented rather than deleted: the line's neighbours explain it, and a person who unsets
766/// `web.port` should still be able to see what the key is called.
767pub fn unset_in_text(text: &str, path: &str) -> std::result::Result<String, String> {
768    let schema = Config::default();
769    let Some(setting) = schema.setting(path) else {
770        return Err(unknown_setting(&schema, path));
771    };
772    let edited = super::toml_comment_out(text, &setting.section, &setting.key);
773    let checked = super::parse_text(&edited).map_err(|e| {
774        format!(
775            "that would not load, so nothing was saved: {}",
776            one_line(&e.to_string())
777        )
778    })?;
779    match checked.setting(&setting.path()) {
780        // "Falls back to its default" is checked against what a `Config::default()` holds for the
781        // key, not against the catalogue's `default` column: `provider.reasoning_effort` reports
782        // `medium` there (the level the shipped profiles resolve, `#276`) while the config struct
783        // leaves the field absent on purpose, so the honest check for "the line is gone and the
784        // resolver is in charge" is that the file now reads what a default file reads.
785        Some(after) if after.value == setting.value => Ok(edited),
786        Some(after) => Err(format!(
787            "the file would still read `{}` as {}; nothing was saved",
788            setting.path(),
789            after.rendered()
790        )),
791        None => Err(format!(
792            "`{}` disappeared from the file when it was edited; nothing was saved",
793            setting.path()
794        )),
795    }
796}
797
798/// The refusal for a path this build does not have, naming what does exist and — the mistake that
799/// started `config check` — the table that *does* read a key of that name.
800fn unknown_setting(schema: &Config, path: &str) -> String {
801    let path = path.trim();
802    let (section, key) = path.split_once('.').unwrap_or(("", path));
803    let settings = schema.settings();
804    if let Some(elsewhere) = settings.iter().find(|s| s.key == key) {
805        return format!(
806            "`{path}` is not a setting: `{key}` is read under [{}]. Write `{}`.",
807            elsewhere.section,
808            elsewhere.path()
809        );
810    }
811    let mut near: Vec<String> = settings
812        .iter()
813        .filter(|s| s.key.contains(key) || key.contains(&s.key) || s.section == section)
814        .map(Setting::path)
815        .take(8)
816        .collect();
817    if near.is_empty() {
818        near = settings.iter().take(8).map(Setting::path).collect();
819    }
820    format!(
821        "`{path}` is not a setting in this build. `eclipse config keys` lists all of them; \
822         close to what you wrote: {}",
823        near.join(", ")
824    )
825}
826
827pub(super) fn one_line(text: &str) -> String {
828    text.split_whitespace().collect::<Vec<_>>().join(" ")
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834
835    fn paths() -> Vec<String> {
836        Config::default()
837            .settings()
838            .into_iter()
839            .map(|s| s.path())
840            .collect()
841    }
842
843    /// `#545`: three spellings the catalogue documents that `set_in_text` refused with a message
844    /// about kinds, because it compared the typed value against the type of the stored one.
845    #[test]
846    fn the_three_spellings_the_catalogue_documents_are_written() {
847        let text = crate::config::starter_config().unwrap();
848
849        // `context.compact_at 0` turns compaction off. The key is a float and TOML has no way to
850        // spell "zero, as a float" without a decimal point.
851        let edited = set_in_text(&text, "context.compact_at", &parse_value("0"))
852            .expect("a whole number is a number");
853        assert!(
854            crate::config::parse_text(&edited)
855                .unwrap()
856                .context
857                .compact_at
858                == 0.0,
859            "the threshold reads back as off: {edited}"
860        );
861
862        // `0` and `-1` are how a person writes "no cap"; the file spells it `unlimited`.
863        for raw in ["0", "-1"] {
864            let edited = set_in_text(&text, "agent.max_iterations", &parse_value(raw))
865                .unwrap_or_else(|e| panic!("`{raw}` is a turn budget: {e}"));
866            assert!(
867                edited.contains("max_iterations = \"unlimited\""),
868                "`{raw}` should be stored as the word: {edited}"
869            );
870        }
871
872        // A list key typed as `a,b` is a list, not a string that the loader then refuses.
873        let edited = set_in_text(
874            &text,
875            "agent.prompt_blocks",
876            &parse_value("task-completion,parallel-tool-calls"),
877        )
878        .expect("a comma list is a list");
879        assert!(
880            edited.contains("prompt_blocks = [\"task-completion\", \"parallel-tool-calls\"]"),
881            "the list is written as one: {edited}"
882        );
883    }
884
885    #[test]
886    fn the_catalogue_is_derived_from_the_config_itself() {
887        let paths = paths();
888        assert!(paths.contains(&"provider.model".to_string()), "{paths:?}");
889        assert!(paths.contains(&"tools.shell".to_string()), "{paths:?}");
890        assert!(paths.contains(&"web.port".to_string()), "{paths:?}");
891        // Structures are not settings.
892        assert!(
893            !paths.iter().any(|k| k.starts_with("provider.route")),
894            "a route is a table to edit, not a value: {paths:?}"
895        );
896        assert!(
897            paths.iter().all(|k| k.matches('.').count() == 1),
898            "{paths:?}"
899        );
900        // Sorted, so three surfaces cannot list them in three orders.
901        let mut sorted = paths.clone();
902        sorted.sort();
903        assert_eq!(paths, sorted);
904    }
905
906    /// The catalogue is derived from `Config::default()`, which omits every `Option` that is `None`.
907    /// That is how ten provider keys, `web.auth_token`, `cli.color`, `update.remote` and the rest
908    /// came to exist without being settable: `config set provider.temperature 0.5` answered
909    /// "unknown setting" for a field the agent reads on every request.
910    ///
911    /// The assignments below are the checklist, and the compiler keeps it honest: a renamed or
912    /// deleted field stops this test building, and a field nobody assigns simply does not appear in
913    /// the serialised config, so the walk cannot claim it.
914    #[test]
915    fn every_field_a_default_config_omits_is_still_settable() {
916        let mut c = Config::default();
917        c.provider.api_key = Some("probe".into());
918        c.provider.api_key_env = Some("PROBE_KEY".into());
919        c.provider.aux = Some("mmnuc/small".into());
920        c.provider.delegate = Some("mmnuc/small".into());
921        c.provider.fallback = Some(vec!["local".into()]);
922        c.provider.temperature = Some(0.5);
923        c.provider.max_tokens = Some(1024);
924        c.provider.profile = Some("openai".into());
925        c.provider.top_p = Some(0.9);
926        c.provider.seed = Some(7);
927        c.provider.stop = Some(vec!["</s>".into()]);
928        c.provider.reasoning_effort = Some("low".into());
929        c.provider.parallel_tool_calls = Some(true);
930        c.provider.vision = Some(true);
931        c.provider.tool_choice = Some(crate::hooks::ToolChoice::Auto);
932        c.provider.extra_body = Some(serde_json::json!({"chat_template_kwargs": {"x": 1}}));
933        c.agent.output_schema = Some("{}".into());
934        c.tools.workspace_root = Some(std::path::PathBuf::from("/w"));
935        c.sessions.dir = Some(std::path::PathBuf::from("/s"));
936        c.plugins.dir = Some(std::path::PathBuf::from("/p"));
937        c.plugins.mcp_timeout_secs = Some(30);
938        c.web.auth_token = Some("probe-token".into());
939        c.web.default_profile = Some("work".into());
940        c.cli.color = Some(false);
941        c.cli.markdown = Some(true);
942        c.update.remote = Some("https://mirror.internal/latest".into());
943        c.update.releases = Some("https://mirror.internal/releases".into());
944
945        let filled = toml::Value::try_from(&c).expect("a filled config serialises");
946        let schema = Config::default();
947        let mut checked = 0;
948        for (section, table) in filled.as_table().expect("a table").iter() {
949            let Some(table) = table.as_table() else {
950                continue;
951            };
952            for key in table.keys() {
953                let path = format!("{section}.{key}");
954                if NOT_SETTINGS.contains(&path.as_str()) {
955                    continue;
956                }
957                assert!(
958                    schema.setting(&path).is_some(),
959                    "`{path}` is a real field but not a setting: `config set {path} …` would refuse it"
960                );
961                checked += 1;
962            }
963        }
964        assert!(
965            checked > 60,
966            "the walk has to see the whole catalogue, not a corner: {checked}"
967        );
968    }
969
970    /// `agent.max_iterations` serialises its off value as the word `unlimited`, which made the
971    /// catalogue call it a string and refuse `config set agent.max_iterations 40`. Both spellings
972    /// are legal input, and the kind a control reads is the number.
973    #[test]
974    fn a_turn_budget_takes_a_number_and_the_word_for_no_cap() {
975        let schema = Config::default();
976        let setting = schema.setting("agent.max_iterations").expect("a setting");
977        assert_eq!(setting.kind, Kind::Integer, "a number, not a word");
978
979        let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
980        let cfg = super::super::parse_text(&edited).unwrap();
981        assert_eq!(cfg.agent.max_iterations, 40);
982
983        let edited = set_in_text(
984            "",
985            "agent.max_iterations",
986            &toml::Value::String("unlimited".into()),
987        )
988        .unwrap();
989        let cfg = super::super::parse_text(&edited).unwrap();
990        assert_eq!(cfg.agent.max_iterations, usize::MAX);
991
992        // Something that is neither is still refused, with the field's own sentence.
993        let refused = set_in_text(
994            "",
995            "agent.max_iterations",
996            &toml::Value::String("lots".into()),
997        )
998        .unwrap_err();
999        assert!(refused.contains("max_iterations"), "{refused}");
1000    }
1001
1002    /// Every key has a line explaining it, and only a closed set has `choices` — the two things a
1003    /// settings window needs and cannot invent.
1004    #[test]
1005    fn every_key_is_explained_and_the_closed_sets_name_their_values() {
1006        let settings = Config::default().settings();
1007        assert!(
1008            settings.len() > 80,
1009            "the whole catalogue: {}",
1010            settings.len()
1011        );
1012        for s in &settings {
1013            assert!(
1014                !s.about.trim().is_empty(),
1015                "{} has no description — add it to `about`",
1016                s.path()
1017            );
1018            assert!(s.about.len() < 160, "{}: too long for a row", s.path());
1019            assert!(
1020                !s.about.ends_with('.'),
1021                "{}: no trailing full stop",
1022                s.path()
1023            );
1024        }
1025        // `#537`: the catalogue said a hook that is not named runs *after* the ones that are,
1026        // while the loader does not run it at all — so `order = ["recall-sessions"]` written from
1027        // that sentence silently turned `redact-secrets` off.
1028        assert!(
1029            about("hooks.order").contains("does not run"),
1030            "{}",
1031            about("hooks.order")
1032        );
1033        assert_eq!(choices("cli.approval"), &["ask", "auto", "smart"]);
1034        assert_eq!(choices("tools.read_file"), &["deny", "ask", "allow"]);
1035        assert!(choices("provider.model").is_empty());
1036    }
1037
1038    /// The hand-written list earns its place: every entry must be a real field, settable, and
1039    /// readable back. An entry for a field that does not exist fails here rather than in the
1040    /// middle of somebody's config edit.
1041    #[test]
1042    fn every_key_that_is_absent_by_default_is_real_and_settable() {
1043        for (section, key, kind) in ABSENT_BY_DEFAULT {
1044            let path = format!("{section}.{key}");
1045            let sample = match kind {
1046                // The three keys that name a route are validated by the command that writes them
1047                // (`#385`), so the probe has to name a route that exists: `default` is the one
1048                // `[provider]` itself provides.
1049                Kind::Str if names_a_route_path(&path) => toml::Value::String("default".into()),
1050                Kind::Str => toml::Value::String("probe".into()),
1051                Kind::Integer => toml::Value::Integer(7),
1052                Kind::Float => toml::Value::Float(0.5),
1053                Kind::Bool => toml::Value::Boolean(true),
1054                // `provider.fallback` is a list *of route names*, and since `#540` the writer
1055                // checks it: a probe that named a route which does not exist would be refused by
1056                // the very check the entry is here to prove.
1057                Kind::List if names_a_route_path(&path) => {
1058                    toml::Value::Array(vec![toml::Value::String("default".into())])
1059                }
1060                Kind::List => toml::Value::Array(vec![toml::Value::String("probe".into())]),
1061                Kind::Datetime => continue,
1062            };
1063            let edited = set_in_text("", &path, &sample).unwrap_or_else(|e| panic!("{path}: {e}"));
1064            let cfg = super::super::parse_text(&edited).unwrap_or_else(|e| panic!("{path}: {e}"));
1065            assert_eq!(
1066                cfg.setting(&path).and_then(|s| s.value),
1067                Some(sample),
1068                "{path} did not read back — is it a real field?"
1069            );
1070        }
1071    }
1072
1073    #[test]
1074    fn an_absent_key_reports_itself_as_unset_and_is_not_the_default() {
1075        let schema = Config::default();
1076        let key = schema
1077            .setting("provider.api_key")
1078            .expect("api_key is a setting");
1079        assert!(key.secret, "a key by that name is a secret");
1080        assert_eq!(
1081            key.rendered(),
1082            "«redacted»",
1083            "never printed, even when unset"
1084        );
1085        assert_eq!(key.value, None, "absent is not the empty string");
1086        let plain = schema
1087            .setting("provider.model")
1088            .expect("model is a setting");
1089        assert!(!plain.secret);
1090    }
1091
1092    /// Found by running `config keys` on a real install: `window_tokens` was `«redacted»`
1093    /// because it contains "token", which hid a number a person has to be able to set.
1094    #[test]
1095    fn a_count_is_not_a_credential() {
1096        let schema = Config::default();
1097        let window = schema
1098            .setting("context.window_tokens")
1099            .expect("window_tokens is a setting");
1100        assert!(!window.secret, "a token count is not a token");
1101        assert_eq!(window.rendered(), "0", "and its value is readable");
1102        assert!(schema.setting("provider.api_key").unwrap().secret);
1103        assert!(
1104            !schema.setting("provider.api_key_env").unwrap().secret,
1105            "the name of a variable is not the variable"
1106        );
1107    }
1108
1109    #[test]
1110    fn setting_a_key_edits_one_line_and_everything_else_survives() {
1111        let text = "# my provider\n[provider]\n# the name the endpoint serves\nmodel = \"old\"\n\n[web]\nport = 8787\n";
1112        let edited =
1113            set_in_text(text, "provider.model", &toml::Value::String("new".into())).unwrap();
1114        assert!(edited.contains("model = \"new\""), "{edited}");
1115        assert!(
1116            edited.contains("# my provider") && edited.contains("# the name"),
1117            "{edited}"
1118        );
1119        assert!(edited.contains("port = 8787"), "{edited}");
1120        assert!(!edited.contains("\"old\""), "{edited}");
1121    }
1122
1123    #[test]
1124    fn a_typed_value_is_written_as_toml_and_read_back() {
1125        let text = "[web]\nport = 8787\n";
1126        let edited = set_in_text(text, "web.port", &toml::Value::Integer(9000)).unwrap();
1127        assert!(edited.contains("port = 9000"), "{edited}");
1128        let cfg = super::super::parse_text(&edited).unwrap();
1129        assert_eq!(cfg.web.port, 9000);
1130    }
1131
1132    #[test]
1133    fn a_value_of_the_wrong_shape_is_refused_with_the_shape_it_wants() {
1134        let text = "[web]\nport = 8787\n";
1135        let err = set_in_text(text, "web.port", &toml::Value::String("nine".into())).unwrap_err();
1136        assert!(err.contains("`web.port` holds an integer"), "{err}");
1137        assert!(err.contains("\"nine\" is a string"), "{err}");
1138
1139        let err =
1140            set_in_text(text, "web.session_ttl_hours", &toml::Value::Boolean(true)).unwrap_err();
1141        assert!(err.contains("an integer"), "{err}");
1142    }
1143
1144    #[test]
1145    fn a_key_this_build_does_not_read_is_refused_and_the_right_table_is_named() {
1146        let text = "[web]\n";
1147        let err = set_in_text(text, "web.model", &toml::Value::String("m".into())).unwrap_err();
1148        assert!(err.contains("`model` is read under [provider]"), "{err}");
1149        assert!(err.contains("provider.model"), "{err}");
1150
1151        let err = set_in_text(text, "provider.modl", &toml::Value::String("m".into())).unwrap_err();
1152        assert!(err.contains("is not a setting"), "{err}");
1153        assert!(err.contains("config keys"), "where to look: {err}");
1154    }
1155
1156    /// `#540`: the keys checked at load are the keys that have to be checked after an edit, or
1157    /// `config set` writes a file every later command dies on.
1158    #[test]
1159    fn a_fallback_naming_a_route_that_does_not_exist_is_refused() {
1160        let text = "[provider]\nbase_url = \"http://127.0.0.1:8080/v1\"\nmodel = \"m\"\n";
1161        let err = set_in_text(
1162            text,
1163            "provider.fallback",
1164            &toml::Value::Array(vec![toml::Value::String("ghost".into())]),
1165        )
1166        .unwrap_err();
1167        assert!(err.contains("ghost"), "{err}");
1168        assert!(err.contains("nothing was saved"), "{err}");
1169    }
1170
1171    #[test]
1172    fn a_context_share_outside_the_window_is_refused() {
1173        let err = set_in_text("", "context.compact_at", &toml::Value::Float(1.5)).unwrap_err();
1174        assert!(err.contains("context.compact_at"), "{err}");
1175        assert!(err.contains("nothing was saved"), "{err}");
1176        let err = set_in_text("", "context.handoff_chars", &toml::Value::Integer(50)).unwrap_err();
1177        assert!(err.contains("context.handoff_chars"), "{err}");
1178    }
1179
1180    #[test]
1181    fn a_key_the_config_does_not_have_yet_is_inserted_under_its_section() {
1182        let text = "[provider]\nbase_url = \"http://x/v1\"\n";
1183        let edited = set_in_text(
1184            text,
1185            "provider.api_key_env",
1186            &toml::Value::String("MY_KEY".into()),
1187        )
1188        .unwrap();
1189        assert!(edited.contains("api_key_env = \"MY_KEY\""), "{edited}");
1190        let cfg = super::super::parse_text(&edited).unwrap();
1191        assert_eq!(cfg.provider.api_key_env.as_deref(), Some("MY_KEY"));
1192    }
1193
1194    #[test]
1195    fn unsetting_a_key_comments_it_out_and_the_default_comes_back() {
1196        let text = "[web]\nport = 9000\n";
1197        let edited = unset_in_text(text, "web.port").unwrap();
1198        assert!(
1199            edited.contains("# port = 9000"),
1200            "the line is kept as documentation: {edited}"
1201        );
1202        let cfg = super::super::parse_text(&edited).unwrap();
1203        assert_eq!(cfg.web.port, Config::default().web.port);
1204    }
1205
1206    /// `#276`: on a fresh install `config keys` reports `provider.reasoning_effort` as `medium`
1207    /// both as the value and as the default — the file says it, and the resolver would supply the
1208    /// same answer if the line were deleted — while `ProviderConfig::default()` still leaves the
1209    /// field off so an undeclared backend is handed nothing.
1210    #[test]
1211    fn the_reasoning_key_reports_the_shipped_default_as_value_and_default() {
1212        let fresh = super::super::parse_text(&super::super::starter_config().unwrap())
1213            .expect("the starter");
1214        let row = fresh
1215            .setting("provider.reasoning_effort")
1216            .expect("the key is in the catalogue");
1217        assert_eq!(
1218            row.rendered(),
1219            format!("\"{}\"", crate::reasoning::SHIPPED_DEFAULT),
1220            "a fresh install has the level written down"
1221        );
1222        assert!(
1223            row.is_default(),
1224            "and the value is the default, so `config keys` marks it (default)"
1225        );
1226
1227        // A file that predates the change: no line, and the default is still the answer.
1228        let older = Config::default();
1229        let row = older
1230            .setting("provider.reasoning_effort")
1231            .expect("the key is in the catalogue");
1232        assert_eq!(
1233            row.default,
1234            Some(toml::Value::String(
1235                crate::reasoning::SHIPPED_DEFAULT.into()
1236            )),
1237            "the resolver's answer is reportable even with no line in the file"
1238        );
1239        assert_eq!(row.value, None, "and the file genuinely sets nothing");
1240        assert_eq!(
1241            older.provider.reasoning_effort, None,
1242            "the config struct still sends nothing to a backend that declares no default"
1243        );
1244    }
1245
1246    /// `#278`: the sentinel is a value of a key that already exists, so the catalogue takes it
1247    /// without knowing the word — which is the whole reason it is spelled there and not as a
1248    /// second `reasoning = "off"` key with a precedence rule of its own.
1249    #[test]
1250    fn the_reasoning_key_takes_the_omit_sentinel_as_a_value() {
1251        let cfg = super::super::parse_text(
1252            "[provider]\nbase_url = \"http://h/v1\"\nmodel = \"m\"\nreasoning_effort = \"omit\"\n",
1253        )
1254        .expect("the sentinel loads");
1255        assert_eq!(cfg.provider.reasoning_effort.as_deref(), Some("omit"));
1256        let row = cfg
1257            .setting("provider.reasoning_effort")
1258            .expect("the key is in the catalogue");
1259        assert_eq!(row.rendered(), "\"omit\"");
1260        assert!(
1261            !row.is_default(),
1262            "an operator's choice, not the shipped default"
1263        );
1264    }
1265
1266    #[test]
1267    fn a_bare_word_is_a_string_and_toml_literals_keep_their_type() {
1268        assert_eq!(
1269            parse_value("gemma-4-12b"),
1270            toml::Value::String("gemma-4-12b".into())
1271        );
1272        assert_eq!(parse_value("3"), toml::Value::Integer(3));
1273        assert_eq!(parse_value("true"), toml::Value::Boolean(true));
1274        assert_eq!(parse_value("0.5"), toml::Value::Float(0.5));
1275        assert_eq!(
1276            parse_value(r#"["a", "b"]"#),
1277            toml::Value::Array(vec![
1278                toml::Value::String("a".into()),
1279                toml::Value::String("b".into())
1280            ])
1281        );
1282        assert_eq!(parse_value(""), toml::Value::String(String::new()));
1283    }
1284
1285    /// `#424`: a three-value enumeration offers its values, like every other one.
1286    #[test]
1287    fn vision_mode_offers_its_three_words() {
1288        assert_eq!(choices("vision.mode"), &["native", "text", "auto"]);
1289        // The catalogue and the choices agree: a value the form cannot offer is a value nobody
1290        // can pick, and a choice the config refuses is a form that writes a broken file.
1291        for word in choices("vision.mode") {
1292            assert!(
1293                Config::default().setting("vision.mode").is_some(),
1294                "the key exists"
1295            );
1296            assert!(
1297                crate::config::Config::from_toml_str(&format!("[vision]\nmode = \"{word}\"\n"))
1298                    .is_ok(),
1299                "{word} is a value the config accepts"
1300            );
1301        }
1302    }
1303
1304    /// `#385`: a key that names a route is checked by the command that writes it. It used to be
1305    /// written, and the *next* load failed — with the valid routes in the error, which is a fine
1306    /// place to read them but not after the file has already been saved.
1307    #[test]
1308    fn a_route_typo_is_refused_by_the_command_that_writes_it() {
1309        let err =
1310            set_in_text("", "vision.route", &toml::Value::String("sigth".into())).unwrap_err();
1311        assert!(
1312            err.contains("names `sigth`") && err.contains("Routes that exist"),
1313            "{err}"
1314        );
1315        // A route that exists is written.
1316        assert!(set_in_text("", "vision.route", &toml::Value::String("default".into())).is_ok());
1317        // And a key that names no route is not held hostage by an unrelated broken one.
1318        let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
1319        assert!(edited.contains("max_iterations = 40"));
1320    }
1321
1322    /// `#403`: the gateway reads its intervals once, at startup, so a change to one is not "next
1323    /// run" — the separate process has to come up again.
1324    #[test]
1325    fn a_gateway_key_says_restart_instead_of_next_run() {
1326        let schema = Config::default();
1327        for path in [
1328            "gateway.check_interval_hours",
1329            "gateway.api_session_ttl_hours",
1330            "web.port",
1331        ] {
1332            let s = schema
1333                .setting(path)
1334                .unwrap_or_else(|| panic!("{path} exists"));
1335            assert_eq!(
1336                s.applies,
1337                Applies::RestartProcess,
1338                "{path} is read once by a process"
1339            );
1340        }
1341        let s = schema.setting("agent.max_iterations").expect("a setting");
1342        assert_eq!(s.applies, Applies::NextRun, "the agent is rebuilt per run");
1343        assert_eq!(
1344            Applies::RestartProcess.as_str(),
1345            "restart the background process"
1346        );
1347    }
1348}