use super::{is_secret_key, Config};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Applies {
NextRun,
RestartProcess,
}
fn applies_to(section: &str) -> Applies {
match section {
"web" | "gateway" => Applies::RestartProcess,
_ => Applies::NextRun,
}
}
impl Applies {
pub fn as_str(&self) -> &'static str {
match self {
Applies::NextRun => "next run",
Applies::RestartProcess => "restart the background process",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Str,
Integer,
Float,
Bool,
List,
Datetime,
}
impl Kind {
fn of(value: &toml::Value) -> Kind {
match value {
toml::Value::String(_) => Kind::Str,
toml::Value::Integer(_) => Kind::Integer,
toml::Value::Float(_) => Kind::Float,
toml::Value::Boolean(_) => Kind::Bool,
toml::Value::Array(_) => Kind::List,
toml::Value::Datetime(_) => Kind::Datetime,
toml::Value::Table(_) => Kind::List,
}
}
}
impl Kind {
pub fn as_str(self) -> &'static str {
match self {
Kind::Str => "str",
Kind::Integer => "integer",
Kind::Float => "float",
Kind::Bool => "bool",
Kind::List => "list",
Kind::Datetime => "datetime",
}
}
}
impl fmt::Display for Kind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Kind::Str => "a string",
Kind::Integer => "an integer",
Kind::Float => "a number",
Kind::Bool => "true or false",
Kind::List => "a list",
Kind::Datetime => "a date",
})
}
}
fn is_empty_string(value: &toml::Value) -> bool {
matches!(value, toml::Value::String(s) if s.is_empty())
}
#[derive(Debug, Clone, PartialEq)]
pub struct Setting {
pub section: String,
pub key: String,
pub default: Option<toml::Value>,
pub value: Option<toml::Value>,
pub kind: Kind,
pub secret: bool,
pub applies: Applies,
pub about: &'static str,
pub choices: &'static [&'static str],
}
impl Setting {
pub fn path(&self) -> String {
format!("{}.{}", self.section, self.key)
}
pub fn is_default(&self) -> bool {
self.value == self.default
}
pub fn rendered(&self) -> String {
if self.secret {
return "«redacted»".to_string();
}
match &self.value {
Some(value) => render(value),
None => "(not set)".to_string(),
}
}
pub fn rendered_default(&self) -> Option<String> {
if self.secret {
return None;
}
self.default.as_ref().map(render)
}
}
impl fmt::Display for Setting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} = {}", self.path(), self.rendered())?;
if self.is_default() {
write!(f, " (default)")?;
}
if self.applies == Applies::RestartProcess {
write!(f, " [{}]", self.applies.as_str())?;
}
Ok(())
}
}
pub(crate) const ABSENT_BY_DEFAULT: &[(&str, &str, Kind)] = &[
("flares", "total_tokens", Kind::Integer),
("provider", "api_key", Kind::Str),
("provider", "api_key_env", Kind::Str),
("provider", "aux", Kind::Str),
("provider", "delegate", Kind::Str),
("provider", "fallback", Kind::List),
("provider", "temperature", Kind::Float),
("provider", "max_tokens", Kind::Integer),
("provider", "profile", Kind::Str),
("provider", "top_p", Kind::Float),
("provider", "seed", Kind::Integer),
("provider", "stop", Kind::List),
("provider", "reasoning_effort", Kind::Str),
("provider", "parallel_tool_calls", Kind::Bool),
("provider", "tool_choice", Kind::Str),
("provider", "vision", Kind::Bool),
("agent", "output_schema", Kind::Str),
("tools", "workspace_root", Kind::Str),
("sessions", "dir", Kind::Str),
("attachments", "dir", Kind::Str),
("plugins", "dir", Kind::Str),
("plugins", "mcp_timeout_secs", Kind::Integer),
("web", "auth_token", Kind::Str),
("web", "default_profile", Kind::Str),
("cli", "color", Kind::Bool),
("cli", "markdown", Kind::Bool),
("update", "remote", Kind::Str),
("update", "releases", Kind::Str),
];
#[cfg(test)]
const NOT_SETTINGS: &[&str] = &[
"provider.route",
"provider.extra_body",
"hooks.settings",
"dotenv",
"profile",
"route_pin",
"no_mcp",
];
fn absent_default(section: &str, key: &str) -> Option<toml::Value> {
match (section, key) {
("provider", "reasoning_effort") => Some(toml::Value::String(
crate::reasoning::SHIPPED_DEFAULT.into(),
)),
_ => None,
}
}
fn render(value: &toml::Value) -> String {
match value {
toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
other => other.to_string(),
}
}
impl Config {
pub fn settings(&self) -> Vec<Setting> {
let Ok(defaults) = toml::Value::try_from(Config::default()) else {
return Vec::new();
};
let Ok(current) = toml::Value::try_from(self) else {
return Vec::new();
};
let mut out = Vec::new();
for (section, table) in defaults.as_table().into_iter().flatten() {
let loaded = current.get(section).and_then(toml::Value::as_table);
for (key, default) in table.as_table().into_iter().flatten() {
if matches!(default, toml::Value::Table(_)) {
continue;
}
if default
.as_array()
.is_some_and(|items| items.iter().any(toml::Value::is_table))
{
continue;
}
let value = loaded.and_then(|t| t.get(key)).cloned();
out.push(Setting {
section: section.clone(),
key: key.clone(),
kind: Kind::of(default),
default: Some(default.clone()),
value,
secret: is_secret_key(key),
applies: applies_to(section),
about: "",
choices: &[],
});
}
}
for (section, key, kind) in ABSENT_BY_DEFAULT {
let value = current
.get(section)
.and_then(toml::Value::as_table)
.and_then(|t| t.get(*key))
.cloned();
out.push(Setting {
section: (*section).to_string(),
key: (*key).to_string(),
kind: *kind,
default: absent_default(section, key),
value,
secret: is_secret_key(key),
applies: applies_to(section),
about: "",
choices: &[],
});
}
out.sort_by_key(Setting::path);
out.dedup_by(|a, b| a.path() == b.path());
for setting in &mut out {
let path = setting.path();
setting.about = about(&path);
setting.choices = choices(&path);
if let Some(kind) = word_default(&path) {
setting.kind = kind;
}
}
out
}
pub fn setting(&self, path: &str) -> Option<Setting> {
self.settings()
.into_iter()
.find(|s| s.path() == path.trim())
}
}
pub fn parse_value(raw: &str) -> toml::Value {
let raw = raw.trim();
if let Ok(value) = format!("v = {raw}").parse::<toml::Value>() {
if let Some(inner) = value.get("v") {
return inner.clone();
}
}
toml::Value::String(raw.to_string())
}
pub fn set_in_text(
text: &str,
path: &str,
value: &toml::Value,
) -> std::result::Result<String, String> {
let schema = Config::default();
let Some(setting) = schema.setting(path) else {
return Err(unknown_setting(&schema, path));
};
let typed = Kind::of(value);
if typed != setting.kind && !(setting.kind == Kind::Integer && is_unlimited(value)) {
return Err(format!(
"`{}` holds {} — {} is {}",
setting.path(),
setting.kind,
render(value),
typed
));
}
let edited = super::toml_set_value(text, &setting.section, &setting.key, &render(value));
let checked = super::parse_text(&edited).map_err(|e| {
format!(
"that would not load, so nothing was saved: {}",
one_line(&e.to_string())
)
})?;
if names_a_route(&setting) {
checked.validate_routes().map_err(|e| {
format!(
"that would not load, so nothing was saved: {}",
one_line(&e.to_string())
)
})?;
}
match checked.setting(&setting.path()) {
Some(after) if after.value.as_ref() == Some(value) => Ok(edited),
Some(after) if is_empty_string(value) && after.value.is_none() => Ok(edited),
Some(after) => Err(format!(
"the file would read `{}` back as {}, not {}; nothing was saved",
setting.path(),
after.rendered(),
render(value)
)),
None => Err(format!(
"`{}` disappeared from the file when it was edited; nothing was saved",
setting.path()
)),
}
}
pub fn set_list_in_text(
text: &str,
path: &str,
items: &[String],
) -> std::result::Result<String, String> {
let value = toml::Value::Array(items.iter().cloned().map(toml::Value::String).collect());
set_in_text(text, path, &value)
}
pub fn about(path: &str) -> &'static str {
const ABOUT: &[(&str, &str)] = &[
("agent.context_file_max_chars", "Truncate one context file past this many characters, keeping its head and tail; 0 = no per-file cap"),
("agent.context_files_budget_chars", "Ceiling across every context file; whole files are dropped past it, broadest first"),
("agent.max_consecutive_malformed_tool_calls", "Stop the run after this many consecutive tool calls that could not be used"),
("agent.max_iterations", "How many model-and-tool round trips one turn may take"),
("agent.output_schema", "A JSON Schema every reply must satisfy, as a path or inline JSON"),
("agent.system_prompt", "The standing instructions every run starts with, added to the built-in prompt rather than replacing it"),
("agent.trace_content", "Include prompts, arguments and results in trace spans"),
(
"agent.prompt_blocks",
"Standing prompt blocks after system_prompt: `auto` (per model family), a list of names, or `off`",
),
("cli.approval", "What an `ask` policy does: `ask` prompts, `auto` never does"),
("cli.clear_on_exit", "What an interactive exit does to the screen: `screen`, `all` or `off`"),
("cli.color", "Colour on a terminal; unset means decide from the stream, and from `NO_COLOR`"),
("cli.history_size", "How many commands the REPL remembers for arrow-up"),
("cli.markdown", "Markdown in replies; unset means on when colour is on"),
("context.compact_at", "Share of the model's window at which a request is compacted, e.g. 0.85; 0 turns the threshold off"),
("context.handoff_chars", "Hard cap, in characters, on the compiled handoff that stands in for the dropped middle"),
("context.judge", "Ask one model one bounded question about why the dropped turns went the way they did"),
("context.judge_timeout_secs", "How long that one call may take before the deterministic handoff ships without it"),
("context.protect_last_n", "Turns kept verbatim at the tail; 0 is read as 1"),
("context.window_tokens", "The window to assume when the endpoint advertises none; 0 assumes nothing"),
("gateway.api_session_ttl_hours", "How long a session made by `POST /v1/chat/completions` is kept"),
("gateway.check_interval_hours", "How often the gateway runs the update check and logs what it found"),
("hooks.order", "The order hooks run in, by name; a hook not named runs after the ones that are"),
("plugins.dir", "Root of the shared plugin directory (default `<config_dir>/plugins`)"),
("plugins.enabled", "The plugins to load, by directory name; one that is not listed loads only as a wire profile"),
("plugins.mcp_timeout_secs", "Ceiling on one MCP call, for `[[mcp]]` entries that state none of their own"),
("provider.api_key", "A key written into the file; prefer `api_key_env` or `ECLIPSE_API_KEY`, which keep it out of it"),
("provider.api_key_env", "Name of an environment variable holding the key"),
("provider.aux", "The route that does the agent's own housekeeping — the summary of trimmed turns — and never the user's work"),
("provider.base_url", "Base URL of an OpenAI-compatible API, up to the `/v1`"),
("provider.context_budget_tokens", "Soft cap on the conversation sent to the model, in estimated tokens (characters / 4, a rough heuristic)"),
("provider.delegate", "The route a `delegate` call's child agent runs on unless the call names one"),
("provider.fallback", "The routes tried in order when a request fails for a transient reason"),
("provider.max_retries", "Extra attempts after a request fails with 408, 429 or 5xx, or could not be sent (0 = never)"),
("provider.max_tokens", "Cap on the reply, in tokens"),
("provider.model", "The model every request asks for"),
("provider.parallel_tool_calls", "Ask for several tool calls in one reply"),
("provider.profile", "Wire profile: `openai` (default), `llamacpp`, or one a plugin declares"),
("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"),
("provider.retry_after_send", "Also retry a request that failed after it went out — a dropped connection, or nothing for `timeout_secs`"),
("provider.retry_base_delay_ms", "How long the first retry waits; each further attempt doubles it"),
("provider.seed", "Ask for a reproducible sample, where the backend supports it"),
("provider.stop", "Up to four sequences the reply stops at"),
("provider.stream", "Ask for a token-by-token (SSE) reply"),
("provider.temperature", "Sampling temperature, unset leaves whatever the server defaults to"),
("provider.timeout_secs", "Ceiling on one request, from connect to last byte"),
("provider.tool_choice", "`auto`, `none`, `required`, or one tool's name"),
("provider.top_p", "Nucleus sampling: draw from the smallest set of tokens holding this much probability"),
("provider.vision", "Declare whether this route's model can see images (overrides the wire profile)"),
(
"attachments.dir",
"Where attached pictures are stored; defaults to `<state_dir>/attachments`"
),
(
"attachments.max_total_bytes",
"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)"
),
("sessions.auto_prune", "Apply the retention limits when the CLI starts, before the first prompt"),
("sessions.autotitle", "Name sessions: a name derived from the opening message, plus at most one small-model call"),
("sessions.dir", "Where sessions are stored; defaults to `<state_dir>/sessions`"),
("sessions.lock_wait_secs", "How long a run waits for another process to release the same session; 0 fails on the first refusal"),
("sessions.retention_keep_count", "Default for `sessions prune --keep-count`: keep only the newest N; 0 = disabled"),
("sessions.retention_keep_days", "Default for `sessions prune --keep-days`: delete sessions idle longer than this; 0 = disabled"),
("skills.index_budget_chars", "Ceiling for the skill index in the system prompt, in characters"),
("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`)"),
("vision.route", "The route that describes a picture, for `text` and for `auto`'s fallback; empty means there is none"),
("vision.allow_cloud", "Let a picture be described by a route that is not on this machine"),
("flares.count", "Default number of jobs for `flares run -n`; a local run starts from it (default 3)"),
("flares.max_concurrent", "The most flares one run may have in flight, whatever the routes allow"),
("flares.max_iterations", "Per flare, when the job does not say: what `delegate` gives a child"),
("flares.total_iterations", "The run's own budget: what stops one wandering flare eating the others' turns"),
("flares.total_tokens", "Optional spend cap for the whole run, in tokens; unset = the budgets are the ceiling"),
("tools.concurrency", "How many of one turn's tool calls run at the same time; 1 runs them in order"),
("tools.deferred", "Tools that stay callable but are not described in the request, so they cost no tokens until needed"),
("tools.delegate", "The `delegate` tool's policy: hand a job to a child agent"),
("tools.disabled", "Tools removed entirely, whatever their policy says"),
("tools.execute_code", "The `execute_code` tool: a short program run from a temporary file, with a bridge to the tools"),
("tools.fetch", "The `fetch` tool: one URL in, its text out"),
("tools.fetch_html", "`text` renders HTML responses as plain text; `raw` returns the source"),
("tools.fetch_timeout_secs", "Ceiling on one `fetch`"),
("tools.max_output_bytes", "Tool output is cut to this many bytes before the model sees it"),
("tools.memory", "The `memory` tool's policy: write a durable fact to MEMORY.md"),
("tools.patch", "The `patch` tool's policy: a targeted edit of a file that already exists"),
("tools.read_file", "The `read_file` tool"),
("tools.rewrite_guard_bytes", "Above this size, `write_file` needs `force` to clobber an existing file"),
("tools.script", "The `script` tool's policy: run a file from the scripts directory"),
("tools.search_files", "The `search_files` tool's policy: a read-only walk of the workspace"),
("tools.shell", "The `shell` tool: run a command on this machine"),
("tools.shell_allowlist", "If set, `shell` may only run these program names, without a shell"),
("tools.shell_ask", "Which `shell` commands ask first: `dangerous` asks only for the un-undoable ones"),
("tools.shell_isolate", "What a `shell` command can reach: `off`, `process` (private PID namespace) or `fs` (bubblewrap)"),
("tools.shell_isolate_hide", "Paths replaced by an empty directory in `fs` mode, so nothing in them can be read"),
("tools.shell_isolate_network", "Whether `fs` isolation keeps the network"),
("tools.shell_isolate_writable", "Extra paths bound read-write in `fs` mode, beyond the workspace and the scripts directory"),
("tools.shell_timeout_secs", "Ceiling on one `shell` command"),
("tools.tool_call", "Call a tool a search found, without it being described up front"),
("tools.tool_describe", "Ask for a deferred tool's full schema"),
("tools.tool_search", "The `tool_search` tool's policy: look for a deferred tool"),
("tools.workspace_root", "The file tools are confined to this directory"),
("tools.write_file", "The `write_file` tool"),
("update.check", "How often the update check asks: `daily`, `weekly` or `off`"),
("update.releases", "Where the newest release is asked for, instead of the public GitHub repository"),
("update.remote", "Where the latest commit is asked for, instead of the public GitHub repository"),
("update.track", "Which branch a source install follows: `release` is main, `develop` is the branch work lands on"),
("user.file", "The user model file, relative to the config directory unless absolute"),
("user.memory_budget_chars", "Ceiling for `MEMORY.md` in characters"),
("user.memory_file", "The agent's memory file, resolved the same way"),
("web.auth_token", "The dashboard's login secret, generated by `config init`"),
("web.default_profile", "The profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE` names one"),
("web.host", "The address the dashboard binds; loopback only"),
("web.port", "The port the dashboard listens on"),
("web.session_ttl_hours", "How long a browser stays signed in"),
];
ABOUT
.iter()
.find(|(key, _)| *key == path)
.map(|(_, about)| *about)
.unwrap_or("")
}
fn word_default(path: &str) -> Option<Kind> {
match path {
"agent.max_iterations" => Some(Kind::Integer),
_ => None,
}
}
const UNLIMITED: &[&str] = &[
"unlimited",
"none",
"null",
"inf",
"infinite",
"infinity",
"∞",
];
fn is_unlimited(value: &toml::Value) -> bool {
value
.as_str()
.is_some_and(|w| UNLIMITED.contains(&w.trim().to_ascii_lowercase().as_str()))
}
pub fn choices(path: &str) -> &'static [&'static str] {
const ANY: &[&str] = &["deny", "ask", "allow"];
match path {
p if p.starts_with("tools.")
&& matches!(
p.split_once('.').map(|(_, k)| k),
Some(
"delegate"
| "execute_code"
| "fetch"
| "memory"
| "patch"
| "read_file"
| "script"
| "search_files"
| "shell"
| "tool_call"
| "tool_describe"
| "tool_search"
| "write_file"
)
) =>
{
ANY
}
"vision.mode" => &["native", "text", "auto"],
"cli.approval" => &["ask", "auto"],
"cli.clear_on_exit" => &["screen", "all", "off"],
"tools.fetch_html" => &["text", "raw"],
"tools.shell_ask" => &["dangerous", "always"],
"tools.shell_isolate" => &["off", "process", "fs"],
"update.check" => &["daily", "weekly", "off"],
"update.track" => &["release", "develop"],
_ => &[],
}
}
fn names_a_route(setting: &Setting) -> bool {
names_a_route_path(&setting.path())
}
fn names_a_route_path(path: &str) -> bool {
path.starts_with("provider.route")
|| matches!(path, "provider.aux" | "provider.delegate" | "vision.route")
}
pub fn unset_in_text(text: &str, path: &str) -> std::result::Result<String, String> {
let schema = Config::default();
let Some(setting) = schema.setting(path) else {
return Err(unknown_setting(&schema, path));
};
let edited = super::toml_comment_out(text, &setting.section, &setting.key);
let checked = super::parse_text(&edited).map_err(|e| {
format!(
"that would not load, so nothing was saved: {}",
one_line(&e.to_string())
)
})?;
match checked.setting(&setting.path()) {
Some(after) if after.value == setting.value => Ok(edited),
Some(after) => Err(format!(
"the file would still read `{}` as {}; nothing was saved",
setting.path(),
after.rendered()
)),
None => Err(format!(
"`{}` disappeared from the file when it was edited; nothing was saved",
setting.path()
)),
}
}
fn unknown_setting(schema: &Config, path: &str) -> String {
let path = path.trim();
let (section, key) = path.split_once('.').unwrap_or(("", path));
let settings = schema.settings();
if let Some(elsewhere) = settings.iter().find(|s| s.key == key) {
return format!(
"`{path}` is not a setting: `{key}` is read under [{}]. Write `{}`.",
elsewhere.section,
elsewhere.path()
);
}
let mut near: Vec<String> = settings
.iter()
.filter(|s| s.key.contains(key) || key.contains(&s.key) || s.section == section)
.map(Setting::path)
.take(8)
.collect();
if near.is_empty() {
near = settings.iter().take(8).map(Setting::path).collect();
}
format!(
"`{path}` is not a setting in this build. `eclipse config keys` lists all of them; \
close to what you wrote: {}",
near.join(", ")
)
}
pub(super) fn one_line(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
fn paths() -> Vec<String> {
Config::default()
.settings()
.into_iter()
.map(|s| s.path())
.collect()
}
#[test]
fn the_catalogue_is_derived_from_the_config_itself() {
let paths = paths();
assert!(paths.contains(&"provider.model".to_string()), "{paths:?}");
assert!(paths.contains(&"tools.shell".to_string()), "{paths:?}");
assert!(paths.contains(&"web.port".to_string()), "{paths:?}");
assert!(
!paths.iter().any(|k| k.starts_with("provider.route")),
"a route is a table to edit, not a value: {paths:?}"
);
assert!(
paths.iter().all(|k| k.matches('.').count() == 1),
"{paths:?}"
);
let mut sorted = paths.clone();
sorted.sort();
assert_eq!(paths, sorted);
}
#[test]
fn every_field_a_default_config_omits_is_still_settable() {
let mut c = Config::default();
c.provider.api_key = Some("probe".into());
c.provider.api_key_env = Some("PROBE_KEY".into());
c.provider.aux = Some("mmnuc/small".into());
c.provider.delegate = Some("mmnuc/small".into());
c.provider.fallback = Some(vec!["local".into()]);
c.provider.temperature = Some(0.5);
c.provider.max_tokens = Some(1024);
c.provider.profile = Some("openai".into());
c.provider.top_p = Some(0.9);
c.provider.seed = Some(7);
c.provider.stop = Some(vec!["</s>".into()]);
c.provider.reasoning_effort = Some("low".into());
c.provider.parallel_tool_calls = Some(true);
c.provider.vision = Some(true);
c.provider.tool_choice = Some(crate::hooks::ToolChoice::Auto);
c.provider.extra_body = Some(serde_json::json!({"chat_template_kwargs": {"x": 1}}));
c.agent.output_schema = Some("{}".into());
c.tools.workspace_root = Some(std::path::PathBuf::from("/w"));
c.sessions.dir = Some(std::path::PathBuf::from("/s"));
c.plugins.dir = Some(std::path::PathBuf::from("/p"));
c.plugins.mcp_timeout_secs = Some(30);
c.web.auth_token = Some("probe-token".into());
c.web.default_profile = Some("work".into());
c.cli.color = Some(false);
c.cli.markdown = Some(true);
c.update.remote = Some("https://mirror.internal/latest".into());
c.update.releases = Some("https://mirror.internal/releases".into());
let filled = toml::Value::try_from(&c).expect("a filled config serialises");
let schema = Config::default();
let mut checked = 0;
for (section, table) in filled.as_table().expect("a table").iter() {
let Some(table) = table.as_table() else {
continue;
};
for key in table.keys() {
let path = format!("{section}.{key}");
if NOT_SETTINGS.contains(&path.as_str()) {
continue;
}
assert!(
schema.setting(&path).is_some(),
"`{path}` is a real field but not a setting: `config set {path} …` would refuse it"
);
checked += 1;
}
}
assert!(
checked > 60,
"the walk has to see the whole catalogue, not a corner: {checked}"
);
}
#[test]
fn a_turn_budget_takes_a_number_and_the_word_for_no_cap() {
let schema = Config::default();
let setting = schema.setting("agent.max_iterations").expect("a setting");
assert_eq!(setting.kind, Kind::Integer, "a number, not a word");
let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
let cfg = super::super::parse_text(&edited).unwrap();
assert_eq!(cfg.agent.max_iterations, 40);
let edited = set_in_text(
"",
"agent.max_iterations",
&toml::Value::String("unlimited".into()),
)
.unwrap();
let cfg = super::super::parse_text(&edited).unwrap();
assert_eq!(cfg.agent.max_iterations, usize::MAX);
let refused = set_in_text(
"",
"agent.max_iterations",
&toml::Value::String("lots".into()),
)
.unwrap_err();
assert!(refused.contains("max_iterations"), "{refused}");
}
#[test]
fn every_key_is_explained_and_the_closed_sets_name_their_values() {
let settings = Config::default().settings();
assert!(
settings.len() > 80,
"the whole catalogue: {}",
settings.len()
);
for s in &settings {
assert!(
!s.about.trim().is_empty(),
"{} has no description — add it to `about`",
s.path()
);
assert!(s.about.len() < 160, "{}: too long for a row", s.path());
assert!(
!s.about.ends_with('.'),
"{}: no trailing full stop",
s.path()
);
}
assert_eq!(choices("cli.approval"), &["ask", "auto"]);
assert_eq!(choices("tools.read_file"), &["deny", "ask", "allow"]);
assert!(choices("provider.model").is_empty());
}
#[test]
fn every_key_that_is_absent_by_default_is_real_and_settable() {
for (section, key, kind) in ABSENT_BY_DEFAULT {
let path = format!("{section}.{key}");
let sample = match kind {
Kind::Str if names_a_route_path(&path) => toml::Value::String("default".into()),
Kind::Str => toml::Value::String("probe".into()),
Kind::Integer => toml::Value::Integer(7),
Kind::Float => toml::Value::Float(0.5),
Kind::Bool => toml::Value::Boolean(true),
Kind::List => toml::Value::Array(vec![toml::Value::String("probe".into())]),
Kind::Datetime => continue,
};
let edited = set_in_text("", &path, &sample).unwrap_or_else(|e| panic!("{path}: {e}"));
let cfg = super::super::parse_text(&edited).unwrap_or_else(|e| panic!("{path}: {e}"));
assert_eq!(
cfg.setting(&path).and_then(|s| s.value),
Some(sample),
"{path} did not read back — is it a real field?"
);
}
}
#[test]
fn an_absent_key_reports_itself_as_unset_and_is_not_the_default() {
let schema = Config::default();
let key = schema
.setting("provider.api_key")
.expect("api_key is a setting");
assert!(key.secret, "a key by that name is a secret");
assert_eq!(
key.rendered(),
"«redacted»",
"never printed, even when unset"
);
assert_eq!(key.value, None, "absent is not the empty string");
let plain = schema
.setting("provider.model")
.expect("model is a setting");
assert!(!plain.secret);
}
#[test]
fn a_count_is_not_a_credential() {
let schema = Config::default();
let window = schema
.setting("context.window_tokens")
.expect("window_tokens is a setting");
assert!(!window.secret, "a token count is not a token");
assert_eq!(window.rendered(), "0", "and its value is readable");
assert!(schema.setting("provider.api_key").unwrap().secret);
assert!(
!schema.setting("provider.api_key_env").unwrap().secret,
"the name of a variable is not the variable"
);
}
#[test]
fn setting_a_key_edits_one_line_and_everything_else_survives() {
let text = "# my provider\n[provider]\n# the name the endpoint serves\nmodel = \"old\"\n\n[web]\nport = 8787\n";
let edited =
set_in_text(text, "provider.model", &toml::Value::String("new".into())).unwrap();
assert!(edited.contains("model = \"new\""), "{edited}");
assert!(
edited.contains("# my provider") && edited.contains("# the name"),
"{edited}"
);
assert!(edited.contains("port = 8787"), "{edited}");
assert!(!edited.contains("\"old\""), "{edited}");
}
#[test]
fn a_typed_value_is_written_as_toml_and_read_back() {
let text = "[web]\nport = 8787\n";
let edited = set_in_text(text, "web.port", &toml::Value::Integer(9000)).unwrap();
assert!(edited.contains("port = 9000"), "{edited}");
let cfg = super::super::parse_text(&edited).unwrap();
assert_eq!(cfg.web.port, 9000);
}
#[test]
fn a_value_of_the_wrong_shape_is_refused_with_the_shape_it_wants() {
let text = "[web]\nport = 8787\n";
let err = set_in_text(text, "web.port", &toml::Value::String("nine".into())).unwrap_err();
assert!(err.contains("`web.port` holds an integer"), "{err}");
assert!(err.contains("\"nine\" is a string"), "{err}");
let err =
set_in_text(text, "web.session_ttl_hours", &toml::Value::Boolean(true)).unwrap_err();
assert!(err.contains("an integer"), "{err}");
}
#[test]
fn a_key_this_build_does_not_read_is_refused_and_the_right_table_is_named() {
let text = "[web]\n";
let err = set_in_text(text, "web.model", &toml::Value::String("m".into())).unwrap_err();
assert!(err.contains("`model` is read under [provider]"), "{err}");
assert!(err.contains("provider.model"), "{err}");
let err = set_in_text(text, "provider.modl", &toml::Value::String("m".into())).unwrap_err();
assert!(err.contains("is not a setting"), "{err}");
assert!(err.contains("config keys"), "where to look: {err}");
}
#[test]
fn a_key_the_config_does_not_have_yet_is_inserted_under_its_section() {
let text = "[provider]\nbase_url = \"http://x/v1\"\n";
let edited = set_in_text(
text,
"provider.api_key_env",
&toml::Value::String("MY_KEY".into()),
)
.unwrap();
assert!(edited.contains("api_key_env = \"MY_KEY\""), "{edited}");
let cfg = super::super::parse_text(&edited).unwrap();
assert_eq!(cfg.provider.api_key_env.as_deref(), Some("MY_KEY"));
}
#[test]
fn unsetting_a_key_comments_it_out_and_the_default_comes_back() {
let text = "[web]\nport = 9000\n";
let edited = unset_in_text(text, "web.port").unwrap();
assert!(
edited.contains("# port = 9000"),
"the line is kept as documentation: {edited}"
);
let cfg = super::super::parse_text(&edited).unwrap();
assert_eq!(cfg.web.port, Config::default().web.port);
}
#[test]
fn the_reasoning_key_reports_the_shipped_default_as_value_and_default() {
let fresh = super::super::parse_text(&super::super::starter_config().unwrap())
.expect("the starter");
let row = fresh
.setting("provider.reasoning_effort")
.expect("the key is in the catalogue");
assert_eq!(
row.rendered(),
format!("\"{}\"", crate::reasoning::SHIPPED_DEFAULT),
"a fresh install has the level written down"
);
assert!(
row.is_default(),
"and the value is the default, so `config keys` marks it (default)"
);
let older = Config::default();
let row = older
.setting("provider.reasoning_effort")
.expect("the key is in the catalogue");
assert_eq!(
row.default,
Some(toml::Value::String(
crate::reasoning::SHIPPED_DEFAULT.into()
)),
"the resolver's answer is reportable even with no line in the file"
);
assert_eq!(row.value, None, "and the file genuinely sets nothing");
assert_eq!(
older.provider.reasoning_effort, None,
"the config struct still sends nothing to a backend that declares no default"
);
}
#[test]
fn the_reasoning_key_takes_the_omit_sentinel_as_a_value() {
let cfg = super::super::parse_text(
"[provider]\nbase_url = \"http://h/v1\"\nmodel = \"m\"\nreasoning_effort = \"omit\"\n",
)
.expect("the sentinel loads");
assert_eq!(cfg.provider.reasoning_effort.as_deref(), Some("omit"));
let row = cfg
.setting("provider.reasoning_effort")
.expect("the key is in the catalogue");
assert_eq!(row.rendered(), "\"omit\"");
assert!(
!row.is_default(),
"an operator's choice, not the shipped default"
);
}
#[test]
fn a_bare_word_is_a_string_and_toml_literals_keep_their_type() {
assert_eq!(
parse_value("gemma-4-12b"),
toml::Value::String("gemma-4-12b".into())
);
assert_eq!(parse_value("3"), toml::Value::Integer(3));
assert_eq!(parse_value("true"), toml::Value::Boolean(true));
assert_eq!(parse_value("0.5"), toml::Value::Float(0.5));
assert_eq!(
parse_value(r#"["a", "b"]"#),
toml::Value::Array(vec![
toml::Value::String("a".into()),
toml::Value::String("b".into())
])
);
assert_eq!(parse_value(""), toml::Value::String(String::new()));
}
#[test]
fn vision_mode_offers_its_three_words() {
assert_eq!(choices("vision.mode"), &["native", "text", "auto"]);
for word in choices("vision.mode") {
assert!(
Config::default().setting("vision.mode").is_some(),
"the key exists"
);
assert!(
crate::config::Config::from_toml_str(&format!("[vision]\nmode = \"{word}\"\n"))
.is_ok(),
"{word} is a value the config accepts"
);
}
}
#[test]
fn a_route_typo_is_refused_by_the_command_that_writes_it() {
let err =
set_in_text("", "vision.route", &toml::Value::String("sigth".into())).unwrap_err();
assert!(
err.contains("names `sigth`") && err.contains("Routes that exist"),
"{err}"
);
assert!(set_in_text("", "vision.route", &toml::Value::String("default".into())).is_ok());
let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
assert!(edited.contains("max_iterations = 40"));
}
#[test]
fn a_gateway_key_says_restart_instead_of_next_run() {
let schema = Config::default();
for path in [
"gateway.check_interval_hours",
"gateway.api_session_ttl_hours",
"web.port",
] {
let s = schema
.setting(path)
.unwrap_or_else(|| panic!("{path} exists"));
assert_eq!(
s.applies,
Applies::RestartProcess,
"{path} is read once by a process"
);
}
let s = schema.setting("agent.max_iterations").expect("a setting");
assert_eq!(s.applies, Applies::NextRun, "the agent is rebuilt per run");
assert_eq!(
Applies::RestartProcess.as_str(),
"restart the background process"
);
}
}