Skip to main content

eclipse_core/
config.rs

1//! TOML configuration with XDG-style paths, `.env` files and environment overrides.
2//!
3//! Resolution order, later wins:
4//!
5//! ```text
6//! built-in defaults < config file < shared .env < profile .env < environment
7//! ```
8//!
9//! Secrets belong in `.env` (mode `0600`) rather than in `config.toml`, which is the file
10//! people paste into issues; `config.toml` can then refer to them as `${NAME}` (see
11//! [`crate::interpolate`]). There are deliberately no built-in endpoints or API keys.
12
13use crate::error::{Error, Result};
14use serde::{Deserialize, Serialize};
15use std::collections::BTreeMap;
16use std::fmt;
17use std::path::{Path, PathBuf};
18
19pub const APP_DIR: &str = "eclipse";
20
21/// The shape of `config.toml` this build writes, stamped into the file as `config_version`.
22///
23/// A file with no stamp was written before the stamp existed (`0`), which is what makes the
24/// migration in [`config::migrate`] able to run against every install that ever shipped rather
25/// than only the ones made after this line was added. Bump it when the *shape* changes — a key
26/// added, renamed or given a different shipped default — not for every release.
27pub const CONFIG_VERSION: u32 = 1;
28
29/// Environment lookup, injectable so tests never touch the process environment.
30pub type EnvFn<'a> = &'a dyn Fn(&str) -> Option<String>;
31
32pub fn process_env(key: &str) -> Option<String> {
33    std::env::var(key).ok().filter(|v| !v.is_empty())
34}
35
36pub(crate) fn home_dir(env: EnvFn) -> Option<PathBuf> {
37    env("HOME").map(PathBuf::from)
38}
39
40/// The one directory everything lives in: `$ECLIPSE_HOME`, or `~/.eclipse`.
41///
42/// Deliberately not XDG. The XDG split is right for a desktop application whose data belongs to
43/// the machine's other applications; an agent is one thing a person owns, moves between hosts,
44/// backs up and deletes, and "one directory you can `tar` up" is the property that matters more.
45/// It is also the shape `~/.hermes` already has, which is what most people using this will have
46/// seen first.
47///
48/// Everything below is derived from this and nothing else: `config.toml`, `.env` and `memory/`
49/// sit at the top, machine-written files go in `state/`, a profile gets its own subtree, and the
50/// checkout `eclipse upgrade` rebuilds from is recorded in `state/install.json` because it may
51/// live anywhere.
52pub fn home_root(env: EnvFn) -> Option<PathBuf> {
53    if let Some(p) = env("ECLIPSE_HOME") {
54        if !p.is_empty() {
55            return Some(expand_tilde(Path::new(&p), env));
56        }
57    }
58    home_dir(env).map(|h| h.join(".eclipse"))
59}
60
61/// Where `config.toml`, `.env` and the shared `plugins/`, `skills/` and `scripts/` live: the root
62/// itself. A `--config` elsewhere moves the file without moving the directory it is read from,
63/// which is what [`config_path`] is for.
64pub fn config_dir(env: EnvFn) -> Option<PathBuf> {
65    home_root(env)
66}
67
68/// Machine-written files: sessions, REPL history, locks, `install.json`, `update.json`. Inside the
69/// root so that a backup, a move or a delete is one operation, and named for what it is rather
70/// than for who wrote it.
71pub fn state_dir(env: EnvFn) -> Option<PathBuf> {
72    home_root(env).map(|r| r.join("state"))
73}
74
75/// Create the directories the layout names, so that `ls ~/.eclipse` answers "where does the
76/// agent's stuff go?" without reading a document. Idempotent, and it never touches a file.
77///
78/// Nothing is created that Eclipse does not use: `memory/` is where the context files go,
79/// `skills/` and `plugins/` are the user's own, `profiles/` holds named subtrees, `workspace/` is
80/// the default place to point `[tools] workspace_root` when you do not want the current
81/// directory, and `state/` is written from the first run.
82pub fn ensure_layout(root: &Path) -> std::io::Result<()> {
83    for dir in [
84        "",
85        "bin",
86        "memory",
87        "skills",
88        "plugins",
89        "profiles",
90        "workspace",
91        "state",
92    ] {
93        let p = if dir.is_empty() {
94            root.to_path_buf()
95        } else {
96            root.join(dir)
97        };
98        std::fs::create_dir_all(&p)?;
99    }
100    Ok(())
101}
102
103/// The starter `AGENT.md`, written on first install. The user is expected to edit it; the
104/// content is a shape and a set of instructions, not facts about the machine.
105pub const STARTER_AGENT_MD: &str = "# How to work here
106# This file is injected into the system prompt on every run, along with USER.md and MEMORY.md.
107# Edit the lines below to describe this project: conventions, commands, gotchas.
108
109You are a direct, practical assistant. Read before acting, say what you are doing,
110and keep a reply short unless it needs to be long. Use the workspace and tools to verify
111what you are about to do, rather than describing it.
112
113MEMORY.md is for facts about the user and their machines. A procedure — the steps, commands and
114pitfalls for a kind of task — belongs in a skill: `skill_manage` writes one, and only its name and
115description sit in the prompt until the task calls for it.
116";
117
118/// The starter `USER.md`: who the operator is. Edit it; it is the agent's standing picture of
119/// the user, injected on every run.
120pub const STARTER_USER_MD: &str = "# Who the operator is
121# This file is injected into the system prompt on every run. Describe the person who owns
122# this install — who they are, what they do, and the preferences you should follow.
123
124The operator is the person who owns this install. Edit this file with their name,
125what they do, and standing preferences. Keep it short: this is who they are,
126not a data dump.
127";
128
129/// Seed the three context files in the memory directory, creating any that are missing.
130///
131/// **A starter is written only where a file is absent, and its content is never revisited.** Two of
132/// these three hold the operator's own words — `AGENT.md` how to work in this project, `USER.md`
133/// who they are — and `MEMORY.md` is the agent's record. None of them can be regenerated from the
134/// config the way `config.toml` can be regenerated from the wizard, which is why there is no merge,
135/// no marker block inside them and no `--force` here: the only writer of a file that exists is
136/// whoever the operator asked to write it (an editor, the `memory` tool, the dashboard).
137///
138/// Starter text is versioned in this binary and may change freely between releases; the change
139/// reaches the next *install* — a fresh prefix, or a profile whose `memory/` has no such file —
140/// and never an existing one. So this is safe on every path that runs it: repeating it over a
141/// directory that has the files does nothing at all.
142///
143/// Returns the paths created, in the order AGENT, USER, MEMORY.
144pub fn seed_context_files(memory_dir: &Path) -> Result<Vec<PathBuf>> {
145    std::fs::create_dir_all(memory_dir).map_err(|e| Error::io(memory_dir, e))?;
146    let mut created = Vec::new();
147    for (name, body) in [
148        ("AGENT.md", STARTER_AGENT_MD),
149        ("USER.md", STARTER_USER_MD),
150        // MEMORY.md starts empty: it is the agent's running record, and the `memory` tool
151        // is what fills it. An empty file is valid and is not injected.
152        ("MEMORY.md", ""),
153    ] {
154        let path = memory_dir.join(name);
155        if path.exists() {
156            continue;
157        }
158        std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
159        created.push(path);
160    }
161    Ok(created)
162}
163
164mod check;
165pub mod migrate;
166mod settings;
167
168pub use check::{unknown_keys_in_file, UnknownKey};
169pub use migrate::{baseline_path, plan as migration_plan, Change, Plan};
170pub use settings::{
171    about, choices, parse_value, set_in_text, set_list_in_text, unset_in_text, Applies, Kind,
172    Setting,
173};
174
175/// `$ECLIPSE_CONFIG` or `<config_dir>/config.toml`.
176pub fn config_path(env: EnvFn) -> Option<PathBuf> {
177    if let Some(p) = env("ECLIPSE_CONFIG") {
178        return Some(PathBuf::from(p));
179    }
180    config_dir(env).map(|d| d.join("config.toml"))
181}
182
183/// Profile names become directory names, so they are held to the same alphabet as session
184/// ids: `[A-Za-z0-9_-]`, 1-64 characters.
185pub fn validate_profile_name(name: &str) -> Result<()> {
186    let ok = !name.is_empty()
187        && name.len() <= 64
188        && name
189            .chars()
190            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
191    if ok {
192        Ok(())
193    } else {
194        Err(Error::Config(format!("invalid profile name {name:?}")))
195    }
196}
197
198/// `<root>/profiles/<name>`: a profile's own config overlay, `memory/`, `skills/`, `plugins/` and
199/// `state/`.
200pub fn profile_dir(env: EnvFn, name: &str) -> Option<PathBuf> {
201    home_root(env).map(|d| d.join("profiles").join(name))
202}
203
204/// The file a config write lands in (`#571`).
205///
206/// An explicit `--config` is that file and nothing else. Under `--profile <name>` it is the
207/// profile's own overlay, because that is the file whose keys win for that profile: writing the
208/// shared base while an overlay pinned the same key left the effective value untouched, so
209/// `config set provider.model …` printed the overlay's old value and the profile kept serving it.
210/// `default` — and no profile at all — is the base file, because that profile *is* the base file.
211///
212/// One answer for both writers: `config set`/`config unset`/`mcp add` on the command line and the
213/// dashboard's settings and MCP panes. Two answers is how one of them came to write the wrong file.
214///
215/// The directory is not created here: a read asks this question too, and a read must not make
216/// one. A caller that writes makes the directory for its own profile first.
217/// `root` is where `profiles/` lives ([`home_root`]), `explicit` is a `--config` the person gave,
218/// `base` is the file a load reads first, and `profile` is the profile in force.
219pub fn write_target(
220    root: Option<&Path>,
221    explicit: Option<&Path>,
222    base: Option<&Path>,
223    profile: Option<&str>,
224) -> Option<PathBuf> {
225    if let Some(path) = explicit {
226        return Some(path.to_path_buf());
227    }
228    match profile {
229        None | Some("default") => base.map(Path::to_path_buf),
230        Some(name) => {
231            validate_profile_name(name).ok()?;
232            Some(root?.join("profiles").join(name).join("config.toml"))
233        }
234    }
235}
236
237/// State directory for a profile: the root's own `state/` for the default profile, otherwise
238/// `profiles/<name>/state` — beside that profile's config, not inside the root's state, so a
239/// profile is a subtree you can move or delete in one piece.
240pub fn state_dir_for(env: EnvFn, profile: Option<&str>) -> Option<PathBuf> {
241    match profile {
242        None | Some("default") => state_dir(env),
243        Some(name) => profile_dir(env, name).map(|d| d.join("state")),
244    }
245}
246
247fn expand_tilde(p: &Path, env: EnvFn) -> PathBuf {
248    if let Ok(rest) = p.strip_prefix("~") {
249        if let Some(h) = home_dir(env) {
250            return h.join(rest);
251        }
252    }
253    p.to_path_buf()
254}
255
256/// What happens when the model asks for a tool.
257/// How `fetch` returns an HTML response by default.
258#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(rename_all = "lowercase")]
260pub enum FetchHtml {
261    /// Convert to approximate plain text (see `eclipse_core::html`).
262    Text,
263    /// Return the HTML source unchanged.
264    Raw,
265}
266
267/// What a `shell` command can reach once it runs. The mechanics are in `eclipse_core::sandbox`.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "lowercase")]
270pub enum ShellIsolate {
271    /// A plain process: your files, your network, and anything it starts outlives the call.
272    Off,
273    /// A private PID namespace, through bubblewrap. The filesystem is unchanged; a daemon the
274    /// command leaves behind dies with the run.
275    Process,
276    /// A private PID namespace and a read-only filesystem, with the workspace writable. Costs a
277    /// build that writes outside the workspace (cargo into `~/.cargo`) a `shell_isolate_writable`
278    /// line.
279    Fs,
280}
281
282impl std::fmt::Display for ShellIsolate {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.write_str(match self {
285            Self::Off => "off",
286            Self::Process => "process",
287            Self::Fs => "fs",
288        })
289    }
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
293#[serde(rename_all = "lowercase")]
294pub enum Policy {
295    /// Never run.
296    Deny,
297    /// Run only if the front-end approver says yes. What "yes" gates depends on the tool: the
298    /// shell asks only about commands that cannot be undone, and the file tools never ask, because
299    /// they refuse anything outside the workspace themselves.
300    Ask,
301    /// Run without asking.
302    Allow,
303}
304
305/// What the shell puts to a person when its policy is [`Policy::Ask`].
306#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
307#[serde(rename_all = "lowercase")]
308pub enum ShellAsk {
309    /// Only a command that can destroy something: `rm`, `sudo`, `dd`, a forced push.
310    #[default]
311    Dangerous,
312    /// Every command, as the interface did before 0.5.1. Kept for a machine where a prompt per
313    /// call is the point — a shared box, a demonstration, a first week with an agent.
314    Always,
315}
316
317/// The `.env` files read for this profile, and what they set.
318///
319/// Read order is shared `.env` then the profile's, so a profile overrides the shared file
320/// key by key. The real process environment still beats both: a `.env` is a fallback for
321/// what the shell did not set, never an override of it — otherwise exporting a variable to
322/// test something would appear not to work.
323///
324/// Only the file *names* are ever printed (`config show`); values are secrets by
325/// assumption, since that is what this file is for.
326#[derive(Clone, Default, PartialEq, Eq)]
327pub struct Dotenv {
328    /// Files that existed and were read, in read order.
329    pub files: Vec<PathBuf>,
330    pub values: BTreeMap<String, String>,
331}
332
333impl fmt::Debug for Dotenv {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        // The file names, and the *names* of what they set — never the values. This file exists
336        // to hold secrets, `Config` derives `Debug`, and `Config` holds this: one `{cfg:?}` in a
337        // panic message or a failing `assert_eq!` would otherwise print the whole secrets file.
338        // The key names stay, because "which variables came from where" is the useful half.
339        f.debug_struct("Dotenv")
340            .field("files", &self.files)
341            .field("keys", &self.values.keys().collect::<Vec<_>>())
342            .finish()
343    }
344}
345
346impl Dotenv {
347    /// Load the `.env` chain for `profile` (if any) from the config directory.
348    pub fn load(env: EnvFn<'_>, profile: Option<&str>) -> Result<Dotenv> {
349        let Some(dir) = config_dir(env) else {
350            return Ok(Dotenv::default());
351        };
352        let mut candidates = vec![dir.join(".env")];
353        if let Some(p) = profile {
354            validate_profile_name(p)?;
355            candidates.push(dir.join("profiles").join(p).join(".env"));
356        }
357        let mut values = BTreeMap::new();
358        let mut files = Vec::new();
359        for path in candidates {
360            if !path.exists() {
361                continue;
362            }
363            // Later files win, so a profile can override one key without restating the rest.
364            // An empty value is *not* a value: the shipped file names every variable and sets
365            // none of them, so `NAME=` has to mean "absent" everywhere, not just where a call
366            // site remembered to filter it. `config init` used to write one line for exactly
367            // that reason, and `setup` still filtered emptiness by hand at two call sites.
368            for assignment in crate::dotenv::load(&path)? {
369                if assignment.value.is_empty() {
370                    values.remove(&assignment.key);
371                    continue;
372                }
373                values.insert(assignment.key, assignment.value);
374            }
375            files.push(path);
376        }
377        Ok(Dotenv { files, values })
378    }
379}
380
381/// `Some("")` is `None` — an empty value is how a shipped config says "not in use".
382///
383/// The shipped file is complete: every key is live, and the ones that name a secret, an address,
384/// a route or a schema are live with `${VAR:-}` or `""`. Without this, `api_key = "${X:-}"` with no
385/// `X` would arrive as `Some("")` and be sent as `Authorization: Bearer *** ` — a failure that shows
386/// up at the far end of a request instead of in the file that caused it. It applies to the
387/// `Option<String>` keys only: `model = ""` and `base_url = ""` are not options but addresses, and
388/// "" already means "not configured" there.
389fn empty_is_none<'de, D>(d: D) -> std::result::Result<Option<String>, D::Error>
390where
391    D: serde::Deserializer<'de>,
392{
393    use serde::Deserialize;
394    Ok(Option::<String>::deserialize(d)?.filter(|v| !v.is_empty()))
395}
396
397#[derive(Clone, PartialEq, Serialize, Deserialize)]
398#[serde(default)]
399pub struct ProviderConfig {
400    /// Base URL of an OpenAI-compatible API, e.g. a local server. No default.
401    pub base_url: String,
402    /// Prefer `api_key_env` or `ECLIPSE_API_KEY` over storing a key here.
403    #[serde(deserialize_with = "empty_is_none")]
404    pub api_key: Option<String>,
405    /// Name of an environment variable holding the key.
406    #[serde(deserialize_with = "empty_is_none")]
407    pub api_key_env: Option<String>,
408    pub model: String,
409    pub temperature: Option<f64>,
410    pub timeout_secs: u64,
411    /// Ask the endpoint for a token-by-token (SSE) reply. Endpoints that ignore the
412    /// request and answer with plain JSON still work; set `false` to never ask.
413    pub stream: bool,
414    /// Extra attempts after a request fails with HTTP 408, 429 or 5xx, or could not be sent at all —
415    /// refused, DNS, TLS (0 = never retry).
416    ///
417    /// Waits `retry_base_delay_ms`, then double, then double again: 2 s, 4 s, 8 s with the defaults.
418    /// Other 4xx statuses are never retried: a wrong key or a rejected option fails the same way
419    /// every time. A failure that happened *after* the request went out — a reset mid-generation, a
420    /// silent connection — is only repeated when [`retry_after_send`](Self::retry_after_send) says
421    /// so, because repeating a billed request can pay for it twice.
422    pub max_retries: u32,
423    /// Repeat a request that failed **after** it went out — the connection dropped mid-generation, or
424    /// nothing came back for `timeout_secs`. Off by default: `/chat/completions` is billed and not
425    /// idempotent, so a repeat can pay for the same work twice, up to `max_retries + 1` times a turn.
426    /// A connect-stage failure (refused, DNS, TLS) never reached the server and is always repeated.
427    pub retry_after_send: bool,
428    pub retry_base_delay_ms: u64,
429    /// Soft cap on the conversation sent to the model, in estimated tokens (characters
430    /// / 4, a rough heuristic). When exceeded, the oldest turns are dropped and replaced
431    /// by a marker note. 0 = disabled.
432    pub context_budget_tokens: usize,
433    /// Cap on the reply, in tokens. Sent under the field name the profile asks for.
434    /// `None` = do not send a cap.
435    pub max_tokens: Option<u32>,
436    /// Wire profile: `openai` (default), `llamacpp`, or one a plugin declares. Profiles
437    /// change how the request is shaped, never what the model is asked.
438    #[serde(deserialize_with = "empty_is_none")]
439    pub profile: Option<String>,
440    /// Nucleus sampling. Unset = do not send. Most local servers default to 1.0 anyway; set
441    /// this when a model rambles.
442    pub top_p: Option<f64>,
443    /// Ask for a reproducible sample where the backend supports it. Unset = do not send.
444    pub seed: Option<i64>,
445    /// Up to four sequences the reply must stop at. Unset = do not send.
446    pub stop: Option<Vec<String>>,
447    /// `low`, `medium` or `high` on backends that have a reasoning knob. Unset = the route's own
448    /// declared default, which is `medium` on both shipped profiles, and nothing at all on a
449    /// backend that declares no default (`#276`); a spelling this backend does not know comes back
450    /// as a 400 naming the field.
451    #[serde(deserialize_with = "empty_is_none")]
452    pub reasoning_effort: Option<String>,
453    /// Ask for several tool calls in one reply. Unset = do not send.
454    pub parallel_tool_calls: Option<bool>,
455    /// Whether this route's model can see images. Overrides the wire profile's declaration:
456    /// `Some(true)` enables vision on a profile that says nothing (such as `llamacpp`),
457    /// `Some(false)` forces vision off even if a profile says `true`, and `None` inherits
458    /// the profile.
459    pub vision: Option<bool>,
460    /// `auto`, `none`, `required`, or a tool name. Overrides the profile's default; unset
461    /// leaves the profile's own value (`auto` where the backend understands the field).
462    pub tool_choice: Option<crate::hooks::ToolChoice>,
463    /// JSON merged into every request body, after the config's own fields and before a
464    /// per-turn patch. The escape hatch for `chat_template_kwargs` and backend quirks this
465    /// build does not model.
466    pub extra_body: Option<serde_json::Value>,
467    /// The order routes are tried in when a request fails for a transient reason. Only
468    /// meaningful directly under `[provider]`; a route that carries one is a config error.
469    /// Unset means "just the `default` route", which is what a config without routes does.
470    #[serde(skip_serializing_if = "Option::is_none")]
471    pub fallback: Option<Vec<String>>,
472    /// The route that does the agent's own housekeeping — the summary of trimmed turns — and
473    /// never the user's work. Only meaningful directly under `[provider]`; a route that carries
474    /// one is a config error. Unset means "the route this run is on".
475    #[serde(skip_serializing_if = "Option::is_none")]
476    #[serde(deserialize_with = "empty_is_none")]
477    pub aux: Option<String>,
478    /// The route a `delegate` call's child agent runs on unless the call names one. Only
479    /// meaningful directly under `[provider]`; a route that carries one is a config error.
480    /// Unset means "the route this run is on".
481    #[serde(skip_serializing_if = "Option::is_none")]
482    #[serde(deserialize_with = "empty_is_none")]
483    pub delegate: Option<String>,
484    /// `[[provider.route]]`: named, complete provider configurations. Only meaningful
485    /// directly under `[provider]`.
486    #[serde(skip_serializing_if = "Vec::is_empty")]
487    pub route: Vec<RouteConfig>,
488}
489
490/// One `[[provider.route]]`: a name and a *complete* [`ProviderConfig`].
491///
492/// Not a delta over `[provider]`. A chain whose entries inherit half their settings from the
493/// one before is a debugging hazard — "which `timeout_secs` did the third hop use?" should
494/// have the answer "the one written under it".
495#[derive(Debug, Clone, PartialEq, Serialize)]
496pub struct RouteConfig {
497    /// What `--route`, `fallback` and the readout call this route.
498    pub name: String,
499    /// How many flares this route may run at once (`#171`). Unset takes the profile's default:
500    /// one for a local server, which serves one model and swaps rather than multiplying, and four
501    /// for an OpenAI-compatible API, where the limit is money and rate, not hardware. `0` reads
502    /// as `1`, the same rule [`ToolsConfig::concurrency`] keeps, because a route with no slot is
503    /// a route flares cannot use and silently starving them is worse than a slow run.
504    #[serde(skip_serializing_if = "Option::is_none")]
505    pub max_parallel: Option<usize>,
506    /// Routes that share one server share its bound (`#171`): two local routes pointed at the same
507    /// llama-swap are one slot, not two, because it swaps by stopping one model to start another.
508    /// A group takes its **lowest** member's bound, the conservative reading of "these are the
509    /// same box".
510    #[serde(skip_serializing_if = "Option::is_none")]
511    pub group: Option<String>,
512    #[serde(flatten)]
513    pub config: ProviderConfig,
514}
515
516/// Written by hand because `#[serde(flatten)]` buffers the table and then reports a wrong-typed
517/// value as "invalid type ... in `provider.route`", dropping the key. A route is exactly where a
518/// misread setting is hardest to spot, so the error says which route and which key.
519impl<'de> Deserialize<'de> for RouteConfig {
520    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
521        use serde::de::Error as _;
522        let mut table = toml::Table::deserialize(d)?;
523        let name = match table.remove("name") {
524            None => String::new(),
525            Some(toml::Value::String(name)) => name,
526            Some(other) => {
527                return Err(D::Error::custom(format!(
528                    "provider.route `name` must be a string, got {}",
529                    other.type_str()
530                )))
531            }
532        };
533        let label = if name.is_empty() {
534            "an unnamed route".to_string()
535        } else {
536            format!("route `{name}`")
537        };
538        // Two keys on a route are not provider settings: they shape how many flares may run on
539        // it (`#171`). Removed here so `ProviderConfig` cannot read one as an unknown key and so
540        // a wrong type is reported against the route that wrote it.
541        let max_parallel = match table.remove("max_parallel") {
542            None => None,
543            Some(toml::Value::Integer(n)) if n >= 0 => Some(n as usize),
544            Some(other) => {
545                return Err(D::Error::custom(format!(
546                    "{label}: `max_parallel` must be a positive integer, got {}",
547                    other.type_str()
548                )))
549            }
550        };
551        let group = match table.remove("group") {
552            None => None,
553            Some(toml::Value::String(g)) if !g.trim().is_empty() => Some(g),
554            Some(_) => {
555                return Err(D::Error::custom(format!(
556                    "{label}: `group` must be a non-empty string"
557                )))
558            }
559        };
560        let config = ProviderConfig::deserialize(toml::Value::Table(table))
561            .map_err(|e| D::Error::custom(format!("{label}: {e}")))?;
562        Ok(Self {
563            name,
564            max_parallel,
565            group,
566            config,
567        })
568    }
569}
570
571/// The name `[provider]` itself goes by once routes exist.
572pub const DEFAULT_ROUTE: &str = "default";
573
574impl ProviderConfig {
575    /// Whether anything but the route table says something about the connection. An empty
576    /// `[provider]` (or none at all) is how a config that only uses routes looks, and it must
577    /// not be mistaken for a `default` route that forgot its `base_url`.
578    ///
579    /// Identity only — where it points, what it serves, which key it uses. A `[provider]` that
580    /// carries nothing but tuning keys (`max_retries`, `temperature`, `context_budget_tokens`)
581    /// is not a route: it names no server, so listing it as one would offer the user a route
582    /// that cannot be used.
583    fn declares_connection(&self) -> bool {
584        !self.base_url.trim().is_empty()
585            || !self.model.trim().is_empty()
586            || self.api_key.is_some()
587            || self.api_key_env.is_some()
588    }
589}
590
591/// A route with its name attached and the route table itself stripped off, so what is left
592/// is exactly one provider's settings.
593#[derive(Debug, Clone, PartialEq)]
594pub struct NamedRoute {
595    pub name: String,
596    /// `[[provider.route]] max_parallel` (`#171`); `None` takes the profile's default.
597    pub max_parallel: Option<usize>,
598    /// `[[provider.route]] group` (`#171`): routes that are one server's worth of slots.
599    pub group: Option<String>,
600    pub config: ProviderConfig,
601}
602
603impl NamedRoute {
604    /// What a flare run may assume about this route when the config says nothing: a local server
605    /// serves one model at a time (llama-swap swaps rather than multiplying), and an API's limit
606    /// is rate and spend. The profile name is the only signal the config gives, so it is the one
607    /// used — guessing from a port would be a rule nobody could read out of the file.
608    pub fn default_parallel(&self) -> usize {
609        let profile = self.config.profile.as_deref().unwrap_or("openai");
610        if profile.eq_ignore_ascii_case("openai") {
611            4
612        } else {
613            1
614        }
615    }
616
617    /// How many flares this route may run at once, with `0` read as `1`.
618    pub fn parallel(&self) -> usize {
619        self.max_parallel
620            .unwrap_or_else(|| self.default_parallel())
621            .max(1)
622    }
623
624    /// The two route keys that are about flares rather than the wire (`#171`), attached after
625    /// construction because the default route has neither.
626    pub fn with_flare_shape(mut self, max_parallel: Option<usize>, group: Option<String>) -> Self {
627        self.max_parallel = max_parallel;
628        self.group = group;
629        self
630    }
631
632    fn new(name: &str, config: &ProviderConfig) -> Self {
633        let mut config = config.clone();
634        config.route.clear();
635        config.fallback = None;
636        config.aux = None;
637        config.delegate = None;
638        Self {
639            name: name.to_string(),
640            max_parallel: None,
641            group: None,
642            config,
643        }
644    }
645
646    /// `[provider]` keeps the messages it has always had; a named route says which one.
647    fn require_endpoint(&self, source: ChainSource) -> Result<()> {
648        let plain = self.name == DEFAULT_ROUTE && source == ChainSource::Default;
649        let missing = |key: &str, hint: &str| {
650            Error::Config(if plain {
651                format!("provider.{key} is not set {hint}")
652            } else {
653                format!("route `{}` has no {key}", self.name)
654            })
655        };
656        if self.config.base_url.trim().is_empty() {
657            return Err(missing(
658                "base_url",
659                "(config file or ECLIPSE_BASE_URL); run `eclipse config init`",
660            ));
661        }
662        if self.config.model.trim().is_empty() {
663            return Err(missing("model", "(config file or ECLIPSE_MODEL)"));
664        }
665        Ok(())
666    }
667}
668
669/// Where a run's chain of routes came from.
670#[derive(Debug, Clone, Copy, PartialEq, Eq)]
671pub enum ChainSource {
672    /// No `fallback`, no pin: `[provider]` alone, exactly as before routes existed.
673    Default,
674    /// `[provider] fallback`: tried in order on a transient failure.
675    Fallback,
676    /// `--route` or `ECLIPSE_ROUTE`: one route, and no falling back from it.
677    Pinned,
678}
679
680/// The routes one run will use, in order.
681#[derive(Debug, Clone, PartialEq)]
682pub struct Chain {
683    pub routes: Vec<NamedRoute>,
684    pub source: ChainSource,
685    /// The route `[provider] aux` names; `None` when unset, which means the first of `routes`.
686    pub aux: Option<NamedRoute>,
687    /// The route `[provider] delegate` names; `None` when unset, which means the first of `routes`.
688    pub delegate: Option<NamedRoute>,
689}
690
691impl Chain {
692    /// Which route each role uses: the one answer `config show`, `/status` and the panel share.
693    pub fn roles(&self) -> Vec<crate::router::RoleRoute> {
694        crate::router::role_table(
695            self.aux.as_ref().map(|r| r.name.as_str()),
696            self.delegate.as_ref().map(|r| r.name.as_str()),
697            self.routes.first().map_or("", |r| r.name.as_str()),
698            self.source == ChainSource::Pinned,
699        )
700    }
701}
702
703/// `api_key_env` (and an explicit override) resolved against `env`. Kept as one function so
704/// `[provider]` and every route follow the same rule: the named variable beats a literal key.
705fn apply_key_env(cfg: &mut ProviderConfig, env: EnvFn, explicit: Option<String>) {
706    if let Some(v) = explicit {
707        cfg.api_key = Some(v);
708    } else if let Some(name) = cfg.api_key_env.clone() {
709        if let Some(v) = env(&name) {
710            cfg.api_key = Some(v);
711        }
712    }
713}
714
715impl Default for ProviderConfig {
716    fn default() -> Self {
717        Self {
718            base_url: String::new(),
719            api_key: None,
720            api_key_env: None,
721            model: String::new(),
722            temperature: None,
723            timeout_secs: 120,
724            stream: true,
725            max_retries: 3,
726            retry_after_send: false,
727            retry_base_delay_ms: 2000,
728            context_budget_tokens: 0,
729            max_tokens: None,
730            profile: None,
731            top_p: None,
732            seed: None,
733            stop: None,
734            reasoning_effort: None,
735            parallel_tool_calls: None,
736            vision: None,
737            tool_choice: None,
738            extra_body: None,
739            fallback: None,
740            aux: None,
741            delegate: None,
742            route: Vec::new(),
743        }
744    }
745}
746
747impl fmt::Debug for ProviderConfig {
748    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749        f.debug_struct("ProviderConfig")
750            // The same URL the redacted TOML scrubs: a `{cfg:?}` in a panic message must not be
751            // the one place a gateway password survives.
752            .field(
753                "base_url",
754                &redact_url(&self.base_url).unwrap_or_else(|| self.base_url.clone()),
755            )
756            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
757            .field("api_key_env", &self.api_key_env)
758            .field("model", &self.model)
759            .field("temperature", &self.temperature)
760            .field("timeout_secs", &self.timeout_secs)
761            .field("stream", &self.stream)
762            .field("max_retries", &self.max_retries)
763            .field("retry_after_send", &self.retry_after_send)
764            .field("retry_base_delay_ms", &self.retry_base_delay_ms)
765            .field("context_budget_tokens", &self.context_budget_tokens)
766            .field("vision", &self.vision)
767            .field("fallback", &self.fallback)
768            .field("aux", &self.aux)
769            .field("delegate", &self.delegate)
770            .field("route", &self.route)
771            .finish()
772    }
773}
774
775#[derive(Debug, Clone, Serialize, Deserialize)]
776#[serde(default)]
777pub struct AgentConfig {
778    /// Stop the run after this many consecutive tool calls that could not be used (an unknown
779    /// tool, or arguments that are not JSON). 0 disables it, which is the default: a model that
780    /// slips once should get another chance, and only a repeat is a pattern.
781    pub max_consecutive_malformed_tool_calls: usize,
782    pub system_prompt: String,
783    /// How many model <-> tool round trips one turn may take. No cap by default: the same
784    /// default Hermes' engine uses, and the honest one, because the number that is right for a
785    /// one-line answer is not the number that is right for a file-plus-tests-plus-a-retry. A cap
786    /// is a policy for the box it runs on, so it is set there, not imposed here.
787    #[serde(
788        default = "unlimited_turns",
789        deserialize_with = "de_turn_limit",
790        serialize_with = "ser_turn_limit"
791    )]
792    pub max_iterations: usize,
793    /// A JSON Schema every reply must satisfy, as a path (relative to the working directory, like
794    /// `workspace_root`) or an inline JSON document. A default for `eclipse run`; a schema is a
795    /// contract, not a chat setting, so the interactive surfaces ignore it.
796    #[serde(deserialize_with = "empty_is_none")]
797    pub output_schema: Option<String>,
798    /// Truncate a single context file past this many characters (head and tail kept, with a
799    /// visible marker). 0 = no per-file cap.
800    pub context_file_max_chars: usize,
801    /// Ceiling across every context file; whole files are dropped past it, broadest first,
802    /// and `eclipse context show` says which. 0 = no cap.
803    pub context_files_budget_chars: usize,
804    /// Include prompts, arguments and results in tracing spans. Off by default: the
805    /// transcript is already readable; the spans exist for timing and routing.
806    pub trace_content: bool,
807    /// Which standing prompt blocks ride after `system_prompt` (`#244`): `auto` (the default) takes
808    /// every block whose gate matches the model, a list names them, `off` sends none. The library is
809    /// [`crate::prompt_blocks`]; `config check` prints what this model is actually being told.
810    pub prompt_blocks: crate::prompt_blocks::Choice,
811}
812
813/// No cap. `usize::MAX` rather than an `Option` so every caller that multiplies, counts or
814/// compares a budget keeps working: `for turn in 0..budget` simply never reaches the end.
815fn unlimited_turns() -> usize {
816    usize::MAX
817}
818
819/// A turn budget is written as a number when someone wants a cap and as a word when they do not.
820/// `0` and `-1` mean no cap too — they are what people type when they mean "off", and answering
821/// "your run gets one request" would be a trap.
822fn de_turn_limit<'de, D>(d: D) -> std::result::Result<usize, D::Error>
823where
824    D: serde::Deserializer<'de>,
825{
826    #[derive(serde::Deserialize)]
827    #[serde(untagged)]
828    enum Raw {
829        Number(i64),
830        Word(String),
831    }
832    let n = match Raw::deserialize(d)? {
833        Raw::Number(n) => n,
834        Raw::Word(word) => match word.trim().to_ascii_lowercase().as_str() {
835            "unlimited" | "none" | "null" | "inf" | "infinite" | "infinity" | "∞" => 0,
836            other => other.parse::<i64>().map_err(|_| {
837                serde::de::Error::custom(format!(
838                    "`max_iterations` takes a whole number or `unlimited`, not `{other}`"
839                ))
840            })?,
841        },
842    };
843    Ok(if n <= 0 {
844        unlimited_turns()
845    } else {
846        n as usize
847    })
848}
849
850/// Printed as the word, so `config show` and the starter file both say what they mean instead of
851/// `18446744073709551615`.
852fn ser_turn_limit<S>(value: &usize, s: S) -> std::result::Result<S::Ok, S::Error>
853where
854    S: serde::Serializer,
855{
856    if *value == usize::MAX {
857        s.serialize_str("unlimited")
858    } else {
859        s.serialize_u64(*value as u64)
860    }
861}
862
863impl Default for AgentConfig {
864    fn default() -> Self {
865        Self {
866            system_prompt:
867                "You are a helpful personal assistant running locally on the user's machine. \
868Use tools only when they are needed, and explain briefly what you did."
869                    .into(),
870            max_iterations: unlimited_turns(),
871            output_schema: None,
872            max_consecutive_malformed_tool_calls: 0,
873            context_file_max_chars: crate::context_files::DEFAULT_MAX_FILE_CHARS,
874            context_files_budget_chars: crate::context_files::DEFAULT_BUDGET_CHARS,
875            trace_content: false,
876            prompt_blocks: crate::prompt_blocks::Choice::Auto,
877        }
878    }
879}
880
881#[derive(Debug, Clone, Serialize, Deserialize)]
882#[serde(default)]
883pub struct ToolsConfig {
884    /// File tools are confined to this directory. Defaults to the current directory.
885    pub workspace_root: Option<PathBuf>,
886    pub read_file: Policy,
887    /// The `search_files` tool: a read-only walk of the workspace. `allow` for the same reason as
888    /// `read_file` — the tree it walks is confined, and a prompt per search is the noise that
889    /// teaches people to approve without reading.
890    pub search_files: Policy,
891    pub write_file: Policy,
892    /// Above this many bytes, clobbering an existing file with `write_file` needs `force`.
893    /// A rewrite carries the whole file as a tool-call argument, and that argument stays in the
894    /// conversation for the rest of the session — the single most expensive way to change a line.
895    /// `0` switches the guard off.
896    #[serde(default = "default_rewrite_guard")]
897    pub rewrite_guard_bytes: usize,
898    /// The `patch` tool: a targeted edit of a file that already exists. Same default as
899    /// `write_file`, because it is the same side effect, more carefully aimed.
900    pub patch: Policy,
901    /// The `memory` tool: write a durable fact to `MEMORY.md`, which is loaded into every later
902    /// system prompt of the session. `ask` by default: clean writes still run silently, and only
903    /// writes carrying a verbatim run from a tool result in the same turn prompt (`#482`).
904    /// `allow` skips the taint check; `deny` disables the tool.
905    pub memory: Policy,
906    pub shell: Policy,
907    pub fetch: Policy,
908    /// The `script` tool, which runs a file from the scripts directory. `ask` by default: a
909    /// script is arbitrary code, and one the agent wrote itself is no more trustworthy for it.
910    /// A bare `{"list": true}` is a read of a directory the user owns and is not asked about.
911    pub script: Policy,
912    /// The `execute_code` tool: a short program written for one job, run from a temporary file
913    /// that is deleted afterwards, with a bridge back to the registry so the program can call
914    /// tools. `ask` by default: it is arbitrary code, and a bridge makes it more useful, not
915    /// more trustworthy.
916    pub execute_code: Policy,
917    /// The `delegate` tool, which hands a job to a child agent. `ask` by default: a child
918    /// spends tokens, possibly on a bigger model than the one you are talking to, and may run
919    /// tools of its own.
920    pub delegate: Policy,
921    /// Timeout for `shell` and for `script`: they are the same kind of thing, a process the
922    /// agent started, and one number keeps them honest with each other.
923    /// Whether the shell asks about every command or only about the dangerous ones.
924    pub shell_ask: ShellAsk,
925    pub shell_timeout_secs: u64,
926    /// If non-empty, `shell` only runs these program names, without a shell.
927    pub shell_allowlist: Vec<String>,
928    /// What a `shell` command can reach: `off` (a plain process), `process` (a private PID
929    /// namespace, filesystem unchanged) or `fs` (also a read-only filesystem). `process` by
930    /// default. Any mode but `off` needs bubblewrap, and refuses to run without it rather
931    /// than quietly running unsandboxed.
932    pub shell_isolate: ShellIsolate,
933    /// Paths bound read-write in `fs` mode, beyond the workspace and the scripts directory.
934    /// `~` is the home directory. A cargo build needs `~/.cargo` here.
935    pub shell_isolate_writable: Vec<PathBuf>,
936    /// Paths replaced by an empty directory in `fs` mode, so their contents cannot be read.
937    /// `~` is the home directory.
938    pub shell_isolate_hide: Vec<PathBuf>,
939    /// Whether `fs` mode keeps the network. `true` by default: a build needs it, and a task
940    /// that only edits files can turn it off.
941    pub shell_isolate_network: bool,
942    pub fetch_timeout_secs: u64,
943    /// `text` (default) converts HTML responses to plain text; `raw` returns the source.
944    /// The model can override per call with `{"raw": true|false}`.
945    pub fetch_html: FetchHtml,
946    /// Tool output is truncated to this many bytes before reaching the model.
947    pub max_output_bytes: usize,
948    /// How many of one turn's tool calls may run at the same time. 1 (the default) runs them
949    /// one after another; 0 is treated as 1. Results are committed in the order the model
950    /// emitted the calls, whatever this is set to.
951    pub concurrency: usize,
952    /// Tools to remove entirely, whatever their policy says. Not offered to the model, and a
953    /// call that names one is refused — the point is that a hallucinated call cannot slip
954    /// through. Stronger than `deny`: it also survives a plugin claiming the name.
955    pub disabled: Vec<String>,
956    /// Tools that stay registered and callable but are **not** described in the request, so they
957    /// cost no tokens until they are needed. `tool_search` finds them by keyword,
958    /// `tool_describe` gives their arguments, and `tool_call` runs them — all three through the
959    /// same policy, approval and hook path as a direct call, so deferring a tool moves it out of
960    /// the prompt and changes nothing else. `"*"` defers everything registered, and a trailing
961    /// `*` is a prefix. A pattern is matched against a tool's **name** and against its **source**
962    /// (`plugin:mcp:<server>`), because MCP tools keep the names their server published and so
963    /// cannot be deferred by name (`#351`).
964    ///
965    /// The shipped default is `plugin:mcp:*`: an MCP server is where forty tools come from, and
966    /// forty schemas in every request is four thousand tokens of promise. Plugins that declare a
967    /// handful of tools stay visible; anything can be deferred or un-deferred explicitly.
968    #[serde(default = "default_deferred")]
969    pub deferred: Vec<String>,
970    /// The three tools that reach the deferred ones. `allow` by default: none of them has a
971    /// side effect of its own, and `tool_call` is a router — the tool it routes *to* is what
972    /// the policy and the approval prompt are about, so asking twice would only train the user
973    /// to hold down Enter.
974    pub tool_search: Policy,
975    pub tool_describe: Policy,
976    pub tool_call: Policy,
977}
978
979/// The secrets under `$HOME` that `fs` mode empties by default: what an injected command would
980/// look for first, and none of which a build needs.
981///
982/// The state directory is deliberately absent: it holds the scripts directory, which every run
983/// writes into, so a hide over it would be dropped every time and the status line would carry a
984/// warning that never means anything. A profile that keeps its own state elsewhere can add it.
985/// The paths `[tools] shell_isolate_hide` names when the file says nothing.
986///
987/// Public because the sandbox has to tell "this machine does not have `~/.aws`" from "you spelled
988/// your own hide wrong": the first is a suggestion that missed, the second leaves a file the
989/// person believes is withheld (#552).
990pub fn default_hidden_paths() -> Vec<PathBuf> {
991    ["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
992        .iter()
993        .map(PathBuf::from)
994        .collect()
995}
996
997/// 32 KB: large enough that no honest one-shot rewrite trips it (a README, a config file, a
998/// script), small enough that the files worth patching — a single-file app, a long document —
999/// are guarded. A rewrite of something bigger is a decision, not an accident.
1000/// MCP tools are deferred out of the box (`#351`): an MCP server is where forty tools come from,
1001/// and forty schemas in every request is four thousand tokens of promise. Matched against the
1002/// tool's source label (`plugin:mcp:<server>`), not its name — MCP tools keep the name the server
1003/// published (`#373`), so `mcp_*` would match nothing.
1004fn default_deferred() -> Vec<String> {
1005    vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
1006}
1007
1008fn default_rewrite_guard() -> usize {
1009    32 * 1024
1010}
1011
1012impl Default for ToolsConfig {
1013    fn default() -> Self {
1014        Self {
1015            workspace_root: None,
1016            read_file: Policy::Allow,
1017            search_files: Policy::Allow,
1018            // The file tools confine every path to the workspace (and the scripts directory) and
1019            // refuse the rest, so the refusal — not a prompt — is what keeps them honest. Asking
1020            // on top of a boundary that already holds is the noise that teaches `y`.
1021            write_file: Policy::Allow,
1022            rewrite_guard_bytes: default_rewrite_guard(),
1023            patch: Policy::Allow,
1024            memory: Policy::Ask,
1025            shell: Policy::Ask,
1026            fetch: Policy::Ask,
1027            script: Policy::Ask,
1028            execute_code: Policy::Ask,
1029            delegate: Policy::Ask,
1030            shell_ask: ShellAsk::Dangerous,
1031            shell_timeout_secs: 30,
1032            shell_allowlist: Vec::new(),
1033            shell_isolate: ShellIsolate::Process,
1034            shell_isolate_writable: Vec::new(),
1035            shell_isolate_hide: default_hidden_paths(),
1036            shell_isolate_network: true,
1037            fetch_timeout_secs: 20,
1038            fetch_html: FetchHtml::Text,
1039            max_output_bytes: 32 * 1024,
1040            concurrency: 1,
1041            disabled: Vec::new(),
1042            deferred: default_deferred(),
1043            tool_search: Policy::Allow,
1044            tool_describe: Policy::Allow,
1045            tool_call: Policy::Allow,
1046        }
1047    }
1048}
1049
1050#[derive(Debug, Clone, Serialize, Deserialize)]
1051#[serde(default)]
1052pub struct SessionsConfig {
1053    /// Defaults to `<state_dir>/sessions`.
1054    pub dir: Option<PathBuf>,
1055    /// Default for `sessions prune --keep-days`: delete sessions whose last activity is
1056    /// older than this many days. 0 = disabled. Applied unattended only if `auto_prune`.
1057    pub retention_keep_days: u64,
1058    /// Default for `sessions prune --keep-count`: keep only the newest N sessions.
1059    /// 0 = disabled. Applied unattended only if `auto_prune`.
1060    pub retention_keep_count: usize,
1061    /// Apply the retention limits when the CLI starts (`run` and the REPL), before the
1062    /// prompt. Off by default. It deletes only if at most 10 sessions would go; otherwise
1063    /// it warns and deletes nothing. With both limits 0 it does nothing. The web dashboard
1064    /// never prunes.
1065    pub auto_prune: bool,
1066    /// How long a run waits for another *process* to release the same session before it
1067    /// fails. 0 = do not wait at all (fail on the first refusal).
1068    pub lock_wait_secs: u64,
1069    /// Name sessions: a name derived from the opening message before the first request, and at
1070    /// most one small-model call per session to replace it with a better one. The call goes to
1071    /// `provider.aux` when there is one, so it costs the cheap route and never the turn's model.
1072    pub autotitle: bool,
1073}
1074
1075impl Default for SessionsConfig {
1076    fn default() -> Self {
1077        Self {
1078            dir: None,
1079            retention_keep_days: 0,
1080            retention_keep_count: 0,
1081            auto_prune: false,
1082            lock_wait_secs: 30,
1083            autotitle: true,
1084        }
1085    }
1086}
1087
1088#[derive(Clone, Serialize, Deserialize)]
1089#[serde(default)]
1090pub struct WebConfig {
1091    pub host: String,
1092    pub port: u16,
1093    /// Dashboard login secret, generated by `config init`. The dashboard refuses to
1094    /// start without one.
1095    #[serde(deserialize_with = "empty_is_none")]
1096    pub auth_token: Option<String>,
1097    /// How long a browser stays signed in. `0` is read as the default rather than as
1098    /// "expire immediately", which would make the dashboard unusable.
1099    pub session_ttl_hours: u64,
1100    /// Which profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE`
1101    /// names one. `None` means the `default` profile.
1102    #[serde(deserialize_with = "empty_is_none")]
1103    pub default_profile: Option<String>,
1104}
1105
1106impl Default for WebConfig {
1107    fn default() -> Self {
1108        Self {
1109            host: "127.0.0.1".into(),
1110            port: 8787,
1111            auth_token: None,
1112            session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
1113            default_profile: None,
1114        }
1115    }
1116}
1117
1118/// `[gateway]`: the one long-lived process that keeps the whole thing running.
1119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1120#[serde(default)]
1121pub struct GatewayConfig {
1122    /// How often the gateway runs the update check and logs what it found. Log-only: a version
1123    /// change is a decision, and the gateway is not the place to make it. `0` turns the check
1124    /// off.
1125    pub check_interval_hours: u64,
1126    /// How long a session created by `POST /v1/chat/completions` is kept. The loop stores every
1127    /// turn, so each API call leaves one behind; they are tagged `api` and swept after this many
1128    /// hours, so a script polling the endpoint cannot fill the store. `0` keeps them forever.
1129    #[serde(default = "default_api_session_ttl_hours")]
1130    pub api_session_ttl_hours: u64,
1131}
1132
1133pub fn default_api_session_ttl_hours() -> u64 {
1134    24
1135}
1136
1137impl Default for GatewayConfig {
1138    fn default() -> Self {
1139        Self {
1140            check_interval_hours: 6,
1141            api_session_ttl_hours: default_api_session_ttl_hours(),
1142        }
1143    }
1144}
1145
1146/// How long a dashboard login lasts before the browser has to sign in again.
1147pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;
1148
1149/// What the CLI does when a tool's policy is `ask`.
1150#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1151#[serde(rename_all = "lowercase")]
1152pub enum Approval {
1153    /// Prompt. The default, and the only setting that lets you see what a tool is about to do.
1154    #[default]
1155    Ask,
1156    /// Never prompt: behave as if `--yes` were always passed.
1157    Auto,
1158    /// Ask the aux route (`#340`). An `ask`-policy call is put to a cheap model as **allow**,
1159    /// **deny** or **escalate**; only the escalate costs a card. A `deny` policy is untouched —
1160    /// the judge may clear a call that was going to be asked about, never widen the registry —
1161    /// and every doubt (a dead route, a timeout, an answer in the wrong words) escalates, because
1162    /// a timeout that read as "carry on" would be a command nobody approved.
1163    Smart,
1164}
1165
1166/// Terminal behaviour. Every field here is read by the CLI; a setting nothing reads is a lie
1167/// in the starter config.
1168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1169#[serde(default)]
1170pub struct CliConfig {
1171    /// Colour. `None` means decide from the stream: a terminal, and `NO_COLOR` unset.
1172    pub color: Option<bool>,
1173    /// Markdown in replies. `None` means on when colour is on, off when piping.
1174    pub markdown: Option<bool>,
1175    /// What an `ask` policy does. `"ask"` prompts, `"auto"` never does, `"smart"` asks the aux
1176    /// route first and escalates to you when it is unsure.
1177    pub approval: Approval,
1178    /// How many commands the REPL remembers for arrow-up.
1179    pub history_size: usize,
1180    /// What an interactive exit does to the screen.
1181    pub clear_on_exit: ClearOnExit,
1182}
1183
1184impl Default for CliConfig {
1185    fn default() -> Self {
1186        Self {
1187            color: None,
1188            markdown: None,
1189            approval: Approval::Ask,
1190            // Matches the constant the REPL used before this was configurable.
1191            history_size: 1000,
1192            clear_on_exit: ClearOnExit::Screen,
1193        }
1194    }
1195}
1196
1197/// What an interactive exit does to the screen: `[cli] clear_on_exit`.
1198///
1199/// The interface draws in the terminal's ordinary buffer, so its last frame survives the process
1200/// and the shell prompt lands underneath it — which reads exactly like a crash. Clearing and
1201/// printing one line says which of the two happened.
1202#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1203#[serde(rename_all = "lowercase")]
1204pub enum ClearOnExit {
1205    /// Clear the visible screen and keep the scrollback. The default: what was scrolled past is
1206    /// the reader's own copy/paste history, and this program deliberately does not own it.
1207    #[default]
1208    Screen,
1209    /// Clear the visible screen and the scrollback behind it.
1210    All,
1211    /// Clear nothing; the goodbye line is simply printed where the frame ended.
1212    Off,
1213}
1214
1215/// How often the update notice asks the public repository for its latest commit.
1216#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1217#[serde(rename_all = "lowercase")]
1218pub enum UpdateCheck {
1219    /// At most once a day. The default: a notice that arrives a month late is not a notice.
1220    #[default]
1221    Daily,
1222    Weekly,
1223    /// Never. No request is made, and nothing is cached.
1224    Off,
1225}
1226
1227impl UpdateCheck {
1228    /// Seconds that must pass between two checks, `None` for `Off`.
1229    pub fn period_secs(self) -> Option<u64> {
1230        match self {
1231            UpdateCheck::Daily => Some(86_400),
1232            UpdateCheck::Weekly => Some(7 * 86_400),
1233            UpdateCheck::Off => None,
1234        }
1235    }
1236}
1237
1238/// Which branch a *source* install follows: `[update] track`.
1239///
1240/// Two names, because there are two long-lived branches and nothing else: `main` only ever takes
1241/// a release or a hotfix, `develop` is where work lands. `release` and `main` are one ref by
1242/// construction, so a second word for the branch would be the confusion the branch model exists
1243/// to end — the key names a track, and a track names a branch.
1244#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1245#[serde(rename_all = "lowercase")]
1246pub enum Track {
1247    /// `main`: the branch releases are cut from, and what every install did before the key
1248    /// existed. The default.
1249    #[default]
1250    Release,
1251    /// `develop`: the branch work lands on — tomorrow's commits, for a checkout that wants them.
1252    Develop,
1253}
1254
1255impl Track {
1256    /// The word the setting takes and the surfaces print.
1257    pub fn label(self) -> &'static str {
1258        match self {
1259            Track::Release => "release",
1260            Track::Develop => "develop",
1261        }
1262    }
1263
1264    /// The branch it follows. `release` is `main`; this is why the key names a track rather than
1265    /// making a person choose between two words for one branch.
1266    pub fn branch(self) -> &'static str {
1267        match self {
1268            Track::Release => "main",
1269            Track::Develop => "develop",
1270        }
1271    }
1272}
1273
1274/// `[hooks]`: which in-process loop hooks run, and their settings.
1275///
1276/// `order` is the composition order, and the only list: a hook that is not named in it does
1277/// not run, and a settings table for a hook that is not named in it is refused at load rather
1278/// than quietly never used. Absent, it is `["redact-secrets"]`; `order = []` runs nothing.
1279#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1280#[serde(default)]
1281pub struct HooksConfig {
1282    pub order: Vec<String>,
1283    /// The `[hooks.<name>]` tables. Read as loose TOML so the parser drops nothing: every key
1284    /// here is checked by [`crate::hooks::validate`], which names the one that is wrong.
1285    #[serde(flatten)]
1286    pub settings: BTreeMap<String, toml::Value>,
1287}
1288
1289impl Default for HooksConfig {
1290    fn default() -> Self {
1291        Self {
1292            order: crate::hooks::DEFAULT_ORDER
1293                .iter()
1294                .map(|n| n.to_string())
1295                .collect(),
1296            settings: BTreeMap::new(),
1297        }
1298    }
1299}
1300
1301/// `[update]`: the notice that says a newer commit exists. It is the only request this tool
1302/// makes that is neither a model call nor something the user asked for, so it has a switch.
1303#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1304#[serde(default)]
1305pub struct UpdateConfig {
1306    pub check: UpdateCheck,
1307    /// Which branch a *source* install follows: `release` is `main`, `develop` is the branch work
1308    /// lands on. The ref comes from here rather than from the checkout's upstream, so a checkout
1309    /// parked on a feature branch is refused instead of quietly becoming an update channel
1310    /// nobody chose. A `release` install has no branch to follow at all: it compares tags, and
1311    /// `eclipse upgrade` refuses the develop track there rather than pretending.
1312    pub track: Track,
1313    /// Where the latest commit is asked for, instead of the public GitHub repository: an
1314    /// http(s) URL that answers with a commit id, either as the whole body or as a JSON
1315    /// object with a `sha` field. Because the user wrote it, it may be a host on a private
1316    /// network, which the `fetch` tool's public-hosts rule would refuse.
1317    #[serde(deserialize_with = "empty_is_none")]
1318    pub remote: Option<String>,
1319    /// Where the newest release is asked for, instead of the public GitHub repository: an
1320    /// http(s) URL answering with the same JSON shape (`tag_name`, `assets[].name` and
1321    /// `assets[].browser_download_url`). `eclipse upgrade` on a release install reads its
1322    /// download URLs from this answer, so a mirror is a mirror. May be a host on your network.
1323    #[serde(deserialize_with = "empty_is_none")]
1324    pub releases: Option<String>,
1325}
1326
1327impl fmt::Debug for WebConfig {
1328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1329        f.debug_struct("WebConfig")
1330            .field("host", &self.host)
1331            .field("port", &self.port)
1332            .field(
1333                "auth_token",
1334                &self.auth_token.as_ref().map(|_| "<redacted>"),
1335            )
1336            .finish()
1337    }
1338}
1339
1340/// `[attachments]`: where the pictures someone attaches are kept (`#499`).
1341///
1342/// A picture has two facts that used to conflict — the original file, and a small payload the wire
1343/// will carry — and keeping both means keeping files. These are the two decisions that follow: where
1344/// they go, and how much room they may take.
1345#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1346#[serde(default)]
1347pub struct AttachmentsConfig {
1348    /// Where pictures are stored. `None` means `<state_dir>/attachments` — not the workspace,
1349    /// which the agent writes to (a `write_file` could clobber a photo, and `git status` in a
1350    /// project should not list someone's holiday snap), and not a temp directory, which is pruned.
1351    pub dir: Option<PathBuf>,
1352    /// Ceiling for everything kept, in bytes. The oldest files are pruned when an attach would
1353    /// exceed it; only if pruning cannot free enough is the attach refused. 0 = no ceiling, which
1354    /// is the one setting here worth being deliberate about.
1355    pub max_total_bytes: u64,
1356}
1357
1358impl Default for AttachmentsConfig {
1359    fn default() -> Self {
1360        Self {
1361            dir: None,
1362            max_total_bytes: 2 * 1024 * 1024 * 1024,
1363        }
1364    }
1365}
1366
1367#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1368#[serde(default)]
1369pub struct Config {
1370    /// The `config_version` the file was written with, and the one thing here that is metadata
1371    /// rather than a setting: it is not in the catalogue, `config set` refuses it, and the agent
1372    /// never reads it. `0` means "written before the stamp existed" and is the version every
1373    /// install older than this key reports.
1374    ///
1375    /// Top-level because it describes the file, and it must survive a section rename.
1376    pub config_version: u32,
1377    pub provider: ProviderConfig,
1378    pub agent: AgentConfig,
1379    pub tools: ToolsConfig,
1380    pub sessions: SessionsConfig,
1381    pub attachments: AttachmentsConfig,
1382    pub plugins: PluginsConfig,
1383    pub web: WebConfig,
1384    pub gateway: GatewayConfig,
1385    pub cli: CliConfig,
1386    pub update: UpdateConfig,
1387    pub hooks: HooksConfig,
1388    pub context: ContextPolicyConfig,
1389    pub user: UserConfig,
1390    pub skills: SkillsConfig,
1391    pub vision: VisionConfig,
1392    /// Which profile this was loaded as. Not part of the file: it comes from `--profile` /
1393    /// `ECLIPSE_PROFILE`, and only decides which overlay and which directories apply.
1394    #[serde(skip)]
1395    pub profile: Option<String>,
1396    /// The route a run is pinned to (`--route`, else `ECLIPSE_ROUTE`). Not part of the file:
1397    /// pinning is a decision about one invocation. Set through [`Config::pin_route`].
1398    #[serde(skip)]
1399    pub route_pin: Option<String>,
1400    /// Which `.env` files were read and what they held. Not part of the file, and never
1401    /// serialised: values are exactly what must not be printed.
1402    #[serde(skip)]
1403    pub dotenv: Dotenv,
1404    /// `[[mcp]]`: MCP servers declared in `config.toml` (`#352`). The same spec a plugin manifest
1405    /// carries — one loader, two providers — and the one a name clash with a manifest wins, because
1406    /// this file is somebody's decision about this machine while a manifest is what a plugin
1407    /// shipped. Tools they list are reported as `config:mcp:<server>`.
1408    #[serde(default)]
1409    pub mcp: Vec<crate::mcp::Spec>,
1410    /// `--no-mcp`: start no MCP server for this process. Not part of the file — it is a decision
1411    /// about one invocation, and it exists because a server that hangs at startup must not be
1412    /// able to lock someone out of their own agent.
1413    #[serde(skip)]
1414    pub no_mcp: bool,
1415    /// `[flares]`: the budget and cap defaults a flare run starts from (`#171`).
1416    #[serde(default)]
1417    pub flares: FlaresConfig,
1418    /// `[bots.<name>]`: named agent identities (`#509`). A bot is a declaration plus one session
1419    /// whose `origin` is `bot:<name>` — no second runtime and no second store. The gateway reads
1420    /// this table at startup, keeps an agent per bot, and the Bots tab lists what it found.
1421    #[serde(default)]
1422    pub bots: std::collections::BTreeMap<String, BotConfig>,
1423}
1424
1425/// `[flares]`: what a run costs and how wide it may go (`#171`).
1426///
1427/// Every number here is a limit, not a promise: a run is N jobs the lead named, and these are
1428/// what stops an N from being expensive. `count` is only the default for `flares run -n` — the
1429/// model-facing tool never gets a count, it names its jobs.
1430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1431#[serde(default)]
1432pub struct FlaresConfig {
1433    /// The default for `flares run -n`, and the number a local run starts from. An accidental
1434    /// fan-out on a server that serves one model at a time is ten minutes of serial turns.
1435    pub count: usize,
1436    /// The most flares one run may have in flight, whatever the routes would allow.
1437    pub max_concurrent: usize,
1438    /// Per flare, when the job does not say: the same budget `delegate` gives a child.
1439    pub max_iterations: usize,
1440    /// The run's own budget. Not `count x max_iterations` in disguise: this is what stops one
1441    /// wandering flare before it eats the budget of the three beside it.
1442    pub total_iterations: usize,
1443    /// Optional spend cap for the whole run, in tokens. Unset: no cap beyond iterations.
1444    pub total_tokens: Option<u64>,
1445}
1446
1447impl Default for FlaresConfig {
1448    fn default() -> Self {
1449        Self {
1450            count: 3,
1451            max_concurrent: 4,
1452            max_iterations: 6,
1453            total_iterations: 24,
1454            total_tokens: None,
1455        }
1456    }
1457}
1458
1459impl FlaresConfig {
1460    /// What this config can actually do: `max_concurrent`, floored by the slots the named routes
1461    /// bring, and never below one.
1462    pub fn concurrency(&self) -> usize {
1463        self.max_concurrent.max(1)
1464    }
1465
1466    /// How many iterations one flare gets when its job does not say.
1467    pub fn per_flare(&self) -> usize {
1468        self.max_iterations.max(1)
1469    }
1470
1471    /// The run's budget as written. Deliberately **not** floored at one flare's worth: a run set
1472    /// to two iterations with a per-flare default of six gives its first flare two and drops the
1473    /// rest, and saying so is more honest than quietly raising the number the operator typed.
1474    pub fn budget(&self) -> usize {
1475        self.total_iterations.max(1)
1476    }
1477}
1478
1479/// `[bots.<name>]`: one named agent identity (`#509`).
1480///
1481/// Every key is optional, because a bot with no keys is still a bot: a session of its own, in
1482/// the list, with the agent's ordinary prompt. What each key overrides is *only* that bot's run —
1483/// the instructions are added to the system prompt rather than replacing it, and nothing here
1484/// changes what the human's own sessions see.
1485#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1486#[serde(default)]
1487pub struct BotConfig {
1488    /// The file this bot's instructions are read from, relative to this profile's directory
1489    /// unless absolute. **Added** to the assembled system prompt, never a replacement: the run is
1490    /// still the CLI/web agent with the bot's words in front of it.
1491    pub instructions: Option<String>,
1492    /// The skills this bot may see, by name. Absent leaves every root in force; an empty list is
1493    /// a bot that sees none — the difference exists because "I declared nothing" and "I declared
1494    /// nothing for it" are not the same sentence.
1495    pub skills: Option<Vec<String>>,
1496    /// Where this bot's `MEMORY.md` lives, relative to this profile's directory unless absolute.
1497    /// Unset means `<profile>/memory/bots/<name>/MEMORY.md`, so a bot's memory is its own file
1498    /// whether or not anyone said where.
1499    pub memory: Option<String>,
1500    /// The lane that reaches this bot. Unset means web only; `telegram` is slice 3 and is not
1501    /// wired yet, so naming it is refused at startup rather than silently ignored.
1502    pub adapter: Option<String>,
1503}
1504
1505/// The adapters this build can actually drive (`#509`). Slice 3 adds `telegram`; a name that is
1506/// not here is reported by `problems` rather than refused, because the declaration is still
1507/// worth writing down today — the bot answers on the web and the lane arrives with slice 3.
1508pub const BOT_ADAPTERS: &[&str] = &[];
1509
1510/// `[context]`: how a request that no longer fits is shortened. The head (first turn) and
1511/// the tail (newest turns) stay verbatim; what pays is the middle.
1512#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1513#[serde(default)]
1514pub struct ContextPolicyConfig {
1515    /// Share of the model's window at which a request is compacted, e.g. `0.85`. `0` turns the
1516    /// threshold off, which leaves only an explicit `provider.context_budget_tokens` as a rail.
1517    pub compact_at: f64,
1518    /// Turns kept verbatim at the tail. `0` is read as `1`: the newest turn is never dropped.
1519    pub protect_last_n: usize,
1520    /// Ask one model one bounded question about *why* the dropped turns went the way they did,
1521    /// and take its answer only if every name in it appears in the digest it was written from.
1522    /// Off by default: it is the one part of compaction that spends a provider request.
1523    pub judge: bool,
1524    /// How long that one call may take before the deterministic handoff ships without it.
1525    pub judge_timeout_secs: u64,
1526    /// The window to assume when the endpoint advertises none (`/props`, `/v1/models`). `0`
1527    /// means assume nothing: a request is never shortened on a guessed window.
1528    pub window_tokens: usize,
1529    /// Hard cap, in characters, on the compiled handoff that stands in for the dropped middle.
1530    /// A handoff that grows to fill the window would defeat the point of compacting it.
1531    pub handoff_chars: usize,
1532}
1533
1534impl Default for ContextPolicyConfig {
1535    fn default() -> Self {
1536        Self {
1537            compact_at: 0.85,
1538            protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
1539            judge: true,
1540            judge_timeout_secs: 20,
1541            window_tokens: 0,
1542            handoff_chars: 6_000,
1543        }
1544    }
1545}
1546
1547impl ContextPolicyConfig {
1548    /// The budget this policy derives from a window, or 0 when the policy is off.
1549    pub fn budget_for(&self, window_tokens: usize) -> usize {
1550        if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
1551            return 0;
1552        }
1553        (window_tokens as f64 * self.compact_at) as usize
1554    }
1555
1556    /// `compact_at` is a share of a window, so anything outside (0, 1] is a mistake worth
1557    /// naming rather than a silently useless rail.
1558    pub fn validate(&self) -> Result<()> {
1559        if !(0.0..=1.0).contains(&self.compact_at) {
1560            return Err(Error::Config(format!(
1561                "context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
1562                 turn the threshold off",
1563                self.compact_at
1564            )));
1565        }
1566        if self.handoff_chars < 200 {
1567            return Err(Error::Config(format!(
1568                "context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
1569                 and 6000 is the default",
1570                self.handoff_chars
1571            )));
1572        }
1573        Ok(())
1574    }
1575}
1576
1577/// `[user]`: the user model and the agent's memory file.
1578#[derive(Debug, Clone, Serialize, Deserialize)]
1579#[serde(default)]
1580pub struct UserConfig {
1581    /// The user model, relative to this profile's config directory unless absolute.
1582    pub file: String,
1583    /// The agent's memory file, same resolution.
1584    pub memory_file: String,
1585    /// Ceiling for `MEMORY.md` in characters. The `memory` tool refuses past this rather than
1586    /// silently overwriting what is already there.
1587    pub memory_budget_chars: usize,
1588}
1589
1590impl Default for UserConfig {
1591    fn default() -> Self {
1592        Self {
1593            file: "USER.md".into(),
1594            memory_file: "MEMORY.md".into(),
1595            memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
1596        }
1597    }
1598}
1599
1600/// `[skills]`: how much of the prompt the skills index may take.
1601///
1602/// One field, because one thing reads it. Where skills are searched is fixed by the layout
1603/// (shared, profile, workspace, plugins), and a skill is off by being absent; a `dirs` or
1604/// `enabled` key would be a setting nothing consumes.
1605/// `[vision]`: what happens to a picture on a turn (`#346`).
1606#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1607#[serde(default)]
1608pub struct VisionConfig {
1609    /// `native`, `text` or `auto`. The default is `auto`: a model that declares vision gets the
1610    /// bytes, a model that does not gets a description instead.
1611    #[serde(default)]
1612    pub mode: VisionMode,
1613    /// The route that describes pictures, for `text` and for `auto`'s fallback. Empty means there
1614    /// is none, which makes `text` a refusal rather than a silent no-op.
1615    #[serde(default)]
1616    pub route: String,
1617    /// Let a description leave this machine. Off by default: a screenshot is the most private
1618    /// thing this agent touches, and "it went to an API once" cannot be undone by reading a log.
1619    #[serde(default)]
1620    pub allow_cloud: bool,
1621}
1622
1623/// The three modes, spelled in the file the way a person would say them.
1624#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1625#[serde(rename_all = "lowercase")]
1626pub enum VisionMode {
1627    /// The turn's own model sees the picture, or the attach is refused.
1628    Native,
1629    /// The picture is described by `[vision] route` and the turn model reads the description.
1630    Text,
1631    /// Native when the turn model declares vision, a description otherwise.
1632    #[default]
1633    Auto,
1634}
1635
1636#[derive(Debug, Clone, Serialize, Deserialize)]
1637#[serde(default)]
1638pub struct SkillsConfig {
1639    /// Ceiling for the index in the system prompt, in characters. Entries that do not fit are
1640    /// left out and named in `eclipse context show`; 0 = no cap.
1641    pub index_budget_chars: usize,
1642}
1643
1644impl Default for SkillsConfig {
1645    fn default() -> Self {
1646        Self {
1647            index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
1648        }
1649    }
1650}
1651
1652/// `[plugins]`: where plugins live and which ones may load.
1653#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1654#[serde(default)]
1655pub struct PluginsConfig {
1656    /// Root of the shared plugin directory (default `<config_dir>/plugins`). A profile's
1657    /// own `plugins/` directory is always searched first.
1658    pub dir: Option<PathBuf>,
1659    /// Allowlist. A plugin that is not listed is not loaded; an empty list loads none.
1660    pub enabled: Vec<String>,
1661    /// Default ceiling for one MCP server call, for `[[mcp]]` entries that state no
1662    /// `timeout_secs` of their own. Clamped to 1–600 s like any plugin timeout.
1663    pub mcp_timeout_secs: Option<u64>,
1664}
1665
1666impl Config {
1667    /// Load from `explicit` (must exist) or the default path (optional), then apply
1668    /// environment overrides, using the real process environment.
1669    pub fn load(explicit: Option<&Path>) -> Result<Config> {
1670        Self::load_with(explicit, &process_env)
1671    }
1672
1673    pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
1674        Self::load_with_profile(explicit, None, env)
1675    }
1676
1677    /// Load the base config, then the profile's overlay (`profiles/<name>/config.toml`, if it
1678    /// exists) on top of it, then environment overrides. Keys the overlay does not mention
1679    /// keep the base value; a key it does mention replaces it (tables are merged, so a
1680    /// profile can change one provider field without restating the rest).
1681    ///
1682    /// The profile also comes from `ECLIPSE_PROFILE`; an explicit argument wins. The name
1683    /// `default` is the default profile: it may still have an overlay and its own plugins,
1684    /// but its state lives in the plain state directory.
1685    pub fn load_with_profile(
1686        explicit: Option<&Path>,
1687        profile: Option<&str>,
1688        env: EnvFn,
1689    ) -> Result<Config> {
1690        let profile = profile
1691            .map(str::to_string)
1692            .or_else(|| env("ECLIPSE_PROFILE"))
1693            .filter(|p| !p.trim().is_empty())
1694            // `default` is the base config, not a profile with a directory of its own. `state_dir_for`
1695            // and `Where` already read it that way while `context_dir` and this loader did not, so
1696            // `--profile default`, `ECLIPSE_PROFILE=default` and `[web] default_profile = "default"`
1697            // detached memory and scripts into `profiles/default/` and left state in the root — one
1698            // install split across two directories (#544).
1699            .filter(|p| p != "default");
1700        if let Some(name) = &profile {
1701            validate_profile_name(name)?;
1702        }
1703        // `.env` is read before the TOML is parsed, because the TOML can reference it:
1704        // `api_key = "${OPENAI_API_KEY}"` needs the value to exist by the time it is resolved.
1705        let dotenv = Dotenv::load(env, profile.as_deref())?;
1706        // One lookup for the whole load: the real environment wins, `.env` fills the gaps — and an
1707        // empty `.env` value is a gap, not an answer. `process_env`, `${VAR}` interpolation and
1708        // `pin_route` all treat empty as absent; a raw `.env` value was the one layer that did not,
1709        // so a half-typed `ECLIPSE_API_KEY=` blanked the key the file already had and requests went
1710        // out unauthenticated while looking like a server problem.
1711        let lookup = |k: &str| {
1712            env(k).or_else(|| {
1713                dotenv
1714                    .values
1715                    .get(k)
1716                    .filter(|v| !v.is_empty())
1717                    .map(String::as_str)
1718                    .map(str::to_string)
1719            })
1720        };
1721        let lookup: EnvFn<'_> = &lookup;
1722
1723        let base_path = match explicit {
1724            Some(p) => Some(p.to_path_buf()),
1725            None => config_path(env).filter(|p| p.exists()),
1726        };
1727        // The file a `[hooks]` mistake is blamed on: the overlay when the profile has one.
1728        let mut hooks_path = base_path.clone();
1729        let mut value = match &base_path {
1730            Some(p) => {
1731                let mut parsed = read_toml(p)?;
1732                crate::interpolate::in_value(&mut parsed, p, lookup)?;
1733                parsed
1734            }
1735            None => toml::Value::try_from(Config::default())
1736                .map_err(|e| Error::Config(e.to_string()))?,
1737        };
1738        if let Some(name) = &profile {
1739            if let Some(dir) = profile_dir(env, name) {
1740                let overlay = dir.join("config.toml");
1741                if overlay.exists() {
1742                    let mut over = read_toml(&overlay)?;
1743                    // The profile's own `.env` is already in `lookup`, so a `${VAR}` here can
1744                    // refer to a secret only that profile has.
1745                    crate::interpolate::in_value(&mut over, &overlay, lookup)?;
1746                    if over.get("hooks").is_some() {
1747                        hooks_path = Some(overlay.clone());
1748                    }
1749                    merge_toml(&mut value, over);
1750                }
1751            }
1752        }
1753        let mut cfg: Config = value
1754            .try_into()
1755            .map_err(|e: toml::de::Error| Error::Parse {
1756                path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1757                message: e.to_string(),
1758            })?;
1759        cfg.profile = profile;
1760        cfg.apply_env(lookup);
1761        cfg.dotenv = dotenv;
1762        // At load, so a typo in the route table is the first thing said and not the thing a
1763        // run trips over once it has already started talking to a server.
1764        cfg.validate_routes()?;
1765        cfg.context.validate()?;
1766        // `#509`: a bot name is parsed back out of `origin` and spelled into a URL, so a name
1767        // that cannot survive either is a startup error rather than a tab that never lists it.
1768        cfg.validate_bots()?;
1769        crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
1770            path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1771            message,
1772        })?;
1773        Ok(cfg)
1774    }
1775
1776    /// The profile name in effect, `default` when none was selected.
1777    pub fn profile_name(&self) -> &str {
1778        self.profile.as_deref().unwrap_or("default")
1779    }
1780
1781    /// This profile's state directory (sessions, REPL history).
1782    pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
1783        state_dir_for(env, self.profile.as_deref())
1784            .ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
1785    }
1786
1787    /// Where plugins are looked for, in order: this profile's own `plugins/` directory
1788    /// first, then the shared one (`[plugins] dir`, else `<config_dir>/plugins`). A profile
1789    /// copy of a plugin shadows the shared copy.
1790    pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
1791        let mut out = Vec::new();
1792        if let Some(name) = &self.profile {
1793            if let Some(dir) = profile_dir(env, name) {
1794                out.push(dir.join("plugins"));
1795            }
1796        }
1797        let shared = match &self.plugins.dir {
1798            Some(p) => expand_tilde(p, env),
1799            None => match config_dir(env) {
1800                Some(d) => d.join("plugins"),
1801                None => return out,
1802            },
1803        };
1804        if !out.contains(&shared) {
1805            out.push(shared);
1806        }
1807        out
1808    }
1809
1810    pub fn from_file(path: &Path) -> Result<Config> {
1811        let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
1812        Self::from_toml_str(&text).map_err(|message| Error::Parse {
1813            path: path.to_path_buf(),
1814            message,
1815        })
1816    }
1817
1818    pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
1819        toml::from_str(text).map_err(|e| e.to_string())
1820    }
1821
1822    /// `ECLIPSE_BASE_URL`, `ECLIPSE_API_KEY`, `ECLIPSE_MODEL`.
1823    ///
1824    /// These describe `[provider]`, the `default` route, and nothing else: one variable cannot
1825    /// sensibly be the key for every route in a chain. A named route takes its key from its
1826    /// own `api_key_env`.
1827    pub fn apply_env(&mut self, env: EnvFn) {
1828        // Only when `[provider]` is in use, or when the file has no routes at all. All three
1829        // variables describe the `default` route, so applying one to a routes-only config invented
1830        // a `default` route that its `fallback` does not name, and `validate_routes` then refused a
1831        // file that loads fine from a clean shell (#543). `ECLIPSE_API_KEY` was already guarded for
1832        // exactly this reason; the other two were not.
1833        if self.provider.route.is_empty() || self.provider.declares_connection() {
1834            if let Some(v) = env("ECLIPSE_BASE_URL") {
1835                self.provider.base_url = v;
1836            }
1837            if let Some(v) = env("ECLIPSE_MODEL") {
1838                self.provider.model = v;
1839            }
1840            apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
1841        }
1842        for route in &mut self.provider.route {
1843            apply_key_env(&mut route.config, env, None);
1844        }
1845    }
1846
1847    /// Serialise to TOML with every secret-looking value replaced, safe to print.
1848    ///
1849    /// Redaction follows the key name rather than a list of known fields, so a new setting
1850    /// called `api_token` is covered the day it is added instead of the day someone
1851    /// remembers to add it here.
1852    pub fn to_toml_redacted(&self) -> Result<String> {
1853        let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
1854        redact(&mut value);
1855        toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
1856    }
1857
1858    /// Fail early, with an actionable message, if the provider is not configured.
1859    pub fn require_provider(&self) -> Result<()> {
1860        self.chain().map(|_| ())
1861    }
1862
1863    /// The routes the file declares, `default` first when `[provider]` is in use.
1864    ///
1865    /// With no routes at all `default` is always listed, so a bare config still has one
1866    /// route and says what is wrong with it rather than that it has none.
1867    pub fn declared_routes(&self) -> Vec<NamedRoute> {
1868        let mut out = Vec::new();
1869        if self.provider.route.is_empty() || self.provider.declares_connection() {
1870            out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
1871        }
1872        out.extend(self.provider.route.iter().map(|r| {
1873            NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
1874        }));
1875        out
1876    }
1877
1878    /// The routes that exist, for a sentence that has to name them.
1879    pub fn route_names(&self) -> String {
1880        let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1881        if names.is_empty() {
1882            "none".to_string()
1883        } else {
1884            names.join(", ")
1885        }
1886    }
1887
1888    /// Check the route table: every rule is something a run would otherwise find out halfway
1889    /// through, and each message names the route or the key at fault.
1890    ///
1891    /// `[provider]` itself is not checked here — whether `base_url` and `model` are set is
1892    /// asked when a run needs it ([`Config::chain`]), which is why `config show` and
1893    /// `config init` work on a half-written file.
1894    pub fn validate_routes(&self) -> Result<()> {
1895        let p = &self.provider;
1896        let mut seen: Vec<&str> = Vec::new();
1897        for (i, r) in p.route.iter().enumerate() {
1898            let name = r.name.trim();
1899            if name.is_empty() {
1900                return Err(Error::Config(format!(
1901                    "provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
1902                    i + 1
1903                )));
1904            }
1905            if seen.contains(&name) {
1906                return Err(Error::Config(format!(
1907                    "two routes are named `{name}`; route names must be unique"
1908                )));
1909            }
1910            seen.push(name);
1911            if name == DEFAULT_ROUTE && p.declares_connection() {
1912                return Err(Error::Config(format!(
1913                    "a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
1914                     route of that name; rename the route, or move its settings out of [provider]"
1915                )));
1916            }
1917            if r.config.fallback.is_some()
1918                || r.config.aux.is_some()
1919                || r.config.delegate.is_some()
1920                || !r.config.route.is_empty()
1921            {
1922                return Err(Error::Config(format!(
1923                    "route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
1924                     belong directly under [provider], not inside a route"
1925                )));
1926            }
1927            if r.config.base_url.trim().is_empty() {
1928                return Err(Error::Config(format!(
1929                    "route `{name}` has no base_url; a route is a complete provider \
1930                     configuration and does not inherit from [provider]"
1931                )));
1932            }
1933            if r.config.model.trim().is_empty() {
1934                return Err(Error::Config(format!(
1935                    "route `{name}` has no model; a route is a complete provider \
1936                     configuration and does not inherit from [provider]"
1937                )));
1938            }
1939        }
1940        if let Some(fallback) = &p.fallback {
1941            if fallback.is_empty() {
1942                return Err(Error::Config(
1943                    "provider.fallback is empty; name the routes to try in order, or remove the \
1944                     key to use `default` alone"
1945                        .into(),
1946                ));
1947            }
1948            let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1949            let mut listed: Vec<&str> = Vec::new();
1950            for name in fallback {
1951                if !known.contains(name) {
1952                    return Err(Error::Config(format!(
1953                        "provider.fallback names `{name}`, which is not a route. Routes that \
1954                         exist: {}",
1955                        self.route_names()
1956                    )));
1957                }
1958                if listed.contains(&name.as_str()) {
1959                    return Err(Error::Config(format!(
1960                        "provider.fallback lists `{name}` twice; each route is tried at most \
1961                         once per run"
1962                    )));
1963                }
1964                listed.push(name);
1965            }
1966            // `[provider]` set a connection key, so it *is* the route `default` — and `fallback`
1967            // is the whole chain, without it. The endpoint the user wrote down would never be
1968            // called. Refused rather than run: both ways out are one word, and a chain that
1969            // quietly omits the primary is the kind of thing found months later from a bill.
1970            if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
1971                return Err(Error::Config(
1972                    "`[provider]` sets a connection, but provider.fallback is the whole chain \
1973                     and does not list `default`, so that endpoint would never be called. Put \
1974                     `default` first in `fallback`, or move the connection keys into a route \
1975                     and leave `[provider]` to `fallback` alone"
1976                        .into(),
1977                ));
1978            }
1979        }
1980        if let Some(aux) = &p.aux {
1981            if aux.trim().is_empty() {
1982                return Err(Error::Config(
1983                    "provider.aux is empty; name the route that does housekeeping, or remove \
1984                     the key to use the route the run is on"
1985                        .into(),
1986                ));
1987            }
1988            if !self.declared_routes().iter().any(|r| &r.name == aux) {
1989                return Err(Error::Config(format!(
1990                    "provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
1991                    self.route_names()
1992                )));
1993            }
1994        }
1995        if let Some(delegate) = &p.delegate {
1996            if delegate.trim().is_empty() {
1997                return Err(Error::Config(
1998                    "provider.delegate is empty; name the route subagents run on, or remove \
1999                     the key to use the route the run is on"
2000                        .into(),
2001                ));
2002            }
2003            if !self.declared_routes().iter().any(|r| &r.name == delegate) {
2004                return Err(Error::Config(format!(
2005                    "provider.delegate names `{delegate}`, which is not a route. Routes that \
2006                     exist: {}",
2007                    self.route_names()
2008                )));
2009            }
2010        }
2011        // `[vision] route` is checked here for the same reason `aux` is: a name that matches no
2012        // route would otherwise be a picture described by the fallback route the run happens to be
2013        // on, which is a picture sent somewhere nobody chose (`#346`).
2014        let vision_route = self.vision.route.trim();
2015        if !vision_route.is_empty()
2016            && !self
2017                .declared_routes()
2018                .iter()
2019                .any(|r| r.name == vision_route)
2020        {
2021            return Err(Error::Config(format!(
2022                "vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
2023                self.route_names()
2024            )));
2025        }
2026        Ok(())
2027    }
2028
2029    /// Pin this configuration to a route, or leave it unpinned.
2030    ///
2031    /// `flag` is `--route`; without it `ECLIPSE_ROUTE` is read from the environment and then
2032    /// from the `.env` chain, the same layering every other `ECLIPSE_*` setting has. An unknown
2033    /// name is an error that lists the routes that exist, here rather than after a run starts.
2034    pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
2035        let wanted = match flag {
2036            Some(name) if name.trim().is_empty() => {
2037                return Err(Error::Config(
2038                    "--route needs a route name; `eclipse config show` lists them".into(),
2039                ))
2040            }
2041            Some(name) => Some(name.trim().to_string()),
2042            None => env("ECLIPSE_ROUTE")
2043                .or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
2044                .map(|v| v.trim().to_string())
2045                .filter(|v| !v.is_empty()),
2046        };
2047        if let Some(name) = &wanted {
2048            if !self.declared_routes().iter().any(|r| &r.name == name) {
2049                return Err(self.unknown_route(name));
2050            }
2051        }
2052        self.route_pin = wanted;
2053        Ok(())
2054    }
2055
2056    fn unknown_route(&self, name: &str) -> Error {
2057        Error::Config(format!(
2058            "unknown route `{name}`. Routes that exist: {}",
2059            self.route_names()
2060        ))
2061    }
2062
2063    /// The routes a run will use, in order, checked.
2064    ///
2065    /// A pinned run gets exactly one route and [`ChainSource::Pinned`]: pinning means pinned,
2066    /// and nothing downstream may fall back from it. Otherwise it is `[provider] fallback`, or
2067    /// `default` alone, which is every config that existed before routes did.
2068    pub fn chain(&self) -> Result<Chain> {
2069        self.validate_routes()?;
2070        let all = self.declared_routes();
2071        let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
2072        let (routes, source) = if let Some(pin) = &self.route_pin {
2073            let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
2074            (vec![route], ChainSource::Pinned)
2075        } else if let Some(fallback) = &self.provider.fallback {
2076            // validate_routes proved every name is declared.
2077            let routes = fallback.iter().filter_map(|n| find(n)).collect();
2078            (routes, ChainSource::Fallback)
2079        } else if self.provider.declares_connection() || self.provider.route.is_empty() {
2080            (
2081                vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
2082                ChainSource::Default,
2083            )
2084        } else {
2085            return Err(Error::Config(format!(
2086                "routes are declared but nothing says which to use: set `[provider] fallback = \
2087                 [...]`, or pass --route NAME. Routes that exist: {}",
2088                self.route_names()
2089            )));
2090        };
2091        for route in &routes {
2092            route.require_endpoint(source)?;
2093        }
2094        // A pin wins over the role routes. `--route local` is what you say when the text must
2095        // not leave that server; a `[provider] aux = "cheap"` or `delegate = "big"` that ignored
2096        // it would be exactly the leak the pin was meant to close. Recorded as the role routes
2097        // being unset, with `ChainSource::Pinned` saying why.
2098        let pinned = source == ChainSource::Pinned;
2099        let only = routes.first().cloned();
2100        let (aux, delegate) = if pinned {
2101            (only.clone(), only)
2102        } else {
2103            (
2104                self.provider.aux.as_deref().and_then(find),
2105                self.provider.delegate.as_deref().and_then(find),
2106            )
2107        };
2108        if let Some(aux) = &aux {
2109            aux.require_endpoint(source)?;
2110        }
2111        if let Some(delegate) = &delegate {
2112            delegate.require_endpoint(source)?;
2113        }
2114        Ok(Chain {
2115            routes,
2116            source,
2117            aux,
2118            delegate,
2119        })
2120    }
2121
2122    pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
2123        if let Some(d) = &self.sessions.dir {
2124            return Ok(expand_tilde(d, env));
2125        }
2126        Ok(self.state_dir(env)?.join("sessions"))
2127    }
2128
2129    /// `[bots.<name>]`: a bot name is half of a session's `origin` (`bot:<name>`) and a segment of
2130    /// a dashboard URL, so it is checked once at load rather than at the first request that
2131    /// spells it — a name with a `:` in it would make its own sessions unparseable.
2132    ///
2133    /// Lowercase letters, digits, `-` and `_`, one to thirty-two of them: the same rule a profile
2134    /// name follows, because it is the same kind of thing (a word a person types, and a path).
2135    pub fn validate_bots(&self) -> Result<()> {
2136        for name in self.bots.keys() {
2137            let ok = !name.is_empty()
2138                && name.len() <= 32
2139                && name
2140                    .chars()
2141                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
2142            if !ok {
2143                return Err(Error::Config(format!(
2144                    "bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
2145                     32 of them — it becomes part of a session's `origin` and a URL"
2146                )));
2147            }
2148        }
2149        Ok(())
2150    }
2151
2152    /// A path from a bot's declaration (`instructions`, `memory`): `~` expanded, and a relative
2153    /// path taken from this profile's own directory, the same rule `[user] file` follows.
2154    pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
2155        let path = expand_tilde(Path::new(path), env);
2156        if path.is_absolute() {
2157            Some(path)
2158        } else {
2159            self.context_dir(env).map(|dir| dir.join(path))
2160        }
2161    }
2162
2163    /// Where a bot's `MEMORY.md` lives: its declaration, else `<profile>/memory/bots/<name>/` with
2164    /// the human's own file name. Always a file of its own — the one thing a bot must not share
2165    /// with the person it answers.
2166    pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
2167        match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
2168            Some(m) => self.bot_file(env, m),
2169            None => {
2170                // The file *name*, never the configured path: `[user] memory_file` may be absolute
2171                // and `Path::join` discards the prefix for one, which handed every bot the
2172                // operator's own `MEMORY.md` — the one thing this function exists to prevent
2173                // (#542).
2174                let file = std::path::Path::new(&self.user.memory_file)
2175                    .file_name()
2176                    .map(PathBuf::from)
2177                    .unwrap_or_else(|| PathBuf::from("MEMORY.md"));
2178                self.memory_dir(env)
2179                    .map(|dir| dir.join("bots").join(name).join(file))
2180            }
2181        }
2182    }
2183
2184    /// Where attached pictures are kept (`#499`): the override, else `<state_dir>/attachments`.
2185    ///
2186    /// `None` when neither can be worked out — no `HOME`, no `ECLIPSE_HOME` and no override — which
2187    /// the caller reports rather than guessing a directory the agent would write to.
2188    pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
2189        if let Some(dir) = &self.attachments.dir {
2190            return Some(expand_tilde(dir, env));
2191        }
2192        self.state_dir(env).ok().map(|d| d.join("attachments"))
2193    }
2194
2195    /// The four answers a person needs when a profile surprises them: which profile, from which
2196    /// file, under which home, writing sessions where.
2197    ///
2198    /// Every one of them comes from the function that already answers it — `home_root`,
2199    /// `config_path`, `sessions_dir` — so `/profile`, `/settings` and `eclipse doctor` cannot
2200    /// disagree the first time `[sessions] dir` or `ECLIPSE_HOME` moves. `loaded` is the file the
2201    /// caller actually read: `--config` may point outside the root, and naming the default path
2202    /// while running from another one is exactly the mistake this reports.
2203    pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
2204        let overlay = self
2205            .profile
2206            .as_deref()
2207            .filter(|name| *name != "default")
2208            .and_then(|name| profile_dir(env, name))
2209            .map(|dir| dir.join("config.toml"))
2210            .filter(|path| path.exists());
2211        Where {
2212            profile: self.profile.clone(),
2213            config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
2214            overlay,
2215            home: home_root(env),
2216            sessions: self.sessions_dir(env).ok(),
2217        }
2218    }
2219
2220    /// The directory this profile's own files live in: `<config>/profiles/<name>` for a named
2221    /// profile, the config directory itself for the default one.
2222    pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2223        match self.profile.as_deref() {
2224            // The backstop for a `Config` built without going through the loader: `default` means
2225            // the base config here too, which is what [`state_dir_for`] already says (#544).
2226            Some(name) if name != "default" => profile_dir(env, name),
2227            _ => config_path(env)
2228                .and_then(|p| p.parent().map(Path::to_path_buf))
2229                .or_else(|| config_dir(env)),
2230        }
2231    }
2232
2233    /// Where this profile's scripts live: `scripts/` under [`Self::context_dir`], so the
2234    /// profile's own directory when a profile is in effect and the shared one otherwise.
2235    /// Nothing falls back from one to the other — a profile with no scripts has none, which is
2236    /// the same rule the profile's `MEMORY.md` follows.
2237    ///
2238    /// Always absolute: the path is handed to scripts in `ECLIPSE_SCRIPTS_DIR` and compared
2239    /// against the paths a model writes, and `--config some/relative/config.toml` would
2240    /// otherwise make it mean something different from one working directory to the next.
2241    pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
2242        let dir = self.context_dir(env)?.join("scripts");
2243        if dir.is_absolute() {
2244            return Some(dir);
2245        }
2246        std::env::current_dir().ok().map(|cwd| cwd.join(dir))
2247    }
2248
2249    /// Where the agent's memory lives: `memory/` under this profile's directory. `AGENT.md`,
2250    /// `USER.md` and `MEMORY.md` all sit here, because "what the agent has been told" is one
2251    /// thing and answering "where is it?" with three directories is how you end up with a
2252    /// `SOUL.md` nobody remembers writing.
2253    ///
2254    /// `[user] file` and `[user] memory_file` may still be absolute, and an absolute path wins —
2255    /// `Path::join` refuses to descend into one.
2256    pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
2257        self.context_dir(env).map(|d| d.join("memory"))
2258    }
2259
2260    /// Where the global `AGENT.md` lives (the config directory, whatever `--config` says).
2261    pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2262        config_path(env)
2263            .and_then(|p| p.parent().map(Path::to_path_buf))
2264            .or_else(|| config_dir(env))
2265    }
2266
2267    pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
2268        home_dir(env)
2269    }
2270
2271    pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
2272        match &self.tools.workspace_root {
2273            Some(p) => expand_tilde(p, env),
2274            None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
2275        }
2276    }
2277}
2278
2279/// Where this process is running from — the four answers [`Config::where_am_i`] fills in.
2280///
2281/// One struct rather than four calls at each site, because four answers worked out in four places
2282/// is how `/profile` and `eclipse doctor` come to name different session directories the first
2283/// time `[sessions] dir` moves.
2284#[derive(Debug, Clone, Default, PartialEq, Eq)]
2285pub struct Where {
2286    /// `None` for the default profile: `default` is not a directory, it is the absence of one.
2287    pub profile: Option<String>,
2288    /// The base file this process read — `--config`, else the default path. `None` when it was
2289    /// started without one. A profile is an overlay *on top of* this, not a replacement.
2290    pub config: Option<PathBuf>,
2291    /// The profile's own `config.toml`, when it has one. Read after the base, so it wins.
2292    pub overlay: Option<PathBuf>,
2293    /// The root everything lives under: `~/.eclipse`, or `$ECLIPSE_HOME`.
2294    pub home: Option<PathBuf>,
2295    /// `[sessions] dir`, else `<state>/sessions`.
2296    pub sessions: Option<PathBuf>,
2297}
2298
2299impl Where {
2300    /// The name to print: `default` when none was chosen.
2301    pub fn name(&self) -> &str {
2302        self.profile.as_deref().unwrap_or("default")
2303    }
2304
2305    /// Whether this is the default profile — the one whose files sit in the root itself rather
2306    /// than under `profiles/<name>`.
2307    pub fn is_default(&self) -> bool {
2308        matches!(self.profile.as_deref(), None | Some("default"))
2309    }
2310}
2311
2312/// Read and parse one TOML file, with an error that names it.
2313fn read_toml(path: &Path) -> Result<toml::Value> {
2314    let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
2315    toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
2316        path: path.to_path_buf(),
2317        message: message.to_string(),
2318    })
2319}
2320
2321/// Deep-merge `over` into `base`: tables merge key by key, anything else replaces.
2322fn merge_toml(base: &mut toml::Value, over: toml::Value) {
2323    match (base, over) {
2324        (toml::Value::Table(base), toml::Value::Table(over)) => {
2325            for (key, value) in over {
2326                match base.get_mut(&key) {
2327                    Some(slot) => merge_toml(slot, value),
2328                    None => {
2329                        base.insert(key, value);
2330                    }
2331                }
2332            }
2333        }
2334        (slot, over) => *slot = over,
2335    }
2336}
2337
2338/// Replace secret-looking values with `<redacted>`.
2339fn redact(value: &mut toml::Value) {
2340    match value {
2341        toml::Value::Table(table) => {
2342            for (key, slot) in table.iter_mut() {
2343                if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
2344                    *slot = toml::Value::String("<redacted>".into());
2345                    continue;
2346                }
2347                if is_url_key(key) {
2348                    if let toml::Value::String(url) = slot {
2349                        if let Some(clean) = redact_url(url) {
2350                            *slot = toml::Value::String(clean);
2351                            continue;
2352                        }
2353                    }
2354                }
2355                redact(slot);
2356            }
2357        }
2358        toml::Value::Array(items) => items.iter_mut().for_each(redact),
2359        _ => {}
2360    }
2361}
2362
2363/// A key that holds a secret. `_env` keys are the *name* of a variable, not its value, so
2364/// they are printed as they are — hiding `api_key_env = "MY_KEY"` would make the output
2365/// less useful without making it safer.
2366pub(crate) fn is_secret_key(key: &str) -> bool {
2367    let k = key.to_ascii_lowercase();
2368    if k.ends_with("_env") {
2369        return false;
2370    }
2371    // A unit suffix says "a count of these", not "one of these": `window_tokens` is how big the
2372    // context window is, and redacting it hid a number a person needs to set.
2373    const COUNTS: &[&str] = &[
2374        "_tokens",
2375        "_chars",
2376        "_secs",
2377        "_ms",
2378        "_count",
2379        "_size",
2380        "_hours",
2381        "_days",
2382        "_bytes",
2383        "_iterations",
2384        "_call",
2385    ];
2386    if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
2387        return false;
2388    }
2389    k == "api_key"
2390        || k.ends_with("_key")
2391        || k.contains("token")
2392        || k.contains("secret")
2393        || k.contains("password")
2394}
2395
2396/// A key whose value is a URL the user wrote. Those are printed as they are — a base URL is how you
2397/// check what you configured — but a URL can carry a secret of its own, so its userinfo and its
2398/// secret-named query parameters are scrubbed first.
2399///
2400/// A bare `url` counts (`#539`): an `[[mcp]]` entry keeps its endpoint there, so the key was skipped
2401/// and `https://user:pw@host/mcp?token=…` went into a printout documented as safe to paste into an
2402/// issue. Nothing is rewritten unless there is a credential in it — `redact_url` answers `None` for a
2403/// plain URL — so the entry reads the same as before when there is nothing to hide.
2404fn is_url_key(key: &str) -> bool {
2405    let k = key.to_ascii_lowercase();
2406    k.ends_with("_url") || k == "url" || k == "remote" || k == "releases"
2407}
2408
2409/// A URL with its secrets taken out, or `None` when there was nothing to take out.
2410///
2411/// Two shapes, both legitimate and both printed verbatim before this existed: a basic-auth gateway
2412/// (`https://user:pw@gw.internal/v1`) and a token in the query
2413/// (`https://mirror/releases?access_token=…`). The URL keeps its shape — scheme, host, path and the
2414/// *names* of its parameters — because that is what makes the printout useful.
2415pub(crate) fn redact_url(text: &str) -> Option<String> {
2416    let (body, fragment) = match text.split_once('#') {
2417        Some((b, f)) => (b, Some(f)),
2418        None => (text, None),
2419    };
2420    let (before_query, query) = match body.split_once('?') {
2421        Some((b, q)) => (b, Some(q)),
2422        None => (body, None),
2423    };
2424    let mut changed = false;
2425
2426    // `scheme://user:pass@host/path`: everything between `//` and the last `@` of the authority is
2427    // credentials. An `@` in the path is not one, which is why this stops at the first `/`.
2428    let head = match before_query.find("://") {
2429        Some(scheme_end) => {
2430            let start = scheme_end + 3;
2431            let rest = &before_query[start..];
2432            let authority_end = rest.find('/').unwrap_or(rest.len());
2433            match rest[..authority_end].rfind('@') {
2434                Some(at) => {
2435                    changed = true;
2436                    format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
2437                }
2438                None => before_query.to_string(),
2439            }
2440        }
2441        None => before_query.to_string(),
2442    };
2443
2444    let query = query.map(|q| {
2445        let pairs: Vec<String> = q
2446            .split('&')
2447            .map(|pair| {
2448                let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
2449                if !name.is_empty() && is_secret_key(name) {
2450                    changed = true;
2451                    format!("{name}=<redacted>")
2452                } else {
2453                    pair.to_string()
2454                }
2455            })
2456            .collect();
2457        pairs.join("&")
2458    });
2459
2460    if !changed {
2461        return None;
2462    }
2463    let mut out = head;
2464    if let Some(q) = query {
2465        out.push('?');
2466        out.push_str(&q);
2467    }
2468    if let Some(f) = fragment {
2469        out.push('#');
2470        out.push_str(f);
2471    }
2472    Some(out)
2473}
2474
2475/// The keys whose shipped spelling is not their Rust default.
2476///
2477/// The file is generated from [`Config::default()`], so everything a struct holds appears without
2478/// anyone maintaining a list — adding a field is enough. The exceptions are the `Option<String>`
2479/// keys, which serialise to nothing when unset and would then be the only settings a person could
2480/// not see. Each ships with the spelling the binary reads as "not in use":
2481///
2482/// - `""` for a path, a route, a profile name or an address nobody has chosen yet;
2483/// - `${VAR:-}` for the two that name a secret, so the value lives in `.env` and a missing
2484///   variable is "no secret" rather than a config that refuses to load. `${VAR}` without `:-`
2485///   is a load error naming the key, which is right for a value a config cannot work without and
2486///   wrong for one it can work without.
2487///
2488/// `reasoning_effort` is here for a different reason: its Rust default is `None` on purpose (an
2489/// undeclared backend must not be handed a field it may reject), while the level a fresh install
2490/// resolves is the shipped `medium`, and the file is where a person reads that.
2491const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
2492    ("provider", "api_key", "${OPENAI_API_KEY:-}"),
2493    ("provider", "api_key_env", ""),
2494    ("provider", "profile", ""),
2495    (
2496        "provider",
2497        "reasoning_effort",
2498        crate::reasoning::SHIPPED_DEFAULT,
2499    ),
2500    ("provider", "aux", ""),
2501    ("provider", "delegate", ""),
2502    ("agent", "output_schema", ""),
2503    ("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
2504    ("web", "default_profile", ""),
2505    ("update", "remote", ""),
2506    ("update", "releases", ""),
2507    // Not a placeholder: the struct default is `allow`, and the shipped file has asked since the
2508    // first install. A fresh install that writes files without a prompt would be a regression in
2509    // everything but the type system, so the stricter value is the one the file carries.
2510    ("tools", "write_file", "ask"),
2511    ("tools", "patch", "ask"),
2512];
2513
2514/// One entry of [`SHIPPED_SPELLING`] as TOML: quoted, escaped, and identical to what
2515/// `toml::Value::String` writes, so a spelling that contains `"` or `\` cannot break the file.
2516fn shipped_text(spelling: &str) -> String {
2517    toml::Value::String(spelling.to_string()).to_string()
2518}
2519
2520/// The order sections appear in the file: the ones a new install edits first, first.
2521const SECTION_ORDER: &[&str] = &[
2522    "provider",
2523    "agent",
2524    "tools",
2525    "flares",
2526    "sessions",
2527    "attachments",
2528    "context",
2529    "plugins",
2530    "cli",
2531    "web",
2532    "gateway",
2533    "update",
2534    "hooks",
2535    "user",
2536    "skills",
2537    "vision",
2538];
2539
2540/// The shipped `config.toml`: every setting this build reads, and no prose.
2541///
2542/// The file is for reading and editing — one key per line, in the section named after the thing it
2543/// configures, with nothing between the lines to scroll past. The explanation for a key is not
2544/// here: it is in the manual `eclipse config docs` renders from [`settings::about`], the same
2545/// string the settings window and `config explain` show. One description per key in the whole
2546/// product, so it cannot drift from the code.
2547///
2548/// Two kinds of line, and the difference is the convention:
2549///
2550/// - `key = value` — the setting is in use at that value. `""` and `[]` are how a key whose "off"
2551///   state is empty is written, and `""` reads back as "not set" ([`empty_is_none`]). A secret is
2552///   `"${VAR:-}"` so its value lives in `.env` and a missing variable means no secret.
2553/// - `# key =` — the setting is not in use, and *no* value could express that: a temperature, a
2554///   cap, a colour, an explicit boolean. TOML has no empty number, so absence is the spelling, and
2555///   a commented line is how the file still shows the key and where it goes. `config set` turns it
2556///   into a real line ([`settings::set_in_text`]).
2557///
2558/// Generated from the schema, never written by hand: `Config::default()` serialised, plus
2559/// [`settings::ABSENT_BY_DEFAULT`] for the keys whose only default is absence, plus
2560/// [`SHIPPED_SPELLING`]. A field added to a struct is in the next `config init` with no second
2561/// edit, and `the_starter_config_carries_every_setting_the_build_reads` asserts the file's keys and
2562/// the catalogue agree exactly, so neither can silently miss one.
2563pub fn starter_config() -> Result<String> {
2564    let defaults = toml::Value::try_from(Config::default())
2565        .map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
2566    let mut out = String::with_capacity(8 * 1024);
2567    out.push_str("# Every setting this build reads, and nothing else.\n");
2568    out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
2569    out.push_str("# A commented key is not in use; an empty value means the same.\n");
2570    out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
2571    for section in SECTION_ORDER {
2572        out.push_str(&format!("\n[{section}]\n"));
2573        let table = defaults.get(*section).and_then(toml::Value::as_table);
2574        let mut lines: Vec<(String, String)> = Vec::new();
2575        let mut nested: Vec<&str> = Vec::new();
2576        if let Some(table) = table {
2577            for (key, value) in table {
2578                match value {
2579                    toml::Value::Table(_) => nested.push(key.as_str()),
2580                    other => {
2581                        let shipped = SHIPPED_SPELLING
2582                            .iter()
2583                            .find(|(s, k, _)| s == section && k == key)
2584                            .map(|(_, _, spelling)| shipped_text(spelling));
2585                        lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
2586                    }
2587                }
2588            }
2589        }
2590        // Keys whose default is absence: visible, and set to nothing. A key the struct *does*
2591        // write is never doubled — the schema and the hand-written list cannot disagree here.
2592        for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
2593            if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
2594                let shipped = SHIPPED_SPELLING
2595                    .iter()
2596                    .find(|(s, k, _)| s == section && k == key)
2597                    .map(|(_, _, spelling)| shipped_text(spelling));
2598                lines.push(((*key).to_string(), shipped.unwrap_or_default()));
2599            }
2600        }
2601        lines.sort();
2602        for (key, text) in lines {
2603            if text.is_empty() {
2604                out.push_str(&format!("# {key} =\n"));
2605            } else {
2606                out.push_str(&format!("{key} = {text}\n"));
2607            }
2608        }
2609        // A hook's own options are a table, not a setting, and are written as one so the block is
2610        // copy-pasteable. `[hooks.<name>]` for a hook that is not in `order` is a parse error, so
2611        // this follows the serialised default exactly rather than adding anything.
2612        nested.sort();
2613        for key in nested {
2614            let Some(sub) = table.and_then(|t| t.get(key)) else {
2615                continue;
2616            };
2617            let mut wrapped = toml::map::Map::new();
2618            wrapped.insert(key.to_string(), sub.clone());
2619            if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
2620                out.push('\n');
2621                out.push_str(&text);
2622            }
2623        }
2624        // The hook that is on by default has no settings table in the default config (its options
2625        // are optional), and `order` has to name a hook this build has. Its block is written
2626        // empty, with each key it accepts named and commented: the one place a table's shape comes
2627        // from the hook's own declaration rather than from a hand-written section.
2628        if *section == "hooks" {
2629            let default_hooks = Config::default().hooks;
2630            for name in &default_hooks.order {
2631                if default_hooks.settings.contains_key(name) {
2632                    continue;
2633                }
2634                let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
2635                    continue;
2636                };
2637                out.push_str(&format!("\n[hooks.{name}]\n"));
2638                let mut keys = info.settings.to_vec();
2639                keys.sort_unstable();
2640                for key in keys {
2641                    out.push_str(&format!("# {key} =\n"));
2642                }
2643            }
2644        }
2645    }
2646    Ok(out)
2647}
2648
2649/// Every variable the shipped `.env` lists, in the order it lists them, with empty values.
2650///
2651/// Empty is the whole point: with [`Dotenv`] treating an empty assignment as absent — the same as
2652/// the line not being there — a file that names every variable and sets none of them behaves
2653/// exactly like a file with one line in it, and it is a directory of what can be set.
2654///
2655/// Only variables that are actually read from `.env` are here. `ECLIPSE_HOME`, `ECLIPSE_CONFIG` and
2656/// `ECLIPSE_PROFILE` are read to *find* the file, so a `.env` cannot set them ([`ENV_SHELL_ONLY`]),
2657/// and the rest are plumbing this tool puts in a child's environment ([`ENV_INTERNAL`]).
2658pub const ENV_TEMPLATE: &[&str] = &[
2659    "ECLIPSE_BASE_URL",
2660    "ECLIPSE_MODEL",
2661    "ECLIPSE_API_KEY",
2662    "ECLIPSE_REASONING_EFFORT",
2663    "ECLIPSE_ROUTE",
2664    "OPENAI_API_KEY",
2665    "ECLIPSE_WEB_AUTH_TOKEN",
2666    "ECLIPSE_WEB_USER",
2667    "ECLIPSE_WEB_PASSWORD_HASH",
2668];
2669
2670/// One line per variable, for the manual: what it is for.
2671///
2672/// The `.env` is shipped as a list of names and nothing else — a name with no explanation is a
2673/// puzzle, and the explanation does not belong in a secrets file. This table is the other half,
2674/// and [`every_classified_variable_has_a_description`] keeps it level with the three lists above.
2675pub const ENV_ABOUT: &[(&str, &str)] = &[
2676    ("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
2677    ("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
2678    ("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
2679    ("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
2680    ("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
2681    ("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
2682    ("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
2683    ("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
2684    ("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
2685    ("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
2686    ("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
2687    ("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
2688    ("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
2689    ("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
2690    ("ECLIPSE_ARGS_BYTES", "How big that JSON was, when it was too big to duplicate into `ECLIPSE_ARGS` (over 64 KiB); set by this tool"),
2691    ("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
2692    ("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
2693    ("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
2694    ("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
2695    ("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
2696];
2697
2698/// What one variable is for, or `""` — the same lookup shape as [`settings::about`].
2699pub fn env_about(name: &str) -> &'static str {
2700    ENV_ABOUT
2701        .iter()
2702        .find(|(n, _)| *n == name)
2703        .map(|(_, about)| *about)
2704        .unwrap_or("")
2705}
2706
2707/// Variables read before a `.env` is opened, or from the process environment only. Setting one of
2708/// these *inside* `.env` would be inert, which is worse than absent: it looks like a setting.
2709pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];
2710
2711/// Variables this tool sets in a child's environment (a plugin, an MCP server, a spawned tool
2712/// call). Nobody sets these by hand, and a value in `.env` would be overwritten anyway.
2713pub const ENV_INTERNAL: &[&str] = &[
2714    "ECLIPSE_BIN",
2715    "ECLIPSE_ARGS",
2716    "ECLIPSE_ARGS_BYTES",
2717    "ECLIPSE_TOOL",
2718    "ECLIPSE_TOOL_SOCKET",
2719    "ECLIPSE_WORKSPACE",
2720    "ECLIPSE_PLUGIN_DIR",
2721    "ECLIPSE_SCRIPTS_DIR",
2722];
2723
2724/// The shipped `.env`: every variable, nothing set, and the dashboard token already generated.
2725///
2726/// The token is the one value a first install cannot invent for you — the dashboard refuses to
2727/// start without it — so `config init` fills exactly that one line and leaves the rest empty.
2728pub fn starter_env(token: &str) -> String {
2729    let mut out = String::with_capacity(1024);
2730    out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
2731    out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
2732    for name in ENV_TEMPLATE {
2733        if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
2734            out.push_str(&format!("{name}={token}\n"));
2735        } else {
2736            out.push_str(&format!("{name}=\n"));
2737        }
2738    }
2739    out
2740}
2741
2742/// The file a named profile starts from: an overlay, not a whole config. Only the keys a
2743/// profile usually changes are here, uncommented examples included — a profile that restated
2744/// every default would pin them, and then a change to the base config would stop reaching it.
2745pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
2746# Examples are commented out on purpose — an empty value here *replaces* the base value.
2747
2748[provider]
2749# base_url = "http://127.0.0.1:8080/v1"
2750# model = "qwen3-coder:30b"
2751# profile = "llamacpp"
2752
2753[tools]
2754# shell = "ask"
2755"#;
2756
2757/// What `config init` did, so the caller can report it without re-deriving paths.
2758#[derive(Debug, Clone, PartialEq, Eq)]
2759pub struct InitReport {
2760    pub config: PathBuf,
2761    pub dotenv: PathBuf,
2762    /// False when a `.env` was already there: an existing file holds secrets and is never
2763    /// overwritten, not even by `--force`.
2764    pub dotenv_written: bool,
2765}
2766
2767/// Write the starter config, and the `.env` **where the loader will read it**, with a freshly
2768/// generated dashboard token (the token is never returned or printed).
2769///
2770/// Refuses to overwrite the config unless `force`. The `.env` is *never* overwritten: it
2771/// holds the user's secrets, and consent to replace a config is not consent to lose those.
2772/// Both files are created `0600` on Unix.
2773///
2774/// The two files are not always neighbours: `[dotenv]` is read from the config *directory*
2775/// (`$ECLIPSE_HOME`, or `~/.eclipse`) whatever `--config` points at, so a `.env` written beside a
2776/// `--config /other/config.toml` would never be opened — `config init` would report a token that
2777/// the next start cannot see. Without a home directory there is no place the loader reads, and the
2778/// file goes beside the config as before.
2779pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
2780    if path.exists() && !force {
2781        return Err(Error::Config(format!(
2782            "{} already exists (use --force to overwrite)",
2783            path.display()
2784        )));
2785    }
2786    let dir = path.parent().unwrap_or(Path::new("."));
2787    std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2788    write_private(path, &starter_config()?)?;
2789
2790    let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
2791    std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
2792    let dotenv = secrets_dir.join(".env");
2793    let mut dotenv_written = false;
2794    if !dotenv.exists() {
2795        let token = crate::token::generate()?;
2796        write_private(&dotenv, &starter_env(&token))?;
2797        dotenv_written = true;
2798    }
2799    // The template this file was generated from, kept so a later version can tell "the operator
2800    // chose this" from "we shipped this" (`config migrate`). Best effort: a config that was written
2801    // is a config that works, and a missing baseline costs nothing but a kept default.
2802    let _ = migrate::write_baseline(path);
2803    Ok(InitReport {
2804        config: path.to_path_buf(),
2805        dotenv,
2806        dotenv_written,
2807    })
2808}
2809
2810/// The value `[section] key = ...` holds in this TOML text, unquoted, if the key is set.
2811/// Commented-out template lines do not count: they are documentation, not config.
2812pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
2813    let mut in_section = false;
2814    for line in text.lines() {
2815        let trimmed = line.trim();
2816        if let Some(state) = header_state(trimmed, section) {
2817            in_section = state;
2818            continue;
2819        }
2820        if !in_section || trimmed.starts_with('#') {
2821            continue;
2822        }
2823        if let Some((k, v)) = key_value(trimmed) {
2824            if k == key {
2825                return Some(v);
2826            }
2827        }
2828    }
2829    None
2830}
2831
2832/// Set `[section] key = "value"` in this TOML text and return the whole text back.
2833///
2834/// Everything the wizard does not ask about survives untouched — comments, ordering, other
2835/// sections — because this rewrites one line rather than re-serialising the config. An
2836/// uncommented line is replaced in place; a commented template line (`# key = ...`) becomes
2837/// the real one; otherwise the key is added under the section header, and the section itself
2838/// is appended if it was missing.
2839pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
2840    toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
2841}
2842
2843/// Set `[section] key = <value>` where `value` is already TOML — `9000`, `true`, `["a", "b"]`,
2844/// `"text"` with its quotes. The line-editing rules are [`toml_set_string`]'s.
2845pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
2846    place_line(text, section, key, &format!("{key} = {value}"))
2847}
2848
2849// ── `[[mcp]]` entries (`#352`) ────────────────────────────────────────────────────────────────
2850//
2851// An entry is an array-of-tables *block*, not a line, so `place_line` cannot reach it: it edits one
2852// key inside one section. These three writers therefore work on line ranges, and each touches only
2853// the block it names — a `mcp add` leaves every hand-written entry, and every comment around it,
2854// exactly as it was. Re-rendering the whole file from the parsed config would be far less code and
2855// would delete every comment a person wrote, which is the one thing `toml_set_value` exists to
2856// avoid.
2857
2858/// One `[[mcp]]` block: its line range (`end` exclusive) and the name it declares, if the block
2859/// reads at all. A malformed block keeps its place and has no name, so no name-based verb can
2860/// silently match it.
2861struct McpSpan {
2862    name: Option<String>,
2863    start: usize,
2864    end: usize,
2865}
2866
2867fn is_table_header(trimmed: &str) -> bool {
2868    trimmed.starts_with('[')
2869}
2870
2871fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
2872    let mut spans: Vec<McpSpan> = Vec::new();
2873    let mut open: Option<usize> = None;
2874    let mut closed_by_header = true;
2875    for (i, line) in lines.iter().enumerate() {
2876        let trimmed = line.trim();
2877        if open.is_some() && is_table_header(trimmed) {
2878            if let Some(start) = open.take() {
2879                spans.push(McpSpan {
2880                    name: None,
2881                    start,
2882                    end: i,
2883                });
2884                closed_by_header = true;
2885            }
2886        }
2887        if trimmed == "[[mcp]]" {
2888            open = Some(i);
2889        }
2890    }
2891    if let Some(start) = open {
2892        spans.push(McpSpan {
2893            name: None,
2894            start,
2895            end: lines.len(),
2896        });
2897        closed_by_header = false;
2898    }
2899    // A block ends where the next one *starts being described*, not where its header sits: blank
2900    // lines and the comment directly above the next `[[mcp]]` are the next entry's. Trimming them
2901    // here is what keeps `disabled` out from under that comment, and what stops a removal from
2902    // taking the neighbour's note with it. The last block keeps its trailing lines — at the end of
2903    // the file there is nobody else they could belong to.
2904    let count = spans.len();
2905    for (i, span) in spans.iter_mut().enumerate() {
2906        let at_eof = i + 1 == count && !closed_by_header;
2907        while span.end > span.start + 1 {
2908            let tail = lines[span.end - 1].trim();
2909            let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
2910            if tail.is_empty() || belongs_to_next {
2911                span.end -= 1;
2912            } else {
2913                break;
2914            }
2915        }
2916    }
2917    for span in &mut spans {
2918        let body = lines[span.start + 1..span.end].join("\n");
2919        span.name = toml::from_str::<crate::mcp::Spec>(&body)
2920            .ok()
2921            .map(|spec| spec.name);
2922    }
2923    spans
2924}
2925
2926/// Collapse runs of blank lines left behind by a removal. Comments are never touched: a file that
2927/// gains a double blank line is untidy, and a file that loses somebody's note is broken.
2928fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
2929    let mut end = lines.len();
2930    while end > 0 && lines[end - 1].trim().is_empty() {
2931        end -= 1;
2932    }
2933    let mut out: Vec<String> = Vec::with_capacity(end);
2934    let mut blanks = 0;
2935    for line in &lines[..end] {
2936        if line.trim().is_empty() {
2937            blanks += 1;
2938            if blanks > 1 {
2939                continue;
2940            }
2941        } else {
2942            blanks = 0;
2943        }
2944        out.push(line.clone());
2945    }
2946    out
2947}
2948
2949/// How one entry is written back out: only the keys it actually sets, in the order the docs list
2950/// them. Rendering the whole struct would emit `args = []`, `env = []`, `policies = {}` and every
2951/// default beside the two lines a person meant to write.
2952fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
2953    let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
2954    let mut out = String::from("[[mcp]]\n");
2955    out.push_str(&format!("name = {}\n", quote(&entry.name)));
2956    if entry.transport == crate::mcp::Transport::Http {
2957        out.push_str("transport = \"http\"\n");
2958    }
2959    if !entry.command.is_empty() {
2960        out.push_str(&format!("command = {}\n", quote(&entry.command)));
2961    }
2962    if !entry.args.is_empty() {
2963        let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
2964        out.push_str(&format!("args = [{}]\n", args.join(", ")));
2965    }
2966    if let Some(url) = &entry.url {
2967        out.push_str(&format!("url = {}\n", quote(url)));
2968    }
2969    if let Some(var) = &entry.token_env {
2970        out.push_str(&format!("token_env = {}\n", quote(var)));
2971    }
2972    if entry.cwd != crate::plugins::Cwd::default() {
2973        let cwd = match entry.cwd {
2974            crate::plugins::Cwd::Workspace => "workspace",
2975            crate::plugins::Cwd::Plugin => "plugin",
2976        };
2977        out.push_str(&format!("cwd = \"{cwd}\"\n"));
2978    }
2979    if let Some(secs) = entry.timeout_secs {
2980        out.push_str(&format!("timeout_secs = {secs}\n"));
2981    }
2982    if entry.policy != Policy::Ask {
2983        let policy = match entry.policy {
2984            Policy::Deny => "deny",
2985            Policy::Ask => "ask",
2986            Policy::Allow => "allow",
2987        };
2988        out.push_str(&format!("policy = \"{policy}\"\n"));
2989    }
2990    if !entry.policies.is_empty() {
2991        let pairs: Vec<String> = entry
2992            .policies
2993            .iter()
2994            .map(|(tool, policy)| {
2995                let policy = match policy {
2996                    Policy::Deny => "deny",
2997                    Policy::Ask => "ask",
2998                    Policy::Allow => "allow",
2999                };
3000                // The tool name is the server's word, not a TOML key: unquoted, `a.b` becomes a
3001                // nested table and `a b` does not parse at all, so `mcp add` rejected its own
3002                // output for such a name (#541).
3003                format!("{} = \"{policy}\"", quote(tool))
3004            })
3005            .collect();
3006        out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
3007    }
3008    if !entry.prefix.is_empty() {
3009        out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
3010    }
3011    if !entry.env.is_empty() {
3012        let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
3013        out.push_str(&format!("env = [{}]\n", env.join(", ")));
3014    }
3015    if entry.override_builtin {
3016        out.push_str("override = true\n");
3017    }
3018    if entry.disabled {
3019        out.push_str("disabled = true\n");
3020    }
3021    out
3022}
3023
3024/// Add `[[mcp]]` entry — to `config.toml`, which is the file this edits (`#352`).
3025pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
3026    entry
3027        .validate()
3028        .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3029    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3030    let spans = mcp_spans(&lines);
3031    if let Some(existing) = spans
3032        .iter()
3033        .find(|s| s.name.as_deref() == Some(&entry.name))
3034    {
3035        return Err(format!(
3036            "`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
3037            entry.name,
3038            existing.start + 1,
3039            entry.name
3040        ));
3041    }
3042    let rendered = render_mcp_entry(entry);
3043    match spans.last() {
3044        Some(last) => {
3045            let at = last.end;
3046            let mut fresh: Vec<String> = Vec::new();
3047            // One blank line between entries; a block that already ends with one does not get two.
3048            if at > 0 && !lines[at - 1].trim().is_empty() {
3049                fresh.push(String::new());
3050            }
3051            fresh.extend(rendered.lines().map(str::to_string));
3052            lines.splice(at..at, fresh);
3053        }
3054        None => {
3055            if lines.last().is_some_and(|l| !l.trim().is_empty()) {
3056                lines.push(String::new());
3057            }
3058            lines.extend(rendered.lines().map(str::to_string));
3059        }
3060    }
3061    let out = join_lines(tidy_blanks(lines));
3062    readback_mcp(&out, &entry.name, |spec| spec == entry)
3063}
3064
3065/// Remove the `[[mcp]]` entry called `name`. Only that block goes.
3066pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
3067    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3068    let spans = mcp_spans(&lines);
3069    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3070        let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3071        return Err(if known.is_empty() {
3072            format!("no `[[mcp]]` entry for `{name}` in this file")
3073        } else {
3074            format!(
3075                "no `[[mcp]]` entry for `{name}`; this file declares {}",
3076                known.join(", ")
3077            )
3078        });
3079    };
3080    // A comment directly above the header describes this entry, so it goes with it — stopping at
3081    // the first blank line, which is where the previous entry's own trailing note lives.
3082    let mut start = span.start;
3083    while start > 0 && lines[start - 1].trim_start().starts_with('#') {
3084        start -= 1;
3085    }
3086    // Take the blank line *after* the block with it when there is one, so removing an entry does
3087    // not leave a hole where the next entry's separation used to be.
3088    let mut end = span.end;
3089    if end < lines.len() && lines[end].trim().is_empty() {
3090        end += 1;
3091    }
3092    lines.drain(start..end);
3093    readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
3094}
3095
3096/// Switch an entry off (or back on) in place: `disabled = true` inside its own block.
3097pub fn mcp_set_disabled(
3098    text: &str,
3099    name: &str,
3100    disabled: bool,
3101) -> std::result::Result<String, String> {
3102    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3103    let spans = mcp_spans(&lines);
3104    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3105        return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
3106    };
3107    let line = if disabled {
3108        "disabled = true".to_string()
3109    } else {
3110        // Written rather than deleted: a person reading the file sees the server was switched off
3111        // deliberately, and the loader treats `false` exactly like absence.
3112        "disabled = false".to_string()
3113    };
3114    let body = span.start + 1..span.end;
3115    match lines[body.clone()].iter().position(|l| {
3116        l.trim_start()
3117            .strip_prefix("disabled")
3118            .is_some_and(|rest| rest.trim_start().starts_with('='))
3119    }) {
3120        Some(offset) => lines[span.start + 1 + offset] = line,
3121        None => lines.insert(span.end, line),
3122    }
3123    readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
3124}
3125
3126/// Change the `[[mcp]]` entry called `name` in place (`#517`).
3127///
3128/// `change` is handed **the entry the file declares**, not a shape from a form: a key the surface
3129/// does not show (`disabled`, `env`, `policies`, `override`, `cwd`) is not a key the person cleared.
3130/// The text that comes back differs only in the lines whose *value* changed, which is why both
3131/// renderings are compared: a hand-written entry keeps its own quoting, its own order and every
3132/// comment, and a field set back to its default loses its line rather than gaining a default one.
3133/// The rename is refused rather than done, because a rename is a remove and an add.
3134pub fn mcp_update(
3135    text: &str,
3136    name: &str,
3137    change: impl FnOnce(&mut crate::mcp::Spec),
3138) -> std::result::Result<String, String> {
3139    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3140    let spans = mcp_spans(&lines);
3141    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3142        let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3143        return Err(if known.is_empty() {
3144            format!("no `[[mcp]]` entry for `{name}` in this file")
3145        } else {
3146            format!(
3147                "no `[[mcp]]` entry for `{name}`; this file declares {}",
3148                known.join(", ")
3149            )
3150        });
3151    };
3152    let body = lines[span.start + 1..span.end].join("\n");
3153    let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
3154        format!(
3155            "the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
3156            span.start + 1,
3157            crate::config::settings::one_line(&e.to_string())
3158        )
3159    })?;
3160    let mut after = before.clone();
3161    change(&mut after);
3162    if after.name != name {
3163        return Err(format!(
3164            "an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
3165             name instead"
3166        ));
3167    }
3168    after
3169        .validate()
3170        .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3171    let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
3172        render_mcp_entry(spec)
3173            .lines()
3174            .skip(1) // the `[[mcp]]` header, which stays where it is
3175            .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
3176            .collect()
3177    };
3178    let (old, new) = (rendered(&before), rendered(&after));
3179    let (mut start, mut end) = (span.start + 1, span.end);
3180    // Walk the block one key (plus its continuation lines) at a time and keep everything the new
3181    // entry still says in the same place.
3182    let block: Vec<String> = lines[start..end].to_vec();
3183    let mut rebuilt: Vec<String> = Vec::new();
3184    let mut seen: Vec<String> = Vec::new();
3185    let mut i = 0;
3186    while i < block.len() {
3187        let line = &block[i];
3188        let trimmed = line.trim();
3189        if trimmed.is_empty() || trimmed.starts_with('#') {
3190            rebuilt.push(line.clone());
3191            i += 1;
3192            continue;
3193        }
3194        let first = i;
3195        let mut depth = bracket_depth(line);
3196        i += 1;
3197        while depth > 0 && i < block.len() {
3198            depth += bracket_depth(&block[i]);
3199            i += 1;
3200        }
3201        match key_of(&block[first]) {
3202            Some(key) => {
3203                seen.push(key.clone());
3204                match (old.get(&key), new.get(&key)) {
3205                    // Unchanged: the file's own line, byte for byte.
3206                    (Some(was), Some(is)) if was == is => {
3207                        rebuilt.extend(block[first..i].iter().cloned())
3208                    }
3209                    (_, Some(is)) => rebuilt.push(is.clone()),
3210                    // Cleared to its default: the line goes, and nothing else moves.
3211                    (_, None) => {}
3212                }
3213            }
3214            // A line that names no key is somebody's text; it is never dropped.
3215            None => rebuilt.extend(block[first..i].iter().cloned()),
3216        }
3217    }
3218    for (key, line) in &new {
3219        if !seen.contains(key) {
3220            rebuilt.push(line.clone());
3221        }
3222    }
3223    start = start.min(lines.len());
3224    end = end.min(lines.len());
3225    lines.splice(start..end, rebuilt);
3226    let out = join_lines(lines);
3227    readback_mcp(&out, name, |spec| spec == &after)
3228}
3229
3230/// The `key` of a `key = value` line, or `None` for a comment, a blank line or a continuation.
3231fn key_of(line: &str) -> Option<String> {
3232    let trimmed = line.trim();
3233    if trimmed.starts_with('#') {
3234        return None;
3235    }
3236    let (key, _) = trimmed.split_once('=')?;
3237    let key = key.trim();
3238    let plain = !key.is_empty()
3239        && !key.contains(char::is_whitespace)
3240        && key
3241            .chars()
3242            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
3243    plain.then(|| key.to_string())
3244}
3245
3246/// How many brackets a line opens: a value that ends above zero continues on the next line.
3247/// Quotes are honoured, so an `args = ["a=b"]` is still one line.
3248fn bracket_depth(line: &str) -> i32 {
3249    let mut depth = 0;
3250    let mut quote: Option<char> = None;
3251    let mut escaped = false;
3252    for c in line.chars() {
3253        if let Some(q) = quote {
3254            if escaped {
3255                escaped = false;
3256            } else if c == '\\' {
3257                escaped = true;
3258            } else if c == q {
3259                quote = None;
3260            }
3261            continue;
3262        }
3263        match c {
3264            '"' | '\'' => quote = Some(c),
3265            '[' | '{' => depth += 1,
3266            ']' | '}' => depth -= 1,
3267            '#' => break, // a trailing comment is prose, not value
3268            _ => {}
3269        }
3270    }
3271    depth
3272}
3273
3274/// The guard every writer here shares, in `set_in_text`'s voice: the text must load, and the entry
3275/// it names must read back as what was asked. Anything else means nothing is written.
3276fn readback_mcp(
3277    text: &str,
3278    name: &str,
3279    ok: impl Fn(&crate::mcp::Spec) -> bool,
3280) -> std::result::Result<String, String> {
3281    let cfg = parse_text(text).map_err(|e| {
3282        format!(
3283            "that would not load, so nothing was saved: {}",
3284            settings::one_line(&e.to_string())
3285        )
3286    })?;
3287    match cfg.mcp.iter().find(|s| s.name == name) {
3288        Some(spec) if ok(spec) => Ok(text.to_string()),
3289        Some(_) => {
3290            Err("the file would not read that entry back as written; nothing was saved".into())
3291        }
3292        None => Err(format!(
3293            "the edit lost `{name}` on the way back in; nothing was saved"
3294        )),
3295    }
3296}
3297
3298fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
3299    let cfg = parse_text(text).map_err(|e| {
3300        format!(
3301            "that would not load, so nothing was saved: {}",
3302            settings::one_line(&e.to_string())
3303        )
3304    })?;
3305    if cfg.mcp.iter().any(|s| s.name == name) {
3306        return Err(format!("`{name}` survived the removal; nothing was saved"));
3307    }
3308    Ok(text.to_string())
3309}
3310
3311/// Replace the line for `[section] key` with `replacement`, or insert one after the section header.
3312///
3313/// The one traversal both a value and a comment go through, so "where a key's line goes" is decided
3314/// once: a commented `# key = …` in that section is the line to replace, and a section with neither
3315/// gets the line directly under its header.
3316fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
3317    let quoted = replacement.to_string();
3318    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3319    let mut in_section = false;
3320    let mut header_at: Option<usize> = None;
3321    let mut commented_at: Option<usize> = None;
3322    for (i, line) in lines.iter().enumerate() {
3323        let trimmed = line.trim();
3324        if let Some(state) = header_state(trimmed, section) {
3325            in_section = state;
3326            if in_section && header_at.is_none() {
3327                header_at = Some(i);
3328            }
3329            continue;
3330        }
3331        if !in_section {
3332            continue;
3333        }
3334        if let Some((k, _)) = key_value(trimmed) {
3335            if k == key {
3336                lines[i] = quoted;
3337                return join_lines(lines);
3338            }
3339        } else if let Some(rest) = trimmed.strip_prefix('#') {
3340            // `# key = "default"` is how the starter documents an optional key.
3341            if let Some((k, _)) = key_value(rest.trim()) {
3342                if k == key && commented_at.is_none() {
3343                    commented_at = Some(i);
3344                }
3345            }
3346        }
3347    }
3348    match (header_at, commented_at) {
3349        (_, Some(i)) => lines[i] = quoted,
3350        (Some(i), None) => lines.insert(i + 1, quoted),
3351        (None, None) => {
3352            lines.push(String::new());
3353            lines.push(format!("[{section}]"));
3354            lines.push(quoted);
3355        }
3356    }
3357    join_lines(lines)
3358}
3359
3360/// Insert `# key =` under `[section]`, which is how a shipped file says "this key exists and is not
3361/// in use" for a key whose off state has no spelling (a number, a colour, an explicit boolean).
3362///
3363/// The companion to [`toml_set_value`], and deliberately not a call to it with a `#` in the key:
3364/// this line is *inert*, and a migration that wrote it as a value would be imposing something.
3365pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
3366    place_line(text, section, key, &format!("# {key} ="))
3367}
3368
3369/// Write `config_version = N` into this TOML text, at the top, where the generated file puts it.
3370///
3371/// Top-level because it describes the file and must survive a section being renamed, and replacing
3372/// the existing line rather than appending keeps it at the top of a file that already has one.
3373pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
3374    let line = format!("config_version = {version}");
3375    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3376    if let Some(at) = lines.iter().position(|l| {
3377        l.trim_start()
3378            .strip_prefix("config_version")
3379            .is_some_and(|rest| rest.trim_start().starts_with('='))
3380    }) {
3381        lines[at] = line;
3382    } else {
3383        // Under the header comments and above the first table: TOML wants top-level scalars before
3384        // the first `[section]`, and the header comment is the file's own front page. The spacing
3385        // is normalised to what `config init` writes — no blank line above the stamp, one below —
3386        // so a migrated file and a fresh one cannot be told apart by looking at them.
3387        let first_table = lines
3388            .iter()
3389            .position(|l| !matches!(classify(l.trim()), Header::Other))
3390            .unwrap_or(lines.len());
3391        let mut insert_at = 0;
3392        while insert_at < first_table
3393            && (lines[insert_at].trim_start().starts_with('#')
3394                || lines[insert_at].trim().is_empty())
3395        {
3396            insert_at += 1;
3397        }
3398        lines.insert(insert_at, String::new());
3399        lines.insert(insert_at, line);
3400        while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
3401            lines.remove(insert_at - 1);
3402            insert_at -= 1;
3403        }
3404    }
3405    let out = join_lines(lines);
3406    // Proved, like every other write here: a file that does not parse afterwards is not written.
3407    parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
3408    Ok(out)
3409}
3410
3411/// Comment `[section] key = …` out of this TOML text, so the file falls back to the default.
3412///
3413/// Commented, not deleted: the neighbours of that line explain the key, and a person who unsets
3414/// `web.port` should still be able to see what it is called. A key that is not there at all is
3415/// left alone — unsetting what is already unset is not an error.
3416pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
3417    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3418    let mut in_section = false;
3419    for line in lines.iter_mut() {
3420        let trimmed = line.trim();
3421        if let Some(state) = header_state(trimmed, section) {
3422            in_section = state;
3423            continue;
3424        }
3425        if !in_section || trimmed.starts_with('#') {
3426            continue;
3427        }
3428        if let Some((k, _)) = key_value(trimmed) {
3429            if k == key {
3430                let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
3431                *line = format!("{indent}# {trimmed}");
3432                return join_lines(lines);
3433            }
3434        }
3435    }
3436    join_lines(lines)
3437}
3438
3439/// What a line is, as far as the line editor is concerned.
3440///
3441/// Three answers rather than `Option<&str>` because `[[provider.route]]` is neither "a section"
3442/// nor "not a header": it *ends* the section above it, and none of that section's keys may be
3443/// edited inside it. A route flattens a provider config, so it carries the same key names as
3444/// `[provider]` — read as part of the section, `config unset provider.timeout_secs` commented out
3445/// the route's key, saved, and reported success (#535).
3446pub(crate) enum Header<'a> {
3447    /// `[section]` — the current section becomes this name.
3448    Section(&'a str),
3449    /// `[[a.b]]` — one element of an array of tables. It ends the current section.
3450    Array,
3451    /// Not a header at all.
3452    Other,
3453}
3454
3455/// `[section]` → `section`; `[[table]]` → an array header; anything else is not a header. `[a.b]`
3456/// is its own name, not `a`.
3457pub(crate) fn classify(trimmed: &str) -> Header<'_> {
3458    if trimmed.starts_with("[[") {
3459        return Header::Array;
3460    }
3461    let Some(rest) = trimmed.strip_prefix('[') else {
3462        return Header::Other;
3463    };
3464    let Some(name) = rest.strip_suffix(']') else {
3465        return Header::Other;
3466    };
3467    if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
3468        return Header::Other;
3469    }
3470    Header::Section(name)
3471}
3472
3473/// If this line is a table header, whether it starts `section`.
3474///
3475/// `Some(false)` for `[[a.b]]`: the walkers below are looking for one section's keys, and an array
3476/// element is the end of whatever came before it. `None` means the line is not a header, so the
3477/// caller should read it as content.
3478pub(crate) fn header_state(trimmed: &str, section: &str) -> Option<bool> {
3479    match classify(trimmed) {
3480        Header::Section(name) => Some(name == section),
3481        Header::Array => Some(false),
3482        Header::Other => None,
3483    }
3484}
3485
3486/// `key = value` → (`key`, unquoted value). Anything without an `=` or with an empty key is
3487/// not a key/value line.
3488pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
3489    let (k, v) = trimmed.split_once('=')?;
3490    let k = k.trim();
3491    if k.is_empty() || k.contains([' ', '"', '\\']) {
3492        return None;
3493    }
3494    let v = v.trim();
3495    let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
3496        Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
3497        None => v.to_string(),
3498    };
3499    Some((k, unquoted))
3500}
3501
3502fn escape_toml(value: &str) -> String {
3503    value.replace('\\', "\\\\").replace('"', "\\\"")
3504}
3505
3506fn join_lines(lines: Vec<String>) -> String {
3507    let mut out = lines.join("\n");
3508    if !out.ends_with('\n') {
3509        out.push('\n');
3510    }
3511    out
3512}
3513
3514/// Write config text back with the same permissions as the starter (`0600`) — the file can
3515/// carry `api_key`, and a config people paste into bug reports should still be readable only
3516/// by them.
3517pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
3518    write_private(path, text)
3519}
3520
3521/// Parse config text exactly as the loader would. A writer uses this to prove what it is
3522/// about to save is loadable *before* it replaces the user's file.
3523pub fn parse_text(text: &str) -> Result<Config> {
3524    let cfg: Config =
3525        toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3526    crate::hooks::validate(&cfg.hooks)
3527        .map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3528    Ok(cfg)
3529}
3530
3531/// Set `KEY=value` in a `.env`, creating it `0600` if it does not exist. An existing line for
3532/// that key is replaced; every other line, comment included, is kept. Values are written raw:
3533/// a `.env` is not TOML and the loader takes the rest of the line as the value.
3534pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
3535    // A line break is not part of a value: it would write a second line into the file, and in a
3536    // `.env` a stray line is another secret (`#538`).
3537    if key.contains(['\n', '\r']) || value.contains(['\n', '\r']) {
3538        return Err(Error::Config(format!(
3539            "{key:?} cannot be written to {}: a line break in a key or a value would make a second \
3540             assignment",
3541            path.display()
3542        )));
3543    }
3544    // A read error is not an empty file. `unwrap_or_default()` collapsed `EACCES`, `EIO` and invalid
3545    // UTF-8 into "", and the write that followed replaced `.env` with one line — taking every other
3546    // secret in it with the read error (`#538`).
3547    let existing = match std::fs::read(path) {
3548        Ok(bytes) => String::from_utf8(bytes).map_err(|_| {
3549            Error::Config(format!(
3550                "{}: not valid UTF-8, so nothing was written — repair or remove it by hand",
3551                path.display()
3552            ))
3553        })?,
3554        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3555        Err(e) => {
3556            return Err(Error::Config(format!(
3557                "{}: {e}, so nothing was written — whatever else is in it is untouched",
3558                path.display()
3559            )))
3560        }
3561    };
3562    let line = format!("{key}={value}");
3563    let mut out = String::new();
3564    let mut replaced = false;
3565    for l in existing.lines() {
3566        let is_key = l
3567            .trim_start()
3568            .strip_prefix(key)
3569            .map(|rest| rest.starts_with('='))
3570            .unwrap_or(false);
3571        if is_key {
3572            out.push_str(&line);
3573            out.push('\n');
3574            replaced = true;
3575        } else {
3576            out.push_str(l);
3577            out.push('\n');
3578        }
3579    }
3580    if !replaced {
3581        if !out.is_empty() && !out.ends_with('\n') {
3582            out.push('\n');
3583        }
3584        out.push_str(&line);
3585        out.push('\n');
3586    }
3587    write_private(path, &out)?;
3588    // And prove it with the parser the next run reads with. A line this wrote that reads back as
3589    // something else — an inline `#`, a quote the loader honours and this writer does not — is how a
3590    // saved secret silently becomes a different one (`#538`).
3591    let back = crate::dotenv::load(path)
3592        .map_err(|e| Error::Config(format!("{}: {e}", path.display())))?
3593        .into_iter()
3594        .rfind(|a| a.key == key)
3595        .map(|a| a.value);
3596    match back {
3597        Some(got) if got == value => Ok(()),
3598        Some(got) => Err(Error::Config(format!(
3599            "{}: {key} was written but reads back as {got:?}, not {value:?}; the rest of the file is \
3600             intact, so fix that line by hand",
3601            path.display()
3602        ))),
3603        None => Err(Error::Config(format!(
3604            "{}: {key} was written but the loader does not see it",
3605            path.display()
3606        ))),
3607    }
3608}
3609
3610/// The value of `KEY` in a `.env` file, if it has one.
3611///
3612/// Answered by the loader that reads the file for real (`crate::dotenv`), so `export`, quotes and a
3613/// repeated key mean here exactly what they mean there: last one wins, as in the loader, and an empty
3614/// value is absence, as `#295` says everywhere else. The old reader took the first duplicate, kept
3615/// the quotes and answered `Some("")` for `KEY=` — three ways to disagree with the run it was
3616/// describing (`#538`).
3617pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
3618    crate::dotenv::load(path)
3619        .ok()?
3620        .into_iter()
3621        .rfind(|a| a.key == key)
3622        .map(|a| a.value)
3623        .filter(|value| !value.is_empty())
3624}
3625
3626/// Write a file that only its owner may read: created `0600` on Unix, and replaced in place
3627/// rather than appended to.
3628pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
3629    // `#408`: this truncated the file before writing it, so a crash, a full disk or a `kill -9`
3630    // between the two left a zero-length `config.toml` — which loads as *defaults*, so every
3631    // `provider.*` value silently vanished. Write beside and rename instead; `0600` is set on the
3632    // temporary file, so there is no window where the secrets are readable by anyone else.
3633    crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
3634}
3635
3636#[test]
3637fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
3638    // The rule from #295: an empty value *is* absence. So `key = ""` has to be writable, and it has
3639    // to verify — which it could not while `set_in_text` demanded the value come back as `""`. The
3640    // 0.9.0-shaped file (every key commented) exposed it: a migration adding 78 keys hit the first
3641    // empty-string key and refused the whole file.
3642    let text = starter_config().unwrap();
3643    let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
3644    assert_eq!(
3645        Config::from_toml_str(&without).unwrap().agent.output_schema,
3646        None
3647    );
3648    let back = settings::set_in_text(
3649        &without,
3650        "agent.output_schema",
3651        &toml::Value::String(String::new()),
3652    )
3653    .expect("an empty value can be written");
3654    assert!(back.contains("output_schema = \"\""), "{back}");
3655    assert_eq!(
3656        Config::from_toml_str(&back).unwrap().agent.output_schema,
3657        None,
3658        "and it reads as unset, which is what it means"
3659    );
3660    assert_eq!(
3661        toml_value(&back, "agent", "output_schema"),
3662        Some(String::new()),
3663        "the line is there; what it holds is nothing"
3664    );
3665}
3666
3667#[cfg(test)]
3668mod tests {
3669    // ---------------------------------------------------------------------------------------
3670    // `#171`: two route keys say how many flares a route holds, and `[flares]` says what a run
3671    // costs. The arithmetic that combines them lives in `flares::slots`, but the reading of the
3672    // keys is here.
3673    // ---------------------------------------------------------------------------------------
3674
3675    #[test]
3676    fn a_route_can_say_how_many_flares_it_holds() {
3677        let cfg = Config::from_toml_str(
3678            r#"
3679[provider]
3680fallback = ["local", "cloud"]
3681
3682[[provider.route]]
3683name = "local"
3684base_url = "http://127.0.0.1:8080/v1"
3685model = "qwen"
3686profile = "llamacpp"
3687group = "gpu0"
3688max_parallel = 2
3689
3690[[provider.route]]
3691name = "cloud"
3692base_url = "https://api.example.com/v1"
3693model = "big"
3694"#,
3695        )
3696        .unwrap();
3697        let routes = cfg.declared_routes();
3698        let local = routes.iter().find(|r| r.name == "local").unwrap();
3699        assert_eq!(local.parallel(), 2, "the route said two slots");
3700        assert_eq!(local.group.as_deref(), Some("gpu0"));
3701        let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
3702        // An API states no shape, so the profile decides: openai is four, a local server one.
3703        assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
3704        assert!(cloud.group.is_none());
3705        assert_eq!(
3706            local.default_parallel(),
3707            1,
3708            "llamacpp serves one model at a time"
3709        );
3710
3711        // `0` is read as `1`: a route with no slot is a route flares cannot use, and starving
3712        // them silently is worse than a slow run.
3713        let zero = Config::from_toml_str(
3714            r#"
3715[[provider.route]]
3716name = "local"
3717base_url = "http://127.0.0.1:8080/v1"
3718model = "qwen"
3719max_parallel = 0
3720"#,
3721        )
3722        .unwrap();
3723        assert_eq!(zero.declared_routes()[0].parallel(), 1);
3724
3725        // A wrong type is the route's error, not a mysterious one about `provider.route`.
3726        let bad = Config::from_toml_str(
3727            r#"
3728[[provider.route]]
3729name = "local"
3730base_url = "http://127.0.0.1:8080/v1"
3731model = "qwen"
3732max_parallel = "two"
3733"#,
3734        )
3735        .unwrap_err()
3736        .to_string();
3737        assert!(bad.contains("route `local`"), "{bad}");
3738        assert!(bad.contains("max_parallel"), "{bad}");
3739    }
3740
3741    #[test]
3742    fn flares_default_to_three_on_one_local_slot() {
3743        let cfg = Config::from_toml_str("").unwrap();
3744        assert_eq!(cfg.flares.count, 3, "the local default");
3745        assert_eq!(cfg.flares.concurrency(), 4);
3746        assert_eq!(cfg.flares.per_flare(), 6);
3747        assert_eq!(cfg.flares.budget(), 24);
3748
3749        let cfg = Config::from_toml_str(
3750            r#"
3751[flares]
3752count = 5
3753max_concurrent = 0
3754max_iterations = 0
3755total_iterations = 2
3756"#,
3757        )
3758        .unwrap();
3759        assert_eq!(cfg.flares.count, 5);
3760        // Zero is never a usable cap: the same rule as `[tools] concurrency`, and a run allowed
3761        // fewer turns than one flare would fail before it began.
3762        assert_eq!(cfg.flares.concurrency(), 1);
3763        assert_eq!(cfg.flares.per_flare(), 1);
3764        assert_eq!(cfg.flares.budget(), 2);
3765    }
3766
3767    // ---------------------------------------------------------------------------------------
3768    // `#542`, `#543`, `#544`: three places where a path or a variable from outside the file was
3769    // applied without asking whether the file had room for it.
3770    // ---------------------------------------------------------------------------------------
3771
3772    fn home_env(k: &str) -> Option<String> {
3773        (k == "HOME").then(|| "/home/op".to_string())
3774    }
3775
3776    /// `#542`: `[user] memory_file` may be absolute, and `Path::join` discards the prefix for one —
3777    /// so every bot read and wrote the operator's own `MEMORY.md`, the one thing `bot_memory`'s
3778    /// own doc says must not be shared.
3779    #[test]
3780    fn a_bot_gets_its_own_memory_even_when_the_operator_names_an_absolute_file() {
3781        let mut cfg = Config::default();
3782        cfg.user.memory_file = "/srv/notes/MEMORY.md".to_string();
3783        let path = cfg
3784            .bot_memory(&home_env, "triage", &crate::config::BotConfig::default())
3785            .expect("a home directory is known");
3786        assert!(
3787            path.ends_with("bots/triage/MEMORY.md"),
3788            "{}",
3789            path.display()
3790        );
3791        assert!(
3792            !path.starts_with("/srv/notes"),
3793            "the absolute path is not a bot's memory: {}",
3794            path.display()
3795        );
3796    }
3797
3798    /// `#543`: the three connection variables describe the `default` route. Applied to a config
3799    /// that has only named routes, they invent a `default` that `fallback` does not name, and
3800    /// `validate_routes` refuses a file that loads fine from a clean shell.
3801    #[test]
3802    fn an_exported_model_does_not_break_a_routes_only_config() {
3803        let text = "\
3804[provider]
3805fallback = [\"local\"]
3806
3807[[provider.route]]
3808name = \"local\"
3809base_url = \"http://127.0.0.1:8080/v1\"
3810model = \"m\"
3811";
3812        let exported = |k: &str| match k {
3813            "ECLIPSE_MODEL" => Some("from-the-shell".to_string()),
3814            "ECLIPSE_BASE_URL" => Some("http://elsewhere.example/v1".to_string()),
3815            _ => None,
3816        };
3817        let mut cfg = Config::from_toml_str(text).unwrap();
3818        cfg.apply_env(&exported);
3819        assert_eq!(cfg.route_names(), "local", "no phantom `default` route");
3820        cfg.validate_routes()
3821            .expect("a routes-only config still validates with variables exported");
3822    }
3823
3824    /// `#544`: `default` is the base config, not a directory of its own. Read the other way,
3825    /// `--profile default` split one install in two — memory and scripts under `profiles/default/`,
3826    /// state in the root.
3827    #[test]
3828    fn the_default_profile_is_the_base_config() {
3829        let plain = Config::default();
3830        let named = Config {
3831            profile: Some("default".to_string()),
3832            ..Default::default()
3833        };
3834        assert_eq!(named.context_dir(&home_env), plain.context_dir(&home_env));
3835        assert_eq!(named.scripts_dir(&home_env), plain.scripts_dir(&home_env));
3836        assert_eq!(
3837            named.state_dir(&home_env).unwrap(),
3838            plain.state_dir(&home_env).unwrap()
3839        );
3840        let dir = named.context_dir(&home_env).unwrap();
3841        assert!(
3842            !dir.ends_with("profiles/default"),
3843            "`default` is not a profile directory: {}",
3844            dir.display()
3845        );
3846    }
3847
3848    // `#535`: the line editor walks text looking for one section's keys, and `[[provider.route]]`
3849    // carries the same key names as `[provider]` (a route is a whole provider config). An array
3850    // header that did not end the section let `config unset provider.timeout_secs` comment out a
3851    // *route's* key, save the file and report success.
3852    // ---------------------------------------------------------------------------------------
3853
3854    /// `[provider]` says nothing about `timeout_secs`; the first route does. That is the shape the
3855    /// bug needed: a key the section does not set but a route does, which the walker used to find
3856    /// inside `[[provider.route]]` and edit there.
3857    const ROUTED: &str = "\
3858[provider]
3859base_url = \"http://127.0.0.1:8080/v1\"
3860
3861[[provider.route]]
3862name = \"slow\"
3863base_url = \"http://gpu-box:8000/v1\"
3864model = \"m\"
3865timeout_secs = 900
3866";
3867
3868    #[test]
3869    fn an_array_header_ends_the_section_above_it() {
3870        assert_eq!(
3871            toml_value(ROUTED, "provider", "timeout_secs"),
3872            None,
3873            "the route's key is not `[provider]`'s"
3874        );
3875
3876        // Unsetting what `[provider]` does not set is a no-op, and the route keeps its line.
3877        let unset = toml_comment_out(ROUTED, "provider", "timeout_secs");
3878        assert_eq!(unset, ROUTED, "nothing in `[provider]` to comment out");
3879
3880        // Setting it writes under `[provider]` — not over the route's 900, which is what the
3881        // walker used to do while reporting success.
3882        let set = toml_set_value(ROUTED, "provider", "timeout_secs", "45");
3883        let (provider, routes) = set.split_once("[[provider.route]]").unwrap();
3884        assert!(
3885            provider.contains("timeout_secs = 45"),
3886            "written under `[provider]`: {set}"
3887        );
3888        assert!(
3889            routes.contains("timeout_secs = 900"),
3890            "the route keeps its own timeout: {set}"
3891        );
3892    }
3893
3894    #[test]
3895    fn a_key_the_section_does_not_have_yet_is_added_under_its_own_header() {
3896        let set = toml_set_string(ROUTED, "provider", "api_key_env", "LOCAL_KEY");
3897        let (provider, routes) = set.split_once("[[provider.route]]").unwrap();
3898        assert!(
3899            provider.contains("api_key_env = \"LOCAL_KEY\""),
3900            "added under `[provider]`, not inside a route: {set}"
3901        );
3902        assert!(
3903            !routes.contains("api_key_env"),
3904            "the route is untouched: {set}"
3905        );
3906    }
3907
3908    #[test]
3909    fn a_header_is_classified_by_what_it_names() {
3910        assert!(matches!(
3911            classify("[provider]"),
3912            Header::Section("provider")
3913        ));
3914        assert!(matches!(classify("[[provider.route]]"), Header::Array));
3915        assert!(matches!(classify("[a.b]"), Header::Section("a.b")));
3916        assert!(matches!(classify("[ spaced ]"), Header::Other));
3917        assert!(matches!(classify("[provider"), Header::Other));
3918        assert!(matches!(classify("key = 1"), Header::Other));
3919        assert_eq!(header_state("[provider]", "provider"), Some(true));
3920        assert_eq!(header_state("[[provider.route]]", "provider"), Some(false));
3921        assert_eq!(header_state("key = 1", "provider"), None);
3922    }
3923
3924    /// `#541`: a tool name is the server's word, not a TOML key.
3925    #[test]
3926    fn an_mcp_tool_name_with_a_dot_or_a_space_is_quoted() {
3927        let spec: crate::mcp::Spec = toml::from_str(
3928            "name = \"srv\"\ncommand = \"x\"\n\
3929             policies = { \"a.b\" = \"allow\", \"read text\" = \"deny\" }\n",
3930        )
3931        .unwrap();
3932        let out = render_mcp_entry(&spec);
3933        assert!(out.contains("\"a.b\" = \"allow\""), "{out}");
3934        assert!(out.contains("\"read text\" = \"deny\""), "{out}");
3935        // The point of quoting is that the file this writes is a file the loader reads again.
3936        // `render_mcp_entry` starts with the `[[mcp]]` header, which belongs to the file rather
3937        // than to the entry: the loader is handed the block without it.
3938        let body = out.lines().skip(1).collect::<Vec<_>>().join("\n");
3939        let back: crate::mcp::Spec = toml::from_str(&body).unwrap();
3940        assert_eq!(back.policies.get("a.b"), Some(&Policy::Allow));
3941        assert_eq!(back.policies.get("read text"), Some(&Policy::Deny));
3942    }
3943
3944    use super::*;
3945    use std::collections::HashMap;
3946
3947    /// The shipped config, generated — the fixture every test about the file itself starts from.
3948    fn starter() -> String {
3949        starter_config().expect("the starter config generates")
3950    }
3951
3952    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
3953        let m: HashMap<String, String> = pairs
3954            .iter()
3955            .map(|(k, v)| (k.to_string(), v.to_string()))
3956            .collect();
3957        move |k| m.get(k).cloned()
3958    }
3959
3960    /// Load `text` as a config file exactly as the binary would, and say what happened.
3961    fn load_hooks(text: &str) -> std::result::Result<Config, String> {
3962        let tmp = tempfile::tempdir().unwrap();
3963        let path = tmp.path().join("config.toml");
3964        std::fs::write(&path, text).unwrap();
3965        let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
3966        Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
3967    }
3968
3969    #[test]
3970    fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
3971        let want = crate::hooks::DEFAULT_ORDER;
3972        let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
3973        assert_eq!(c.hooks.order, want);
3974        assert_eq!(Config::default().hooks.order, want);
3975        let c = load_hooks("").unwrap();
3976        assert_eq!(c.hooks.order, want);
3977        assert!(
3978            !want.contains(&"recall-sessions"),
3979            "a new session is a new session: recall is opt-in, and `session_search` is how the \
3980             agent reaches the archive"
3981        );
3982    }
3983
3984    #[test]
3985    fn an_empty_order_turns_every_hook_off() {
3986        let c = load_hooks("[hooks]\norder = []\n").unwrap();
3987        assert!(c.hooks.order.is_empty());
3988    }
3989
3990    #[test]
3991    fn a_settings_table_alone_keeps_the_default_order() {
3992        let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
3993        assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
3994    }
3995
3996    #[test]
3997    fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
3998        let err =
3999            load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
4000        assert!(err.contains("`redact-secret`"), "{err}");
4001        assert!(
4002            err.contains("Hooks that exist: recall-sessions, redact-secrets"),
4003            "{err}"
4004        );
4005        assert!(err.contains("config.toml"), "the file is named: {err}");
4006    }
4007
4008    #[test]
4009    fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
4010        let err =
4011            load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
4012        assert!(err.contains("[hooks.redact-secrets]"), "{err}");
4013        assert!(err.contains("never run"), "{err}");
4014        assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
4015    }
4016
4017    #[test]
4018    fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
4019        let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
4020        assert!(err.contains("[hooks.nope]"), "{err}");
4021        assert!(err.contains("Hooks that exist"), "{err}");
4022    }
4023
4024    #[test]
4025    fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
4026        let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
4027        assert!(err.contains("unknown key `alow`"), "{err}");
4028        assert!(err.contains("accepts: allow"), "{err}");
4029    }
4030
4031    #[test]
4032    fn a_stray_key_directly_under_hooks_is_refused() {
4033        let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
4034        assert!(err.contains("`enabled`"), "{err}");
4035        assert!(err.contains("`order`"), "{err}");
4036    }
4037
4038    #[test]
4039    fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
4040        let err =
4041            load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
4042        assert!(err.contains("twice"), "{err}");
4043        let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
4044        assert!(err.contains("must be a list of strings"), "{err}");
4045        let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
4046        assert!(err.contains("empty string"), "{err}");
4047        let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
4048        assert!(err.contains("only strings"), "{err}");
4049    }
4050
4051    #[test]
4052    fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
4053        let tmp = tempfile::tempdir().unwrap();
4054        let home = tmp.path().join("home");
4055        let dir = home.join(".eclipse");
4056        std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
4057        std::fs::write(
4058            dir.join("config.toml"),
4059            "[hooks]\norder = [\"redact-secrets\"]\n",
4060        )
4061        .unwrap();
4062        std::fs::write(
4063            dir.join("profiles/work/config.toml"),
4064            "[hooks]\norder = [\"typo\"]\n",
4065        )
4066        .unwrap();
4067        let env = env_of(&[("HOME", home.to_str().unwrap())]);
4068        let err = Config::load_with_profile(None, Some("work"), &env)
4069            .unwrap_err()
4070            .to_string();
4071        assert!(err.contains("profiles/work/config.toml"), "{err}");
4072        assert!(err.contains("`typo`"), "{err}");
4073    }
4074
4075    /// An empty value is "not in use", and it has to be true in one place: a shipped `.env` names
4076    /// every variable and sets none of them, so `NAME=` has to read as absent — in the loader that
4077    /// resolves `${VAR}`, in the token the dashboard needs, and not one call site at a time.
4078    #[test]
4079    fn an_empty_value_is_not_a_value_in_the_dotenv() {
4080        let dir = tempfile::tempdir().unwrap();
4081        let home = dir.path();
4082        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
4083        let path = home.join(".eclipse/.env");
4084        std::fs::write(
4085            &path,
4086            "ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
4087        )
4088        .unwrap();
4089        let home_s = home.to_str().unwrap().to_string();
4090        let env = env_of(&[("HOME", &home_s)]);
4091        let loaded = Dotenv::load(&env, None).unwrap();
4092        assert_eq!(
4093            loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
4094            Some("m")
4095        );
4096        assert!(
4097            !loaded.values.contains_key("ECLIPSE_API_KEY"),
4098            "an empty assignment is absent: {:?}",
4099            loaded.values.keys().collect::<Vec<_>>()
4100        );
4101        assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
4102    }
4103
4104    /// A later line still wins even when it empties a key: "this host does not use it" is a thing
4105    /// a profile's `.env` has to be able to say about the shared one.
4106    #[test]
4107    fn a_later_empty_assignment_unsets_an_earlier_one() {
4108        let dir = tempfile::tempdir().unwrap();
4109        let home = dir.path();
4110        std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
4111        std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
4112        std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
4113        let home_s = home.to_str().unwrap().to_string();
4114        let env = env_of(&[("HOME", &home_s)]);
4115        let loaded = Dotenv::load(&env, Some("work")).unwrap();
4116        assert_eq!(loaded.files.len(), 2);
4117        assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
4118    }
4119
4120    /// The shipped `.env` is a directory of what can be set: every variable the build reads from
4121    /// it, nothing set, and the token the dashboard cannot invent for you.
4122    #[test]
4123    fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
4124        let text = starter_env("tok");
4125        for name in ENV_TEMPLATE {
4126            assert!(
4127                text.contains(&format!("\n{name}=")),
4128                "`{name}` is in the shipped .env"
4129            );
4130        }
4131        for line in text.lines().filter(|l| !l.starts_with('#')) {
4132            let (name, value) = line.split_once('=').expect("KEY=VALUE");
4133            if name == "ECLIPSE_WEB_AUTH_TOKEN" {
4134                assert_eq!(value, "tok", "the one value a first install cannot invent");
4135            } else {
4136                assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
4137            }
4138        }
4139    }
4140
4141    /// The classification is exhaustive against the source, not against a list beside it: a new
4142    /// `ECLIPSE_*` variable has to be decided on — shipped, shell-only, or internal — before it
4143    /// compiles past this test. Without it the shipped `.env` silently stops being complete.
4144    #[test]
4145    fn every_environment_variable_the_build_reads_is_classified() {
4146        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
4147        let mut seen = Vec::new();
4148        let mut dirs = vec![
4149            root.join("eclipse-core/src"),
4150            root.join("eclipse-cli/src"),
4151            root.join("eclipse-web/src"),
4152        ];
4153        while let Some(dir) = dirs.pop() {
4154            let Ok(entries) = std::fs::read_dir(&dir) else {
4155                continue;
4156            };
4157            for entry in entries.flatten() {
4158                let path = entry.path();
4159                if path.is_dir() {
4160                    dirs.push(path);
4161                    continue;
4162                }
4163                if path.extension().and_then(|e| e.to_str()) != Some("rs") {
4164                    continue;
4165                }
4166                let text = std::fs::read_to_string(&path).unwrap_or_default();
4167                for name in env_names(&text) {
4168                    if !seen.contains(&name) {
4169                        seen.push(name);
4170                    }
4171                }
4172            }
4173        }
4174        assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
4175        for name in &seen {
4176            let known = ENV_TEMPLATE.contains(&name.as_str())
4177                || ENV_SHELL_ONLY.contains(&name.as_str())
4178                || ENV_INTERNAL.contains(&name.as_str());
4179            assert!(
4180                known,
4181                "`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
4182            );
4183        }
4184        // And the other direction: a name in the template has to be one something acts on — read
4185        // by the build, or interpolated by the config the build ships. A variable nobody consumes
4186        // is a line in a secrets file that does nothing, which reads as a setting that is broken.
4187        let shipped = starter();
4188        for name in ENV_TEMPLATE {
4189            let read = seen.iter().any(|s| s == name);
4190            let interpolated = shipped.contains(&format!("${{{name}"));
4191            assert!(
4192                read || interpolated,
4193                "`{name}` is in the shipped .env and nothing reads or interpolates it"
4194            );
4195        }
4196    }
4197
4198    /// The manual's environment table and the `.env` template describe the same set: a name in
4199    /// one and not the other is either a variable nobody can look up or a paragraph about a
4200    /// variable that does not exist.
4201    #[test]
4202    fn every_classified_variable_has_a_description() {
4203        let classified: Vec<&str> = ENV_TEMPLATE
4204            .iter()
4205            .chain(ENV_SHELL_ONLY)
4206            .chain(ENV_INTERNAL)
4207            .copied()
4208            .collect();
4209        for name in &classified {
4210            assert!(
4211                !env_about(name).is_empty(),
4212                "`{name}` is classified and has no line in ENV_ABOUT"
4213            );
4214        }
4215        for (name, about) in ENV_ABOUT {
4216            assert!(
4217                classified.contains(name),
4218                "ENV_ABOUT explains `{name}`, which the build does not read"
4219            );
4220            assert!(
4221                about.len() > 30 && !about.ends_with('.'),
4222                "one sentence, no full stop: {about}"
4223            );
4224        }
4225    }
4226
4227    /// Every `"ECLIPSE_…"` literal in a source file, quoted form only (a doc comment naming one is
4228    /// prose, not a read).
4229    fn env_names(text: &str) -> Vec<String> {
4230        let mut out = Vec::new();
4231        let mut rest = text;
4232        while let Some(at) = rest.find("\"ECLIPSE_") {
4233            let after = &rest[at + 1..];
4234            let Some(end) = after.find('"') else {
4235                break;
4236            };
4237            let name = &after[..end];
4238            // A name, not a prefix: `"ECLIPSE_"` used to build one at run time ends in an
4239            // underscore, and this scanner's own search literal is in the tree it scans.
4240            let complete = name
4241                .chars()
4242                .last()
4243                .is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
4244            if complete
4245                && name
4246                    .chars()
4247                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4248            {
4249                out.push(name.to_string());
4250            }
4251            rest = &after[end + 1..];
4252        }
4253        out
4254    }
4255
4256    #[test]
4257    fn an_empty_optional_string_loads_as_unset() {
4258        // The shipped spelling of a secret is `${VAR:-}`, which resolves to "" when the variable
4259        // is absent — and "" has to mean "no secret", not "an empty one".
4260        let c = Config::from_toml_str(
4261            "[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
4262        )
4263        .unwrap();
4264        assert_eq!(c.provider.api_key, None);
4265        assert_eq!(c.provider.api_key_env, None);
4266        assert_eq!(c.web.auth_token, None);
4267        // A path is not an option and "" is already its absent state.
4268        assert_eq!(c.provider.model, "m");
4269        // The shipped spelling is `${VAR:-}`, and that resolves through the *loader* — an absent
4270        // variable is no key, not the string with the braces left in it.
4271        let dir = tempfile::tempdir().unwrap();
4272        let path = dir.path().join("config.toml");
4273        std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
4274        let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
4275        assert_eq!(
4276            from_var.provider.api_key, None,
4277            "an absent variable is no key"
4278        );
4279    }
4280
4281    /// The file ships every setting and no prose, and it is the schema's own file: the assertion
4282    /// is against the catalogue, not against a list written here, so a field added to a struct
4283    /// cannot reach this build without reaching the next install's config.
4284    #[test]
4285    fn the_starter_config_carries_every_setting_the_build_reads() {
4286        let text = starter();
4287        let c = parse_text(&text).unwrap();
4288        let settings = Config::default().settings();
4289        assert!(
4290            settings.len() > 80,
4291            "the catalogue is the yardstick: {settings:?}"
4292        );
4293        for setting in &settings {
4294            let key = setting.key.clone();
4295            let present = text.lines().any(|l| {
4296                l.trim_start_matches("# ")
4297                    .trim_start()
4298                    .starts_with(&format!("{key} ="))
4299            });
4300            assert!(
4301                present,
4302                "[{}] `{key}` is missing from the shipped file:\n{text}",
4303                setting.section
4304            );
4305        }
4306        // No prose: the header is three lines, and every other comment is a `key =` that is not
4307        // in use. A paragraph in this file is the thing the manual exists to replace.
4308        for line in text.lines().filter(|l| l.starts_with('#')) {
4309            assert!(
4310                line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
4311                "a comment in the settings file should be a key, not a sentence: {line}"
4312            );
4313        }
4314        let prose = text
4315            .lines()
4316            .filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
4317            .count();
4318        assert!(prose <= 3, "only the three header lines: {prose}");
4319        // It loads, and the hooks block it writes is the order this build actually defaults to.
4320        assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
4321        assert_eq!(c.hooks.order, Config::default().hooks.order);
4322        assert!(c.hooks.settings.contains_key("redact-secrets"));
4323        crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
4324        assert!(
4325            !c.hooks.settings.contains_key("recall-sessions"),
4326            "a settings table for a hook that is not in `order` cannot run"
4327        );
4328        // And every key in it is one the build reads: a config that answers "nothing reads this"
4329        // about its own file is a config that teaches people to ignore the checker.
4330        let value: toml::Value = toml::from_str(&text).unwrap();
4331        let unknown = c.unknown_keys(&value);
4332        assert!(
4333            unknown.is_empty(),
4334            "unknown keys in the shipped file: {unknown:?}"
4335        );
4336        assert_eq!(
4337            c.config_version, CONFIG_VERSION,
4338            "the file stamps its shape"
4339        );
4340    }
4341
4342    /// `#539`: an `[[mcp]]` entry keeps its endpoint under the bare key `url`, which `is_url_key` did
4343    /// not match — so basic-auth userinfo and a `?token=` went into a printout documented as safe to
4344    /// paste into an issue.
4345    #[test]
4346    fn config_show_scrubs_credentials_carried_in_an_mcp_url() {
4347        let c = Config::from_toml_str(
4348            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\n\n\
4349             [[mcp]]\nname = \"gh\"\ntransport = \"http\"\n\
4350             url = \"https://user:pw@example.test/mcp?token=abc&limit=5\"\n\n\
4351             [[mcp]]\nname = \"plain\"\ntransport = \"http\"\n\
4352             url = \"https://example.test/mcp\"\n",
4353        )
4354        .unwrap();
4355        let shown = c.to_toml_redacted().unwrap();
4356        assert!(!shown.contains("pw"), "the password is gone: {shown}");
4357        assert!(!shown.contains("abc"), "the token is gone: {shown}");
4358        assert!(
4359            shown.contains("https://<redacted>@example.test/mcp"),
4360            "the shape is kept, the credentials are not: {shown}"
4361        );
4362        assert!(
4363            shown.contains("token=<redacted>"),
4364            "the parameter name stays, its value does not: {shown}"
4365        );
4366        assert!(
4367            shown.contains("limit=5"),
4368            "a parameter that is not a secret is not touched: {shown}"
4369        );
4370        assert!(
4371            shown.contains("url = \"https://example.test/mcp\""),
4372            "an endpoint with no credentials in it reads exactly as written: {shown}"
4373        );
4374    }
4375
4376    #[test]
4377    fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
4378        let c = load_hooks(
4379            "[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
4380        )
4381        .unwrap();
4382        let shown = c.to_toml_redacted().unwrap();
4383        let again = Config::from_toml_str(&shown).unwrap();
4384        assert_eq!(again.hooks, c.hooks);
4385    }
4386
4387    #[test]
4388    fn defaults_have_no_endpoint_or_key() {
4389        let c = Config::default();
4390        assert!(c.provider.base_url.is_empty());
4391        assert!(c.provider.api_key.is_none());
4392        assert!(c.require_provider().is_err());
4393        // The file tools confine every path themselves, so the default is not to ask; the shell
4394        // asks, but only about commands that cannot be undone.
4395        assert_eq!(c.tools.write_file, Policy::Allow);
4396        assert_eq!(c.tools.shell, Policy::Ask);
4397        assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
4398    }
4399
4400    #[test]
4401    fn cli_section_defaults_and_parses() {
4402        // Absent: the documented defaults, and `None` meaning "decide from the stream".
4403        let d = Config::from_toml_str("").unwrap().cli;
4404        assert_eq!(d.color, None);
4405        assert_eq!(d.markdown, None);
4406        assert_eq!(d.approval, Approval::Ask);
4407        assert_eq!(d.history_size, 1000);
4408
4409        let c = Config::from_toml_str(
4410            "[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
4411        )
4412        .unwrap()
4413        .cli;
4414        assert_eq!(c.color, Some(false));
4415        assert_eq!(c.markdown, Some(true));
4416        assert_eq!(c.approval, Approval::Auto);
4417        assert_eq!(c.history_size, 50);
4418    }
4419
4420    #[test]
4421    fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
4422        // Guessing here would mean either prompting someone who asked not to be prompted, or
4423        // not prompting someone who asked to be. Refuse instead.
4424        let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
4425        assert!(err.contains("approval"), "{err}");
4426    }
4427
4428    #[test]
4429    fn web_section_parses_its_ttl_and_default_profile() {
4430        let d = Config::from_toml_str("").unwrap().web;
4431        assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
4432        assert_eq!(d.default_profile, None);
4433
4434        let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
4435            .unwrap()
4436            .web;
4437        assert_eq!(w.session_ttl_hours, 1);
4438        assert_eq!(w.default_profile.as_deref(), Some("work"));
4439    }
4440
4441    /// A `config.toml` on its own has to load: copying the starter file to another host, or
4442    /// losing `.env`, must not take every command down behind a dashboard credential. The token
4443    /// loads empty and only the dashboard refuses it.
4444    #[test]
4445    fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
4446        let dir = tempfile::tempdir().unwrap();
4447        let path = dir.path().join("config.toml");
4448        std::fs::write(&path, starter()).unwrap();
4449        // `|_| None` is the whole environment: nothing set, and no config dir to find a `.env`
4450        // in, which is exactly what a copied file sees on a new machine.
4451        let c = Config::load_with(Some(&path), &|_| None)
4452            .expect("the starter config loads with no .env at all");
4453        assert_eq!(
4454            c.web.auth_token, None,
4455            "an unset token loads as no token, not as a load error and not as an empty secret"
4456        );
4457        assert_eq!(c.provider.model, Config::default().provider.model);
4458    }
4459
4460    #[test]
4461    fn starter_config_parses_and_matches_defaults() {
4462        let c = Config::from_toml_str(&starter()).unwrap();
4463        let d = Config::default();
4464        assert_eq!(c.tools.read_file, d.tools.read_file);
4465        assert_eq!(c.tools.fetch, d.tools.fetch);
4466        assert_eq!(c.web.port, d.web.port);
4467        assert!(c.provider.base_url.is_empty());
4468    }
4469
4470    #[test]
4471    fn partial_file_fills_defaults() {
4472        let c = Config::from_toml_str(
4473            "[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
4474        )
4475        .unwrap();
4476        assert_eq!(c.provider.base_url, "http://x/v1");
4477        assert_eq!(c.tools.shell, Policy::Deny);
4478        assert_eq!(c.tools.write_file, Policy::Allow);
4479        assert_eq!(
4480            c.agent.max_iterations,
4481            usize::MAX,
4482            "no cap unless the box asks for one"
4483        );
4484        assert!(c.require_provider().is_ok());
4485
4486        for word in ["unlimited", "none", "inf", "0", "-1"] {
4487            let raw = format!("[agent]\nmax_iterations = {word}\n");
4488            let raw = if word.parse::<i64>().is_ok() {
4489                raw
4490            } else {
4491                format!("[agent]\nmax_iterations = \"{word}\"\n")
4492            };
4493            let c = Config::from_toml_str(&raw).unwrap();
4494            assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
4495        }
4496
4497        let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
4498        assert_eq!(c.agent.max_iterations, 12, "a number is a cap");
4499
4500        let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
4501        let printed = toml::to_string(&words).unwrap();
4502        assert!(
4503            printed.contains("max_iterations = \"unlimited\""),
4504            "the schema says the word, not a length: {printed}"
4505        );
4506
4507        let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
4508        assert!(
4509            refused.is_err(),
4510            "a word that is not one of ours is an error"
4511        );
4512    }
4513
4514    #[test]
4515    fn unknown_policy_is_rejected() {
4516        assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
4517    }
4518
4519    #[test]
4520    fn env_overrides_file() {
4521        let dir = tempfile::tempdir().unwrap();
4522        let p = dir.path().join("c.toml");
4523        std::fs::write(
4524            &p,
4525            "[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
4526        )
4527        .unwrap();
4528        let env = env_of(&[
4529            ("ECLIPSE_BASE_URL", "http://env/v1"),
4530            ("ECLIPSE_API_KEY", "env-key"),
4531        ]);
4532        let c = Config::load_with(Some(&p), &env).unwrap();
4533        assert_eq!(c.provider.base_url, "http://env/v1");
4534        assert_eq!(c.provider.model, "file-model");
4535        assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
4536    }
4537
4538    #[test]
4539    fn api_key_env_indirection() {
4540        let env = env_of(&[("MY_KEY", "secret")]);
4541        let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
4542        c.apply_env(&env);
4543        assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
4544    }
4545
4546    #[test]
4547    fn debug_redacts_api_key() {
4548        let mut c = Config::default();
4549        c.provider.api_key = Some("hunter2".into());
4550        assert!(!format!("{c:?}").contains("hunter2"));
4551    }
4552
4553    #[test]
4554    fn debug_and_redacted_toml_hide_web_token() {
4555        let mut c = Config::default();
4556        c.web.auth_token = Some("s3cret-token-value".into());
4557        assert!(!format!("{c:?}").contains("s3cret"));
4558        assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
4559    }
4560
4561    /// `Config` derives `Debug` and holds the loaded `.env`; the values in it are the whole point of
4562    /// the file. `config show` was safe, `{cfg:?}` was not — and a panic message or a failing
4563    /// `assert_eq!` is exactly where it would have gone out.
4564    #[test]
4565    fn debug_never_prints_a_dotenv_value() {
4566        let dir = tempfile::tempdir().unwrap();
4567        let root = dir.path().join("root");
4568        std::fs::create_dir_all(&root).unwrap();
4569        std::fs::write(
4570            root.join(".env"),
4571            "ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
4572        )
4573        .unwrap();
4574        let cfg_path = root.join("config.toml");
4575        std::fs::write(
4576            &cfg_path,
4577            "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
4578        )
4579        .unwrap();
4580        let env = env_of(&[
4581            ("ECLIPSE_HOME", root.to_str().unwrap()),
4582            ("HOME", dir.path().to_str().unwrap()),
4583        ]);
4584
4585        let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4586        let debug = format!("{cfg:?}");
4587        assert!(
4588            !debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
4589            "the .env values must never be printed: {debug}"
4590        );
4591        assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
4592        assert!(debug.contains("Dotenv"), "{debug}");
4593        // And the token reached the provider, so this is a real loaded .env, not an empty one.
4594        assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
4595    }
4596
4597    #[test]
4598    fn redacted_toml_hides_key_and_round_trips() {
4599        let mut c = Config::default();
4600        c.provider.api_key = Some("hunter2".into());
4601        c.provider.model = "m".into();
4602        let t = c.to_toml_redacted().unwrap();
4603        assert!(!t.contains("hunter2"));
4604        assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
4605    }
4606
4607    /// The update track is a word in the file and a branch in the code: `release` and `main` are
4608    /// one ref, which is why the key names a track. A word this build does not know is a parse
4609    /// error, never a silent fall back to the release track.
4610    #[test]
4611    fn the_update_track_names_a_branch_and_takes_two_words() {
4612        assert_eq!(Config::default().update.track, Track::Release);
4613        assert_eq!(Track::Release.branch(), "main");
4614        assert_eq!(Track::Develop.branch(), "develop");
4615        let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
4616        assert_eq!(cfg.update.track, Track::Develop);
4617        assert_eq!(cfg.update.track.label(), "develop");
4618        let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
4619            .unwrap_err()
4620            .to_string();
4621        assert!(
4622            err.contains("main") && err.contains("develop"),
4623            "the refusal lists the words it takes: {err}"
4624        );
4625    }
4626
4627    /// A URL is printed as it is, because that is how you check what you configured — but a URL can
4628    /// carry a secret, and both legitimate spellings were printed verbatim by `config show`.
4629    #[test]
4630    fn a_url_keeps_its_shape_and_loses_its_secrets() {
4631        let mut c = Config::default();
4632        c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
4633        c.update.remote =
4634            Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
4635        c.update.releases = Some("https://mirror.internal/api#frag".into());
4636
4637        let t = c.to_toml_redacted().unwrap();
4638        assert!(
4639            !t.contains("hunter2") && !t.contains("abc123"),
4640            "the secrets are gone: {t}"
4641        );
4642        // The shape survives: scheme, host, path, and the *names* of the parameters.
4643        assert!(
4644            t.contains("https://<redacted>@gw.internal/v1"),
4645            "the userinfo is replaced, not the URL: {t}"
4646        );
4647        assert!(
4648            t.contains("access_token=<redacted>&page=2"),
4649            "the secret parameter keeps its name and loses its value: {t}"
4650        );
4651        assert!(t.contains("https://mirror.internal/api#frag"), "{t}");
4652
4653        // And the same URL is not the one place a secret survives: `{cfg:?}` scrubs it too.
4654        let debug = format!("{c:?}");
4655        assert!(!debug.contains("hunter2"), "{debug}");
4656
4657        // A URL with nothing secret in it is left exactly as written.
4658        let plain = Config::default();
4659        assert!(plain
4660            .to_toml_redacted()
4661            .unwrap()
4662            .contains(&plain.provider.base_url));
4663    }
4664
4665    #[test]
4666    fn one_root_layout() {
4667        // One directory, everything in it. Deliberately not XDG: the reason is in `home_root`.
4668        let env = env_of(&[("HOME", "/home/u")]);
4669        assert_eq!(
4670            config_path(&env).unwrap(),
4671            PathBuf::from("/home/u/.eclipse/config.toml")
4672        );
4673        assert_eq!(
4674            Config::default().sessions_dir(&env).unwrap(),
4675            PathBuf::from("/home/u/.eclipse/state/sessions")
4676        );
4677        assert_eq!(
4678            Config::default().memory_dir(&env).unwrap(),
4679            PathBuf::from("/home/u/.eclipse/memory")
4680        );
4681        // XDG is not consulted, even when it is set: two roots is the thing this layout exists
4682        // to prevent, and honouring XDG "sometimes" would be the worst of both.
4683        let env = env_of(&[
4684            ("HOME", "/home/u"),
4685            ("XDG_CONFIG_HOME", "/x/cfg"),
4686            ("XDG_STATE_HOME", "/x/state"),
4687        ]);
4688        assert_eq!(
4689            config_path(&env).unwrap(),
4690            PathBuf::from("/home/u/.eclipse/config.toml")
4691        );
4692        // ECLIPSE_HOME is the one way to move it.
4693        let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
4694        assert_eq!(
4695            config_path(&env).unwrap(),
4696            PathBuf::from("/opt/ecl/config.toml")
4697        );
4698    }
4699
4700    #[test]
4701    fn missing_default_file_is_ok_but_explicit_missing_is_error() {
4702        let dir = tempfile::tempdir().unwrap();
4703        let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
4704        assert!(Config::load_with(None, &env).is_ok());
4705        assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
4706    }
4707
4708    #[test]
4709    fn auto_prune_is_off_by_default_and_can_be_enabled() {
4710        assert!(!Config::default().sessions.auto_prune);
4711        let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
4712            .unwrap();
4713        assert!(c.sessions.auto_prune);
4714        assert_eq!(c.sessions.retention_keep_count, 5);
4715    }
4716
4717    #[test]
4718    fn sessions_dir_expands_tilde() {
4719        let env = env_of(&[("HOME", "/home/u")]);
4720        let mut c = Config::default();
4721        c.sessions.dir = Some("~/s".into());
4722        assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
4723    }
4724
4725    #[test]
4726    fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
4727        let dir = tempfile::tempdir().unwrap();
4728        let p = dir.path().join("a/b/config.toml");
4729        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4730        let report = write_starter_config(&p, false, &env).unwrap();
4731        assert!(report.dotenv_written);
4732        assert_eq!(
4733            report.dotenv,
4734            dir.path().join(".env"),
4735            "the .env goes where the loader reads it, not beside a config elsewhere"
4736        );
4737
4738        let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
4739        let token = dotenv
4740            .lines()
4741            .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4742            .expect("the token lives in .env");
4743        assert_eq!(token.len(), 64, "a generated token, not a placeholder");
4744        assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
4745        assert!(
4746            !std::fs::read_to_string(&p).unwrap().contains(token),
4747            "the config carries the reference, never the secret"
4748        );
4749
4750        #[cfg(unix)]
4751        {
4752            use std::os::unix::fs::PermissionsExt;
4753            for f in [&p, &report.dotenv] {
4754                assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
4755            }
4756        }
4757
4758        // End to end: the value is resolvable through the chain the loader uses. The config
4759        // has to sit where the loader looks, or its `.env` is a different file's.
4760        let root = dir.path().join("root");
4761        let cfg_dir = root.clone();
4762        std::fs::create_dir_all(&cfg_dir).unwrap();
4763        let real = cfg_dir.join("config.toml");
4764        let env = env_of(&[
4765            ("ECLIPSE_HOME", root.to_str().unwrap()),
4766            ("HOME", dir.path().to_str().unwrap()),
4767        ]);
4768        let written = write_starter_config(&real, false, &env).unwrap();
4769        let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
4770        let token = std::fs::read_to_string(&written.dotenv)
4771            .unwrap()
4772            .lines()
4773            .find_map(|l| {
4774                l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
4775                    .map(str::to_string)
4776            })
4777            .unwrap();
4778        assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
4779        assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
4780    }
4781
4782    /// A `.env` line with no value is a half-typed line, not a setting: every other layer treats
4783    /// empty as absent, and the loader used to hand the raw empty string through — which blanked the
4784    /// key the config file already had and made requests go out unauthenticated.
4785    #[test]
4786    fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
4787        let dir = tempfile::tempdir().unwrap();
4788        let root = dir.path().join("root");
4789        std::fs::create_dir_all(&root).unwrap();
4790        std::fs::write(
4791            root.join(".env"),
4792            "ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
4793        )
4794        .unwrap();
4795        let cfg_path = root.join("config.toml");
4796        std::fs::write(
4797            &cfg_path,
4798            "[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
4799             base_url = \"http://127.0.0.1:9999/v1\"\n",
4800        )
4801        .unwrap();
4802        let env = env_of(&[
4803            ("ECLIPSE_HOME", root.to_str().unwrap()),
4804            ("HOME", dir.path().to_str().unwrap()),
4805        ]);
4806
4807        let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4808        assert_eq!(
4809            cfg.provider.api_key.as_deref(),
4810            Some("sk-from-the-file"),
4811            "an empty .env value must not blank the key"
4812        );
4813        assert_eq!(cfg.provider.model, "keep-me", "nor the model");
4814        assert_eq!(
4815            cfg.provider.base_url, "http://127.0.0.1:9999/v1",
4816            "nor the base URL"
4817        );
4818    }
4819
4820    #[test]
4821    fn context_files_are_seeded_and_existing_ones_are_kept() {
4822        let tmp = tempfile::tempdir().unwrap();
4823        let memory = tmp.path().join("memory");
4824        let created = seed_context_files(&memory).unwrap();
4825        assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
4826        assert!(memory.join("AGENT.md").exists());
4827        assert!(memory.join("USER.md").exists());
4828        assert!(memory.join("MEMORY.md").exists());
4829        assert_eq!(
4830            std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
4831            ""
4832        );
4833
4834        // Re-run: nothing is overwritten.
4835        let created = seed_context_files(&memory).unwrap();
4836        assert!(
4837            created.is_empty(),
4838            "existing files are left alone: {created:?}"
4839        );
4840
4841        // All three hold an operator's text, not just the one this test used to check: a rewrite
4842        // of a starter is the failure mode (#295), so the assertion has to be byte for byte on
4843        // every file that can carry a person's words.
4844        let written = [
4845            ("AGENT.md", "run make, no cargo test\n"),
4846            ("USER.md", "I am the operator; keep it short\n"),
4847            ("MEMORY.md", "- one durable fact\n"),
4848        ];
4849        for (name, body) in written {
4850            std::fs::write(memory.join(name), body).unwrap();
4851        }
4852        let created = seed_context_files(&memory).unwrap();
4853        assert!(created.is_empty(), "{created:?}");
4854        for (name, body) in written {
4855            assert_eq!(
4856                std::fs::read_to_string(memory.join(name)).unwrap(),
4857                body,
4858                "{name} was rewritten"
4859            );
4860        }
4861    }
4862
4863    /// "Once" is a fact about a directory, not about a process or an install: a profile whose
4864    /// `memory/` has the files is left alone exactly as the base install is, and a profile that
4865    /// has never been used is a first install and gets the starters. Seeding one must not touch
4866    /// the other, which is what makes it safe for `setup` to run against any profile (#295).
4867    #[test]
4868    fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
4869        let tmp = tempfile::tempdir().unwrap();
4870        let base = tmp.path().join("memory");
4871        let lived_in = tmp.path().join("profiles/work/memory");
4872        let fresh = tmp.path().join("profiles/lab/memory");
4873
4874        assert_eq!(seed_context_files(&base).unwrap().len(), 3);
4875        std::fs::write(base.join("USER.md"), "the operator\n").unwrap();
4876
4877        std::fs::create_dir_all(&lived_in).unwrap();
4878        for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4879            std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
4880        }
4881
4882        assert!(
4883            seed_context_files(&lived_in).unwrap().is_empty(),
4884            "an existing profile's files are not rewritten"
4885        );
4886        assert_eq!(
4887            seed_context_files(&fresh).unwrap().len(),
4888            3,
4889            "a profile that has never been used is a first install"
4890        );
4891
4892        assert_eq!(
4893            std::fs::read_to_string(base.join("USER.md")).unwrap(),
4894            "the operator\n"
4895        );
4896        for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4897            assert_eq!(
4898                std::fs::read_to_string(lived_in.join(name)).unwrap(),
4899                format!("{name} as it was lived in\n")
4900            );
4901        }
4902    }
4903
4904    /// `--config /other/config.toml`: the config is there, the secrets are in the config
4905    /// directory. Writing the `.env` beside the config put it where no start would ever read it —
4906    /// `config init` reported a dashboard token that the next launch did not have.
4907    #[test]
4908    fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
4909        let dir = tempfile::tempdir().unwrap();
4910        let home = dir.path().join("home");
4911        std::fs::create_dir_all(&home).unwrap();
4912        let elsewhere = dir.path().join("other");
4913        let path = elsewhere.join("config.toml");
4914        let env = env_of(&[
4915            ("ECLIPSE_HOME", home.to_str().unwrap()),
4916            ("HOME", dir.path().to_str().unwrap()),
4917        ]);
4918
4919        let report = write_starter_config(&path, false, &env).unwrap();
4920        let token = std::fs::read_to_string(&report.dotenv)
4921            .unwrap()
4922            .lines()
4923            .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4924            .expect("the token lives in .env")
4925            .to_string();
4926        assert_eq!(report.dotenv, home.join(".env"));
4927
4928        let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
4929        assert_eq!(
4930            cfg.web.auth_token.as_deref(),
4931            Some(token.as_str()),
4932            "the token `config init` reported is the token the next start reads"
4933        );
4934    }
4935
4936    #[test]
4937    fn config_init_refuses_to_overwrite_a_config_without_force() {
4938        let dir = tempfile::tempdir().unwrap();
4939        let p = dir.path().join("c/config.toml");
4940        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4941        write_starter_config(&p, false, &env).unwrap();
4942        assert!(write_starter_config(&p, false, &env).is_err());
4943    }
4944
4945    #[test]
4946    fn config_init_never_overwrites_an_existing_dotenv() {
4947        let dir = tempfile::tempdir().unwrap();
4948        let p = dir.path().join("d/config.toml");
4949        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4950        let first = write_starter_config(&p, false, &env).unwrap();
4951        let before = std::fs::read_to_string(&first.dotenv).unwrap();
4952
4953        // `--force` replaces the config. It is not consent to lose the user's secrets.
4954        let again = write_starter_config(&p, true, &env).unwrap();
4955        assert!(!again.dotenv_written);
4956        assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
4957    }
4958
4959    #[test]
4960    fn a_profile_overlay_merges_over_the_base_config() {
4961        let tmp = tempfile::tempdir().unwrap();
4962        let home = tmp.path().join("home");
4963        let cfg_dir = home.join(".eclipse");
4964        std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
4965        std::fs::write(
4966            cfg_dir.join("config.toml"),
4967            "[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
4968             temperature = 0.2\n[agent]\nmax_iterations = 7\n",
4969        )
4970        .unwrap();
4971        std::fs::write(
4972            cfg_dir.join("profiles/work/config.toml"),
4973            "[provider]\nmodel = \"work-model\"\n",
4974        )
4975        .unwrap();
4976        let env = env_of(&[("HOME", home.to_str().unwrap())]);
4977
4978        let base = Config::load_with(None, &env).unwrap();
4979        assert_eq!(base.provider.model, "base-model");
4980        assert_eq!(base.profile_name(), "default");
4981
4982        let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
4983        // The overlay replaced one key and left its siblings alone.
4984        assert_eq!(work.provider.model, "work-model");
4985        assert_eq!(work.provider.base_url, "http://base/v1");
4986        assert_eq!(work.provider.temperature, Some(0.2));
4987        assert_eq!(work.agent.max_iterations, 7);
4988        assert_eq!(work.profile_name(), "work");
4989        // Same config file, different state.
4990        assert_eq!(
4991            work.sessions_dir(&env).unwrap(),
4992            home.join(".eclipse/profiles/work/state/sessions")
4993        );
4994        assert_eq!(
4995            base.sessions_dir(&env).unwrap(),
4996            home.join(".eclipse/state/sessions")
4997        );
4998        assert_eq!(
4999            work.state_dir(&env).unwrap(),
5000            home.join(".eclipse/profiles/work/state")
5001        );
5002    }
5003
5004    #[test]
5005    fn the_profile_comes_from_the_environment_and_the_argument_wins() {
5006        let tmp = tempfile::tempdir().unwrap();
5007        let home = tmp.path().join("home");
5008        std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
5009        std::fs::write(
5010            home.join(".eclipse/profiles/env/config.toml"),
5011            "[agent]\nmax_iterations = 3\n",
5012        )
5013        .unwrap();
5014        let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
5015        let from_env = Config::load_with(None, &env).unwrap();
5016        assert_eq!(from_env.profile_name(), "env");
5017        assert_eq!(from_env.agent.max_iterations, 3);
5018
5019        let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
5020        assert_eq!(explicit.profile_name(), "other");
5021        // No overlay for "other": the base defaults apply, which is no cap at all.
5022        assert_eq!(explicit.agent.max_iterations, usize::MAX);
5023    }
5024
5025    #[test]
5026    fn the_default_profile_keeps_the_plain_state_directory() {
5027        let env = env_of(&[("HOME", "/home/u")]);
5028        assert_eq!(
5029            state_dir_for(&env, Some("default")).unwrap(),
5030            PathBuf::from("/home/u/.eclipse/state")
5031        );
5032        assert_eq!(
5033            state_dir_for(&env, None).unwrap(),
5034            PathBuf::from("/home/u/.eclipse/state")
5035        );
5036        assert_eq!(
5037            state_dir_for(&env, Some("work")).unwrap(),
5038            PathBuf::from("/home/u/.eclipse/profiles/work/state")
5039        );
5040    }
5041
5042    #[test]
5043    fn a_profile_name_must_be_a_safe_directory_name() {
5044        for bad in ["", "../etc", "a/b", "sp ace"] {
5045            assert!(
5046                validate_profile_name(bad).is_err(),
5047                "{bad:?} should be rejected"
5048            );
5049        }
5050        assert!(validate_profile_name("work-2026_x").is_ok());
5051        let env = env_of(&[("HOME", "/home/u")]);
5052        assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
5053    }
5054
5055    #[test]
5056    fn plugin_directories_put_the_profile_first() {
5057        let tmp = tempfile::tempdir().unwrap();
5058        let home = tmp.path().join("home");
5059        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
5060        let env = env_of(&[("HOME", home.to_str().unwrap())]);
5061        let mut cfg = Config::default();
5062        let default_dirs = cfg.plugins_dirs(&env);
5063        assert_eq!(
5064            default_dirs,
5065            vec![home.join(".eclipse/plugins")],
5066            "the default profile has no profile plugin dir"
5067        );
5068
5069        cfg.profile = Some("work".into());
5070        let dirs = cfg.plugins_dirs(&env);
5071        assert_eq!(dirs.len(), 2);
5072        assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
5073        assert_eq!(dirs[1], home.join(".eclipse/plugins"));
5074
5075        cfg.plugins.dir = Some("~/elsewhere/plugins".into());
5076        assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
5077    }
5078
5079    #[test]
5080    fn plugins_are_off_until_named() {
5081        let cfg = Config::default();
5082        assert!(cfg.plugins.enabled.is_empty());
5083        assert!(cfg.plugins.dir.is_none());
5084        let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
5085        assert_eq!(parsed.plugins.enabled, ["a", "b"]);
5086    }
5087
5088    // ---- editing a config file in place (what `eclipse setup` does) ----------------------
5089
5090    #[test]
5091    fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
5092        let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
5093        let text = toml_set_string(&text, "provider", "model", "some-model");
5094        assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
5095        assert!(text.contains("model = \"some-model\""), "{text}");
5096        // The shipped file is what a person reads and edits: nothing else may move.
5097        assert!(text.contains("# Every setting this build reads"));
5098        assert!(text.contains("[agent]"));
5099        assert!(
5100            !text.contains("base_url = \"\""),
5101            "the empty blank must be gone: {text}"
5102        );
5103        // And it is still a config the real loader accepts.
5104        let cfg: Config = toml::from_str(&text).expect("edited config must parse");
5105        assert_eq!(cfg.provider.base_url, "http://h:1/v1");
5106        assert_eq!(cfg.provider.model, "some-model");
5107    }
5108
5109    #[test]
5110    fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
5111        let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
5112        assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
5113        assert_eq!(
5114            text.matches("\nprofile = ").count(),
5115            1,
5116            "no duplicate key (the commented [web] default_profile is a different key): {text}"
5117        );
5118        let cfg: Config = toml::from_str(&text).unwrap();
5119        assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
5120    }
5121
5122    #[test]
5123    fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
5124        // `[sessions] dir` and `[plugins] dir` both exist; only the one asked for may change.
5125        let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
5126        let cfg: Config = toml::from_str(&text).unwrap();
5127        assert_eq!(
5128            cfg.sessions.dir.as_deref(),
5129            Some(std::path::Path::new("/tmp/sessions-here"))
5130        );
5131        assert_eq!(cfg.plugins.dir, None, "{text}");
5132    }
5133
5134    #[test]
5135    fn setting_a_key_in_a_missing_section_adds_the_section() {
5136        let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
5137        let cfg: Config = toml::from_str(&text).unwrap();
5138        assert_eq!(cfg.web.host, "0.0.0.0");
5139        assert_eq!(cfg.agent.max_iterations, 5);
5140    }
5141
5142    #[test]
5143    fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
5144        let text = starter();
5145        assert_eq!(
5146            toml_value(&text, "provider", "base_url"),
5147            Some(String::new())
5148        );
5149        // An absent-by-default key is present in the file *as a comment*, and reads as unset:
5150        // nothing is imposed by shipping the key, which is the whole point of the two kinds of
5151        // line. `config set` is what turns one into a value.
5152        assert_eq!(toml_value(&text, "provider", "temperature"), None);
5153        assert!(text.contains("# temperature ="), "{text}");
5154        assert_eq!(
5155            toml_value(&text, "agent", "max_iterations"),
5156            Some("unlimited".to_string()),
5157            "the cap is written, and its off value is the word `unlimited`"
5158        );
5159    }
5160
5161    /// `#538`: `read_to_string(..).unwrap_or_default()` collapsed every read error into "no file", so
5162    /// the write that followed replaced `.env` with a single line. A directory at the path is the one
5163    /// read error a test can produce without caring whether it runs as root.
5164    #[test]
5165    fn a_dotenv_that_cannot_be_read_is_not_treated_as_an_empty_one() {
5166        let dir = tempfile::tempdir().unwrap();
5167        let dotenv = dir.path().join(".env");
5168        std::fs::create_dir(&dotenv).unwrap();
5169        std::fs::write(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN"), "still here").unwrap();
5170
5171        let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap_err();
5172        let said = err.to_string();
5173        assert!(
5174            said.contains("nothing was written"),
5175            "the refusal says the file is untouched: {said}"
5176        );
5177        assert!(
5178            dotenv.is_dir(),
5179            "a failed save must not have replaced the path"
5180        );
5181        assert_eq!(
5182            std::fs::read_to_string(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN")).unwrap(),
5183            "still here",
5184            "and nothing under it was touched"
5185        );
5186    }
5187
5188    /// The other half of the same defect: a value with a line break wrote a second assignment.
5189    #[test]
5190    fn a_line_break_in_a_value_is_refused_before_it_writes() {
5191        let dir = tempfile::tempdir().unwrap();
5192        let dotenv = dir.path().join(".env");
5193        std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=tok\n").unwrap();
5194
5195        let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1\nECLIPSE_ADMIN=1").unwrap_err();
5196        assert!(err.to_string().contains("second assignment"), "{err}");
5197        assert_eq!(
5198            std::fs::read_to_string(&dotenv).unwrap(),
5199            "ECLIPSE_WEB_AUTH_TOKEN=tok\n",
5200            "a refused save leaves the file byte for byte"
5201        );
5202    }
5203
5204    /// And the file that survives a save is the file the loader reads: comments, quotes, `export` and
5205    /// a duplicate key all come through untouched.
5206    #[test]
5207    fn a_save_keeps_every_other_line_and_the_loader_still_reads_them() {
5208        let dir = tempfile::tempdir().unwrap();
5209        let dotenv = dir.path().join(".env");
5210        let before = "# secrets\n\
5211                      export ECLIPSE_WEB_USER='max h'\n\
5212                      ECLIPSE_WEB_PASSWORD_HASH=\"pbkdf2$abc\"\n\
5213                      ECLIPSE_API_KEY=first\n\
5214                      ECLIPSE_API_KEY=second\n";
5215        std::fs::write(&dotenv, before).unwrap();
5216
5217        save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
5218
5219        let after = std::fs::read_to_string(&dotenv).unwrap();
5220        for line in before.lines() {
5221            assert!(after.contains(line), "{line:?} did not survive:\n{after}");
5222        }
5223        assert!(after.contains("ECLIPSE_WEB_AUTH_TOKEN=tok"), "{after}");
5224    }
5225
5226    /// `#538`: the reader answered the first duplicate, kept the quotes, and called `KEY=` a value —
5227    /// three disagreements with the loader that the same run then used.
5228    #[test]
5229    fn dotenv_var_answers_what_the_loader_answers() {
5230        let dir = tempfile::tempdir().unwrap();
5231        let dotenv = dir.path().join(".env");
5232        std::fs::write(
5233            &dotenv,
5234            "A=first\nA=second\nexport B='quoted value'\nC=\"also quoted\"\nD=\n",
5235        )
5236        .unwrap();
5237
5238        assert_eq!(
5239            dotenv_var(&dotenv, "A").as_deref(),
5240            Some("second"),
5241            "the loader is last-wins, so the reader is too"
5242        );
5243        assert_eq!(dotenv_var(&dotenv, "B").as_deref(), Some("quoted value"));
5244        assert_eq!(dotenv_var(&dotenv, "C").as_deref(), Some("also quoted"));
5245        assert_eq!(
5246            dotenv_var(&dotenv, "D"),
5247            None,
5248            "an empty value is absence, as everywhere else"
5249        );
5250        assert_eq!(dotenv_var(&dotenv, "MISSING"), None);
5251    }
5252
5253    #[test]
5254    fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
5255        let dir = tempfile::tempdir().unwrap();
5256        let cfg_path = dir.path().join("config.toml");
5257        let dotenv = dir.path().join(".env");
5258        save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
5259        save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
5260        save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
5261        save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
5262        let body = std::fs::read_to_string(&dotenv).unwrap();
5263        assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
5264        assert_eq!(
5265            dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
5266            Some("sk-2")
5267        );
5268        assert_eq!(
5269            dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
5270            Some("tok"),
5271            "an unrelated secret must survive"
5272        );
5273        #[cfg(unix)]
5274        {
5275            use std::os::unix::fs::PermissionsExt;
5276            for f in [&cfg_path, &dotenv] {
5277                let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
5278                assert_eq!(mode, 0o600, "{}", f.display());
5279            }
5280        }
5281    }
5282
5283    #[test]
5284    fn trace_content_is_off_by_default_and_can_be_set() {
5285        assert!(!Config::default().agent.trace_content);
5286        let cfg = Config::from_toml_str(
5287            "[agent]
5288trace_content = true
5289",
5290        )
5291        .unwrap();
5292        assert!(cfg.agent.trace_content);
5293    }
5294
5295    #[test]
5296    fn an_output_schema_is_absent_until_somebody_asks_for_one() {
5297        // A default schema would make every reply in a conversation have to be JSON, so there is
5298        // no default at all: it is opt-in, per install or per run.
5299        assert_eq!(Config::default().agent.output_schema, None);
5300        let cfg = Config::from_toml_str(
5301            "[agent]
5302output_schema = \"schemas/plan.json\"
5303",
5304        )
5305        .unwrap();
5306        assert_eq!(
5307            cfg.agent.output_schema.as_deref(),
5308            Some("schemas/plan.json")
5309        );
5310    }
5311
5312    #[test]
5313    fn the_user_section_has_the_defaults_the_docs_promise() {
5314        let cfg = Config::default();
5315        assert_eq!(cfg.user.file, "USER.md");
5316        assert_eq!(cfg.user.memory_file, "MEMORY.md");
5317        assert_eq!(cfg.user.memory_budget_chars, 3000);
5318        assert_eq!(
5319            cfg.agent.context_file_max_chars,
5320            crate::context_files::DEFAULT_MAX_FILE_CHARS
5321        );
5322        assert_eq!(
5323            cfg.agent.context_files_budget_chars,
5324            crate::context_files::DEFAULT_BUDGET_CHARS
5325        );
5326    }
5327
5328    #[test]
5329    fn the_context_and_memory_budgets_can_be_set_in_the_file() {
5330        let cfg = Config::from_toml_str(
5331            "[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
5332             [user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
5333        )
5334        .unwrap();
5335        assert_eq!(cfg.agent.context_file_max_chars, 100);
5336        assert_eq!(cfg.agent.context_files_budget_chars, 200);
5337        assert_eq!(cfg.user.file, "WHO.md");
5338        assert_eq!(cfg.user.memory_file, "FACTS.md");
5339        assert_eq!(cfg.user.memory_budget_chars, 50);
5340    }
5341
5342    #[test]
5343    fn the_default_profile_keeps_its_files_in_the_config_directory() {
5344        let env = |k: &str| match k {
5345            "HOME" => Some("/home/m".to_string()),
5346            _ => None,
5347        };
5348        let mut cfg = Config::default();
5349        assert_eq!(
5350            cfg.context_dir(&env),
5351            Some(PathBuf::from("/home/m/.eclipse"))
5352        );
5353        cfg.profile = Some("work".into());
5354        assert_eq!(
5355            cfg.context_dir(&env),
5356            Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
5357        );
5358    }
5359
5360    #[test]
5361    fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
5362        let env = |k: &str| match k {
5363            "HOME" => Some("/home/m".to_string()),
5364            _ => None,
5365        };
5366        let mut cfg = Config::default();
5367        assert_eq!(
5368            cfg.scripts_dir(&env),
5369            Some(PathBuf::from("/home/m/.eclipse/scripts"))
5370        );
5371        cfg.profile = Some("work".into());
5372        assert_eq!(
5373            cfg.scripts_dir(&env),
5374            Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
5375        );
5376        let no_home = |_: &str| None;
5377        assert_eq!(Config::default().scripts_dir(&no_home), None);
5378    }
5379
5380    #[test]
5381    fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
5382        let env = |k: &str| match k {
5383            "ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
5384            _ => None,
5385        };
5386        let dir = Config::default().scripts_dir(&env).unwrap();
5387        assert!(dir.is_absolute(), "{}", dir.display());
5388        assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
5389    }
5390
5391    #[test]
5392    fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5393        assert_eq!(Config::default().tools.script, Policy::Ask);
5394        let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
5395        assert_eq!(cfg.tools.script, Policy::Deny);
5396        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5397        assert_eq!(starter.tools.script, Policy::Ask);
5398        assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
5399    }
5400
5401    #[test]
5402    fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
5403        let cfg = Config::default();
5404        assert_eq!(cfg.vision.mode, VisionMode::Auto);
5405        assert_eq!(cfg.vision.route, "");
5406        assert!(!cfg.vision.allow_cloud);
5407    }
5408
5409    #[test]
5410    fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
5411        for (text, mode) in [
5412            ("native", VisionMode::Native),
5413            ("text", VisionMode::Text),
5414            ("auto", VisionMode::Auto),
5415        ] {
5416            let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
5417            assert_eq!(cfg.vision.mode, mode, "{text}");
5418        }
5419    }
5420
5421    #[test]
5422    fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
5423        let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
5424        let sentence = err.to_string();
5425        assert!(sentence.contains("telepathy"), "{sentence}");
5426        assert!(sentence.contains("native"), "{sentence}");
5427        assert!(sentence.contains("text"), "{sentence}");
5428        assert!(sentence.contains("auto"), "{sentence}");
5429    }
5430
5431    #[test]
5432    fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
5433        let cfg = Config::from_toml_str(
5434            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5435             [vision]\nroute = \"sight\"\n",
5436        )
5437        .unwrap();
5438        let err = cfg.validate_routes().unwrap_err().to_string();
5439        assert!(err.contains("vision.route"), "{err}");
5440        assert!(err.contains("sight"), "{err}");
5441        assert!(err.contains("default"), "{err}");
5442    }
5443
5444    #[test]
5445    fn a_vision_route_that_exists_validates() {
5446        let cfg = Config::from_toml_str(
5447            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5448             [vision]\nroute = \"default\"\n",
5449        )
5450        .unwrap();
5451        cfg.validate_routes().unwrap();
5452        assert_eq!(cfg.vision.route, "default");
5453    }
5454
5455    #[test]
5456    fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
5457        assert_eq!(Config::default().skills.index_budget_chars, 4000);
5458        let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
5459        assert_eq!(cfg.skills.index_budget_chars, 250);
5460        assert!(starter().contains("[skills]"));
5461        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5462        assert_eq!(starter.skills.index_budget_chars, 4000);
5463    }
5464
5465    #[test]
5466    fn the_redacted_config_shows_the_skills_section() {
5467        let mut cfg = Config::default();
5468        cfg.skills.index_budget_chars = 123;
5469        let shown = cfg.to_toml_redacted().unwrap();
5470        assert!(shown.contains("[skills]"), "{shown}");
5471        assert!(shown.contains("index_budget_chars = 123"), "{shown}");
5472    }
5473
5474    #[test]
5475    fn the_starter_writes_the_context_file_settings() {
5476        let text = starter();
5477        let cfg = Config::from_toml_str(&text).unwrap();
5478        assert_eq!(cfg.user.memory_file, "MEMORY.md");
5479        for key in ["context_files_budget_chars", "[user]", "USER.md"] {
5480            assert!(text.contains(key), "the shipped file names `{key}`");
5481        }
5482    }
5483
5484    // ---- routes (M12, slice 1) ----
5485
5486    const TWO_ROUTES: &str = "\
5487[provider]
5488fallback = [\"local\", \"big\"]
5489[[provider.route]]
5490name = \"local\"
5491base_url = \"http://127.0.0.1:8081/v1\"
5492model = \"small\"
5493[[provider.route]]
5494name = \"big\"
5495base_url = \"http://10.0.0.2:8000/v1\"
5496model = \"large\"
5497api_key = \"hunter2\"
5498timeout_secs = 30
5499";
5500
5501    fn parse(text: &str) -> Config {
5502        Config::from_toml_str(text).unwrap()
5503    }
5504
5505    fn refusal(text: &str) -> String {
5506        let c = parse(text);
5507        c.validate_routes()
5508            .and_then(|_| c.chain().map(|_| ()))
5509            .unwrap_err()
5510            .to_string()
5511    }
5512
5513    #[test]
5514    fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
5515        let c = parse(
5516            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
5517             [[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
5518        );
5519        let r = c.declared_routes();
5520        assert_eq!(
5521            r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
5522            ["default", "r"],
5523            "[provider] is the route called default"
5524        );
5525        assert_eq!(r[0].config.timeout_secs, 7);
5526        assert_eq!(
5527            r[1].config.timeout_secs, 120,
5528            "the route got the built-in default, not [provider]'s 7"
5529        );
5530    }
5531
5532    #[test]
5533    fn provider_may_be_omitted_when_fallback_names_a_route() {
5534        let c = parse(TWO_ROUTES);
5535        c.validate_routes().unwrap();
5536        let chain = c.chain().unwrap();
5537        assert_eq!(chain.source, ChainSource::Fallback);
5538        let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5539        assert_eq!(names, ["local", "big"]);
5540        assert_eq!(chain.routes[1].config.timeout_secs, 30);
5541        assert!(
5542            c.declared_routes().iter().all(|r| r.name != "default"),
5543            "no phantom default route appears"
5544        );
5545    }
5546
5547    #[test]
5548    fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
5549        // `fallback` is the whole chain. Writing a base_url into `[provider]` and then a
5550        // fallback that does not list `default` is a config where the endpoint the user typed
5551        // is never called — the sort of thing discovered later from a bill.
5552        let text = r#"
5553[provider]
5554base_url = "https://api.example.com/v1"
5555model = "gpt"
5556fallback = ["local"]
5557
5558[[provider.route]]
5559name = "local"
5560base_url = "http://127.0.0.1:8080/v1"
5561model = "qwen3-coder"
5562"#;
5563        let err = parse(text).validate_routes().unwrap_err().to_string();
5564        assert!(err.contains("would never be called"), "{err}");
5565        assert!(
5566            err.contains("Put `default` first"),
5567            "it says what to type: {err}"
5568        );
5569    }
5570
5571    #[test]
5572    fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
5573        let text = r#"
5574[provider]
5575base_url = "https://api.example.com/v1"
5576model = "gpt"
5577fallback = ["default", "local"]
5578
5579[[provider.route]]
5580name = "local"
5581base_url = "http://127.0.0.1:8080/v1"
5582model = "qwen3-coder"
5583"#;
5584        let c = parse(text);
5585        c.validate_routes().unwrap();
5586        let chain = c.chain().unwrap();
5587        let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5588        assert_eq!(names, ["default", "local"]);
5589        assert_eq!(chain.routes[0].config.model, "gpt");
5590    }
5591
5592    #[test]
5593    fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
5594        // `max_retries = 0` at provider level is a tuning key, not a server: a config that
5595        // uses only routes must not grow a `default` route with no endpoint, or every error
5596        // that lists the routes offers one that cannot be used.
5597        let text = "\
5598[provider]
5599max_retries = 0
5600fallback = [\"local\", \"big\"]
5601[[provider.route]]
5602name = \"local\"
5603base_url = \"http://127.0.0.1:8081/v1\"
5604model = \"small\"
5605[[provider.route]]
5606name = \"big\"
5607base_url = \"http://127.0.0.1:8082/v1\"
5608model = \"large\"
5609";
5610        let c = parse(text);
5611        c.validate_routes().unwrap();
5612        let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
5613        assert_eq!(names, ["local", "big"], "no phantom default route");
5614
5615        let mut pinned = parse(text);
5616        let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
5617        let e = e.to_string();
5618        assert!(
5619            e.contains("unknown route `default`") && e.contains("local, big"),
5620            "{e}"
5621        );
5622        assert!(!e.contains("provider.base_url"), "{e}");
5623    }
5624
5625    #[test]
5626    fn two_routes_with_the_same_name_are_refused_naming_it() {
5627        let e = refusal(
5628            "[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
5629             [[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5630        );
5631        assert!(e.contains("`a`") && e.contains("unique"), "{e}");
5632    }
5633
5634    #[test]
5635    fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
5636        let e = refusal("[[provider.route]]\nname=\"  \"\nbase_url=\"u\"\nmodel=\"m\"\n");
5637        assert!(
5638            e.contains("provider.route #1") && e.contains("no name"),
5639            "{e}"
5640        );
5641        let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
5642        assert!(e.contains("provider.route #1"), "{e}");
5643    }
5644
5645    #[test]
5646    fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
5647        let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5648        let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
5649        assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
5650        let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
5651        assert_eq!(c.chain().unwrap().routes[0].name, "default");
5652    }
5653
5654    #[test]
5655    fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
5656        let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
5657        assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
5658        let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
5659        assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
5660    }
5661
5662    #[test]
5663    fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
5664        let e = refusal(
5665            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5666             [[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
5667        );
5668        assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
5669    }
5670
5671    #[test]
5672    fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
5673        let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
5674        assert!(e.contains("`cloud`"), "{e}");
5675        assert!(e.contains("local, big"), "{e}");
5676    }
5677
5678    #[test]
5679    fn an_empty_fallback_is_a_typo_not_a_policy() {
5680        let e = refusal("[provider]\nfallback = []\n");
5681        assert!(e.contains("provider.fallback is empty"), "{e}");
5682    }
5683
5684    #[test]
5685    fn a_fallback_that_lists_a_route_twice_is_refused() {
5686        let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
5687        assert!(e.contains("`local` twice"), "{e}");
5688    }
5689
5690    #[test]
5691    fn a_fallback_or_route_table_inside_a_route_is_refused() {
5692        let e = refusal(
5693            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
5694        );
5695        assert!(e.contains("`r`") && e.contains("directly"), "{e}");
5696    }
5697
5698    const WITH_AUX: &str = "\
5699[provider]
5700base_url = \"http://d/v1\"
5701model = \"dm\"
5702aux = \"cheap\"
5703[[provider.route]]
5704name = \"cheap\"
5705base_url = \"http://c/v1\"
5706model = \"cm\"
5707";
5708
5709    #[test]
5710    fn aux_names_a_route_and_the_role_table_says_so() {
5711        let chain = parse(WITH_AUX).chain().unwrap();
5712        assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
5713        assert_eq!(chain.aux.unwrap().config.model, "cm");
5714        let roles = parse(WITH_AUX).chain().unwrap().roles();
5715        assert_eq!(roles.len(), 2, "only roles that exist get a row");
5716        assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
5717        assert_eq!(
5718            roles[1].to_string(),
5719            "delegate \u{2192} default (no delegate route set)"
5720        );
5721    }
5722
5723    #[test]
5724    fn delegate_names_a_route_and_the_role_table_says_so() {
5725        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
5726        let chain = c.chain().unwrap();
5727        assert_eq!(
5728            chain.delegate.as_ref().map(|r| r.name.as_str()),
5729            Some("cheap")
5730        );
5731        assert!(chain.aux.is_none());
5732        let roles = chain.roles();
5733        assert_eq!(
5734            roles[0].to_string(),
5735            "judgement \u{2192} default (no aux route set)"
5736        );
5737        assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
5738    }
5739
5740    #[test]
5741    fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
5742        // Both keys set, and `--route cheap`: every role is on `cheap`, because a pin bounds
5743        // where this run's text may go.
5744        let mut c =
5745            parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5746        c.pin_route(Some("cheap"), &|_| None).unwrap();
5747        let chain = c.chain().unwrap();
5748        assert_eq!(chain.source, ChainSource::Pinned);
5749        assert_eq!(
5750            chain.aux.as_ref().map(|r| r.name.as_str()),
5751            Some("cheap"),
5752            "the pinned route, not the key's own value"
5753        );
5754        assert_eq!(
5755            chain.delegate.as_ref().map(|r| r.name.as_str()),
5756            Some("cheap")
5757        );
5758        for role in chain.roles() {
5759            assert!(role.pinned, "{role} should be pinned");
5760            assert!(!role.set, "{role} should not claim the key decided it");
5761            assert_eq!(role.route, "cheap");
5762            assert!(role.to_string().ends_with("(pinned)"), "{role}");
5763        }
5764
5765        // The same config without a pin keeps both keys.
5766        let c =
5767            parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5768        let chain = c.chain().unwrap();
5769        assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
5770    }
5771
5772    #[test]
5773    fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
5774        let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
5775        assert!(
5776            e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
5777            "{e}"
5778        );
5779        // Empty means unset, the same as an absent line — the shipped config writes it that way.
5780        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
5781        c.validate_routes()
5782            .expect("an empty delegate is a config that loads");
5783        let e = refusal(
5784            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
5785             [provider]\nfallback=[\"r\"]\n",
5786        );
5787        assert!(
5788            e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
5789            "{e}"
5790        );
5791        let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
5792        assert!(e.contains("delegate"), "{e}");
5793    }
5794
5795    #[test]
5796    fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5797        assert_eq!(Config::default().tools.delegate, Policy::Ask);
5798        let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
5799        assert_eq!(cfg.tools.delegate, Policy::Deny);
5800        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5801        assert_eq!(starter.tools.delegate, Policy::Ask);
5802        assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
5803    }
5804
5805    #[test]
5806    fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
5807        let chain = parse(TWO_ROUTES).chain().unwrap();
5808        assert!(chain.aux.is_none());
5809        assert_eq!(
5810            chain.roles()[0].to_string(),
5811            "judgement \u{2192} local (no aux route set)"
5812        );
5813        let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5814        assert_eq!(
5815            bare.chain().unwrap().roles()[0].to_string(),
5816            "judgement \u{2192} default (no aux route set)"
5817        );
5818    }
5819
5820    #[test]
5821    fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
5822        let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
5823        assert!(
5824            e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
5825            "{e}"
5826        );
5827        // Empty is not a misspelling to refuse any more: it is the shipped spelling of "no aux
5828        // route", and the file a first install writes has it in it (`empty_is_none`). A name that
5829        // is *set* and unknown is still refused, above.
5830        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
5831        c.validate_routes()
5832            .expect("an empty aux route is a config that loads");
5833        assert!(c.chain().unwrap().aux.is_none());
5834    }
5835
5836    #[test]
5837    fn aux_inside_a_route_is_refused_like_fallback_and_route() {
5838        let e = refusal(
5839            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
5840             [provider]\nfallback=[\"r\"]\n",
5841        );
5842        assert!(
5843            e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
5844            "{e}"
5845        );
5846    }
5847
5848    #[test]
5849    fn a_wrong_typed_aux_is_an_error_naming_the_key() {
5850        let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
5851        assert!(e.contains("aux"), "{e}");
5852    }
5853
5854    #[test]
5855    fn aux_may_name_the_default_route_when_provider_is_one() {
5856        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
5857        assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
5858        let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
5859             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5860        assert!(refusal(tuning_only).contains("Routes that exist: r"));
5861    }
5862
5863    #[test]
5864    fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
5865        let bad =
5866            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
5867        let e = Config::from_toml_str(bad).unwrap_err();
5868        assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
5869        let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
5870        assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
5871    }
5872
5873    #[test]
5874    fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
5875        let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
5876        assert!(
5877            e.contains("fallback") && e.contains("--route") && e.contains("r"),
5878            "{e}"
5879        );
5880    }
5881
5882    #[test]
5883    fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
5884        let c = parse(
5885            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5886             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5887        );
5888        let chain = c.chain().unwrap();
5889        assert_eq!(chain.source, ChainSource::Default);
5890        assert_eq!(chain.routes.len(), 1);
5891        assert_eq!(chain.routes[0].name, "default");
5892        let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
5893        assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
5894    }
5895
5896    #[test]
5897    fn a_bare_config_still_says_what_is_wrong_with_provider() {
5898        let e = Config::default()
5899            .require_provider()
5900            .unwrap_err()
5901            .to_string();
5902        assert!(e.contains("provider.base_url is not set"), "{e}");
5903        assert!(e.contains("eclipse config init"), "{e}");
5904        let c = parse("[provider]\nbase_url=\"u\"\n");
5905        assert!(c
5906            .require_provider()
5907            .unwrap_err()
5908            .to_string()
5909            .contains("provider.model is not set"));
5910    }
5911
5912    #[test]
5913    fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
5914        let mut c = parse(TWO_ROUTES);
5915        c.pin_route(Some("big"), &env_of(&[])).unwrap();
5916        let chain = c.chain().unwrap();
5917        assert_eq!(chain.source, ChainSource::Pinned);
5918        assert_eq!(chain.routes.len(), 1);
5919        assert_eq!(chain.routes[0].name, "big");
5920    }
5921
5922    #[test]
5923    fn an_unknown_pin_lists_the_routes_that_exist() {
5924        let mut c = parse(TWO_ROUTES);
5925        let e = c
5926            .pin_route(Some("nope"), &env_of(&[]))
5927            .unwrap_err()
5928            .to_string();
5929        assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
5930        let e = c
5931            .pin_route(Some(" "), &env_of(&[]))
5932            .unwrap_err()
5933            .to_string();
5934        assert!(e.contains("--route needs a route name"), "{e}");
5935    }
5936
5937    #[test]
5938    fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
5939        let mut c = parse(TWO_ROUTES);
5940        c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
5941            .unwrap();
5942        assert_eq!(c.route_pin.as_deref(), Some("big"));
5943        c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
5944            .unwrap();
5945        assert_eq!(c.route_pin.as_deref(), Some("local"));
5946        let mut c = parse(TWO_ROUTES);
5947        c.dotenv
5948            .values
5949            .insert("ECLIPSE_ROUTE".into(), "local".into());
5950        c.pin_route(None, &env_of(&[])).unwrap();
5951        assert_eq!(
5952            c.route_pin.as_deref(),
5953            Some("local"),
5954            "the .env chain counts too"
5955        );
5956        let mut c = parse(TWO_ROUTES);
5957        c.pin_route(None, &env_of(&[])).unwrap();
5958        assert_eq!(c.route_pin, None);
5959    }
5960
5961    #[test]
5962    fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
5963        let mut c = parse(
5964            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5965             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
5966        );
5967        c.apply_env(&env_of(&[
5968            ("R_KEY", "from-r"),
5969            ("ECLIPSE_API_KEY", "for-default"),
5970        ]));
5971        assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
5972        assert_eq!(
5973            c.provider.route[0].config.api_key.as_deref(),
5974            Some("from-r")
5975        );
5976
5977        let mut only_routes = parse(TWO_ROUTES);
5978        only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
5979        assert_eq!(
5980            only_routes.provider.api_key, None,
5981            "no phantom default route"
5982        );
5983        assert_eq!(only_routes.provider.route[0].config.api_key, None);
5984    }
5985
5986    #[test]
5987    fn the_redacted_config_hides_every_routes_key_and_round_trips() {
5988        let c = parse(TWO_ROUTES);
5989        let t = c.to_toml_redacted().unwrap();
5990        assert!(!t.contains("hunter2"), "{t}");
5991        assert!(
5992            t.contains("[[provider.route]]") && t.contains("<redacted>"),
5993            "{t}"
5994        );
5995        let back = parse(&t);
5996        assert_eq!(back.provider.fallback, c.provider.fallback);
5997        assert_eq!(back.provider.route.len(), 2);
5998        assert_eq!(back.provider.route[1].config.timeout_secs, 30);
5999    }
6000
6001    #[test]
6002    fn a_config_without_routes_prints_no_provider_route_keys() {
6003        // The table, not the letters: `[vision] route` is a key of its own, and a substring check
6004        // for the word would have made that a regression instead of a setting.
6005        let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
6006        let t = c.to_toml_redacted().unwrap();
6007        let parsed: toml::Value = toml::from_str(&t).unwrap();
6008        let provider = parsed.get("provider").expect("a provider table");
6009        for absent in ["route", "fallback", "aux", "delegate"] {
6010            assert!(
6011                provider.get(absent).is_none(),
6012                "`provider.{absent}` printed for a config with one route: {t}"
6013            );
6014        }
6015    }
6016
6017    #[test]
6018    fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
6019        let tmp = tempfile::tempdir().unwrap();
6020        let path = tmp.path().join("c.toml");
6021        std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
6022        let e = Config::load_with(Some(&path), &env_of(&[]))
6023            .unwrap_err()
6024            .to_string();
6025        assert!(e.contains("`ghost`"), "{e}");
6026    }
6027
6028    #[test]
6029    fn context_policy_defaults_and_the_rail_it_derives() {
6030        let c = ContextPolicyConfig::default();
6031        assert!(
6032            c.judge,
6033            "the model half is the judgement pass, and it ships on: compile plus one bounded call"
6034        );
6035        assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
6036        assert_eq!(c.compact_at, 0.85);
6037        assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
6038        assert_eq!(c.window_tokens, 0, "no window is invented");
6039        assert_eq!(c.budget_for(0), 0, "no window, no rail");
6040        assert_eq!(c.budget_for(327_680), 278_528);
6041        let off = ContextPolicyConfig {
6042            compact_at: 0.0,
6043            ..c.clone()
6044        };
6045        assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
6046        let half = ContextPolicyConfig {
6047            compact_at: 0.5,
6048            ..c
6049        };
6050        assert_eq!(half.budget_for(131_072), 65_536);
6051    }
6052
6053    #[test]
6054    fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
6055        for bad in ["1.5", "-0.2"] {
6056            let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
6057            let err = c.context.validate().unwrap_err().to_string();
6058            assert!(
6059                err.contains("context.compact_at"),
6060                "{bad} must be named in the error: {err}"
6061            );
6062        }
6063        assert!(parse("[context]\ncompact_at = 0.6\n")
6064            .context
6065            .validate()
6066            .is_ok());
6067        assert!(parse("[context]\ncompact_at = 0\n")
6068            .context
6069            .validate()
6070            .is_ok());
6071    }
6072}
6073
6074#[cfg(test)]
6075mod mcp_editor_tests {
6076    use super::*;
6077    use crate::mcp::Spec;
6078
6079    fn spec(text: &str) -> Spec {
6080        toml::from_str(text).unwrap()
6081    }
6082
6083    fn add(spec: &Spec) -> String {
6084        let out = mcp_add(CONFIG, spec).unwrap();
6085        // Every writer proves itself the same way: the file it returns loads.
6086        parse_text(&out).unwrap();
6087        out
6088    }
6089
6090    const CONFIG: &str = r#"# my config
6091[provider]
6092base_url = "http://127.0.0.1:8081/v1"
6093model = "m"
6094
6095# this comment belongs to the first entry
6096[[mcp]]
6097name = "first"
6098command = "one"
6099
6100# and this one to the second
6101[[mcp]]
6102name = "second"
6103command = "two"
6104policy = "allow"
6105"#;
6106
6107    #[test]
6108    fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
6109        let out = add(&spec(
6110            "name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
6111        ));
6112        let cfg = parse_text(&out).unwrap();
6113        assert_eq!(
6114            cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
6115            ["first", "second", "third"]
6116        );
6117        let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
6118        assert_eq!(third.args, ["--x"]);
6119        assert_eq!(third.prefix, "t_");
6120        // The two hand-written entries and both comments are untouched, byte for byte.
6121        for line in [
6122            "# my config",
6123            "# this comment belongs to the first entry",
6124            "# and this one to the second",
6125        ] {
6126            assert!(out.contains(line), "lost {line:?}:\n{out}");
6127        }
6128        assert!(
6129            out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
6130            "{out}"
6131        );
6132        assert!(
6133            !out.contains("args = []"),
6134            "only what was set is written:\n{out}"
6135        );
6136    }
6137
6138    #[test]
6139    fn a_duplicate_name_is_refused_and_named_by_line() {
6140        let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
6141        assert!(err.contains("already declared at line 7"), "{err}");
6142    }
6143
6144    #[test]
6145    fn an_unusable_entry_is_refused_before_anything_is_written() {
6146        // http with a command: `Spec::validate`'s own refusal, wrapped in the writer's voice.
6147        let err = mcp_add(
6148            CONFIG,
6149            &spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
6150        )
6151        .unwrap_err();
6152        assert!(err.starts_with("that entry is not usable"), "{err}");
6153        assert!(err.contains("belong to the stdio transport"), "{err}");
6154    }
6155
6156    #[test]
6157    fn remove_takes_the_named_block_and_the_blank_line_after_it() {
6158        let out = mcp_remove(CONFIG, "first").unwrap();
6159        let cfg = parse_text(&out).unwrap();
6160        assert_eq!(
6161            cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
6162            ["second"]
6163        );
6164        // The second entry's comment stays with the second entry.
6165        assert!(out.contains("# and this one to the second"), "{out}");
6166        assert!(!out.contains("name = \"first\""), "{out}");
6167        assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
6168    }
6169
6170    #[test]
6171    fn remove_says_what_the_file_does_declare() {
6172        let err = mcp_remove(CONFIG, "nope").unwrap_err();
6173        assert!(err.contains("declares first, second"), "{err}");
6174        let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
6175        let err = mcp_remove(bare, "nope").unwrap_err();
6176        assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
6177    }
6178
6179    #[test]
6180    fn disable_flips_the_line_inside_its_own_block() {
6181        let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
6182        let cfg = parse_text(&off).unwrap();
6183        assert!(
6184            cfg.mcp
6185                .iter()
6186                .find(|s| s.name == "second")
6187                .unwrap()
6188                .disabled
6189        );
6190        assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
6191        // Written into the block that already exists, not appended to the file.
6192        let second_at = off.find("name = \"second\"").unwrap();
6193        let tail = &off[second_at..];
6194        assert!(tail.contains("disabled = true"), "{off}");
6195        assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));
6196
6197        let on = mcp_set_disabled(&off, "second", false).unwrap();
6198        let cfg = parse_text(&on).unwrap();
6199        assert!(
6200            !cfg.mcp
6201                .iter()
6202                .find(|s| s.name == "second")
6203                .unwrap()
6204                .disabled
6205        );
6206        assert!(
6207            on.contains("disabled = false"),
6208            "said out loud, not deleted:\n{on}"
6209        );
6210    }
6211
6212    #[test]
6213    fn disable_on_an_entry_without_the_key_inserts_one() {
6214        let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
6215        assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
6216        assert!(parse_text(&off).unwrap().mcp[0].disabled);
6217    }
6218
6219    /// `#517`: an edit is a line-level splice inside one block. The neighbours — and this entry's
6220    /// own comments and ordering — round trip byte for byte; only the lines whose value changed
6221    /// move, which is the whole reason this is not a remove followed by an add.
6222    #[test]
6223    fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
6224        let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
6225        parse_text(&out).unwrap();
6226        assert_eq!(
6227            out,
6228            CONFIG.replace(
6229                "command = \"two\"\npolicy = \"allow\"",
6230                "command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
6231            ),
6232            "one added line, and not one other character moved:\n{out}"
6233        );
6234    }
6235
6236    /// A field set back to its default loses its line rather than gaining a default one, and a
6237    /// new one is appended in the renderer's order — again, nothing else moves.
6238    #[test]
6239    fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
6240        let on = mcp_update(CONFIG, "second", |entry| {
6241            entry.token_env = Some("HA_TOKEN".into())
6242        })
6243        .unwrap();
6244        assert_eq!(
6245            on,
6246            CONFIG.replace(
6247                "command = \"two\"\npolicy = \"allow\"",
6248                "command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
6249            ),
6250            "{on}"
6251        );
6252        let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
6253        assert_eq!(
6254            off, CONFIG,
6255            "clearing a field removes its line and nothing else"
6256        );
6257    }
6258
6259    /// A comment written *inside* a block belongs to that block, so it survives an edit to a
6260    /// neighbouring line of the same entry.
6261    #[test]
6262    fn an_edit_keeps_a_comment_written_inside_the_block() {
6263        let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
6264        let out = mcp_update(inner, "a", |entry| {
6265            entry.args = vec!["--y".into()];
6266        })
6267        .unwrap();
6268        assert_eq!(
6269            out,
6270            "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
6271             args = [\"--y\"]\n",
6272            "{out}"
6273        );
6274    }
6275
6276    /// A rename is a remove and an add, and the writer says so rather than doing half of one.
6277    #[test]
6278    fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
6279        let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
6280        assert!(err.contains("an edit does not rename"), "{err}");
6281
6282        let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
6283        assert!(err.contains("declares first, second"), "{err}");
6284
6285        // And an unusable result is the validator's sentence, before anything is written.
6286        let err = mcp_update(CONFIG, "second", |entry| {
6287            entry.transport = crate::mcp::Transport::Http;
6288            entry.url = Some("http://h/mcp".into());
6289        })
6290        .unwrap_err();
6291        assert!(err.starts_with("that entry is not usable"), "{err}");
6292        assert!(err.contains("belong to the stdio transport"), "{err}");
6293    }
6294
6295    #[test]
6296    fn an_empty_file_gets_its_first_entry_cleanly() {
6297        let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
6298        assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
6299        assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
6300    }
6301
6302    #[test]
6303    fn a_second_entry_is_separated_by_exactly_one_blank_line() {
6304        let out = add(&spec("name = \"third\"\ncommand = \"three\""));
6305        assert!(!out.contains("\n\n\n"), "{out}");
6306        assert!(
6307            out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
6308            "{out}"
6309        );
6310    }
6311}