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.
985fn default_hidden_paths() -> Vec<PathBuf> {
986    ["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
987        .iter()
988        .map(PathBuf::from)
989        .collect()
990}
991
992/// 32 KB: large enough that no honest one-shot rewrite trips it (a README, a config file, a
993/// script), small enough that the files worth patching — a single-file app, a long document —
994/// are guarded. A rewrite of something bigger is a decision, not an accident.
995/// MCP tools are deferred out of the box (`#351`): an MCP server is where forty tools come from,
996/// and forty schemas in every request is four thousand tokens of promise. Matched against the
997/// tool's source label (`plugin:mcp:<server>`), not its name — MCP tools keep the name the server
998/// published (`#373`), so `mcp_*` would match nothing.
999fn default_deferred() -> Vec<String> {
1000    vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
1001}
1002
1003fn default_rewrite_guard() -> usize {
1004    32 * 1024
1005}
1006
1007impl Default for ToolsConfig {
1008    fn default() -> Self {
1009        Self {
1010            workspace_root: None,
1011            read_file: Policy::Allow,
1012            search_files: Policy::Allow,
1013            // The file tools confine every path to the workspace (and the scripts directory) and
1014            // refuse the rest, so the refusal — not a prompt — is what keeps them honest. Asking
1015            // on top of a boundary that already holds is the noise that teaches `y`.
1016            write_file: Policy::Allow,
1017            rewrite_guard_bytes: default_rewrite_guard(),
1018            patch: Policy::Allow,
1019            memory: Policy::Ask,
1020            shell: Policy::Ask,
1021            fetch: Policy::Ask,
1022            script: Policy::Ask,
1023            execute_code: Policy::Ask,
1024            delegate: Policy::Ask,
1025            shell_ask: ShellAsk::Dangerous,
1026            shell_timeout_secs: 30,
1027            shell_allowlist: Vec::new(),
1028            shell_isolate: ShellIsolate::Process,
1029            shell_isolate_writable: Vec::new(),
1030            shell_isolate_hide: default_hidden_paths(),
1031            shell_isolate_network: true,
1032            fetch_timeout_secs: 20,
1033            fetch_html: FetchHtml::Text,
1034            max_output_bytes: 32 * 1024,
1035            concurrency: 1,
1036            disabled: Vec::new(),
1037            deferred: default_deferred(),
1038            tool_search: Policy::Allow,
1039            tool_describe: Policy::Allow,
1040            tool_call: Policy::Allow,
1041        }
1042    }
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize)]
1046#[serde(default)]
1047pub struct SessionsConfig {
1048    /// Defaults to `<state_dir>/sessions`.
1049    pub dir: Option<PathBuf>,
1050    /// Default for `sessions prune --keep-days`: delete sessions whose last activity is
1051    /// older than this many days. 0 = disabled. Applied unattended only if `auto_prune`.
1052    pub retention_keep_days: u64,
1053    /// Default for `sessions prune --keep-count`: keep only the newest N sessions.
1054    /// 0 = disabled. Applied unattended only if `auto_prune`.
1055    pub retention_keep_count: usize,
1056    /// Apply the retention limits when the CLI starts (`run` and the REPL), before the
1057    /// prompt. Off by default. It deletes only if at most 10 sessions would go; otherwise
1058    /// it warns and deletes nothing. With both limits 0 it does nothing. The web dashboard
1059    /// never prunes.
1060    pub auto_prune: bool,
1061    /// How long a run waits for another *process* to release the same session before it
1062    /// fails. 0 = do not wait at all (fail on the first refusal).
1063    pub lock_wait_secs: u64,
1064    /// Name sessions: a name derived from the opening message before the first request, and at
1065    /// most one small-model call per session to replace it with a better one. The call goes to
1066    /// `provider.aux` when there is one, so it costs the cheap route and never the turn's model.
1067    pub autotitle: bool,
1068}
1069
1070impl Default for SessionsConfig {
1071    fn default() -> Self {
1072        Self {
1073            dir: None,
1074            retention_keep_days: 0,
1075            retention_keep_count: 0,
1076            auto_prune: false,
1077            lock_wait_secs: 30,
1078            autotitle: true,
1079        }
1080    }
1081}
1082
1083#[derive(Clone, Serialize, Deserialize)]
1084#[serde(default)]
1085pub struct WebConfig {
1086    pub host: String,
1087    pub port: u16,
1088    /// Dashboard login secret, generated by `config init`. The dashboard refuses to
1089    /// start without one.
1090    #[serde(deserialize_with = "empty_is_none")]
1091    pub auth_token: Option<String>,
1092    /// How long a browser stays signed in. `0` is read as the default rather than as
1093    /// "expire immediately", which would make the dashboard unusable.
1094    pub session_ttl_hours: u64,
1095    /// Which profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE`
1096    /// names one. `None` means the `default` profile.
1097    #[serde(deserialize_with = "empty_is_none")]
1098    pub default_profile: Option<String>,
1099}
1100
1101impl Default for WebConfig {
1102    fn default() -> Self {
1103        Self {
1104            host: "127.0.0.1".into(),
1105            port: 8787,
1106            auth_token: None,
1107            session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
1108            default_profile: None,
1109        }
1110    }
1111}
1112
1113/// `[gateway]`: the one long-lived process that keeps the whole thing running.
1114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1115#[serde(default)]
1116pub struct GatewayConfig {
1117    /// How often the gateway runs the update check and logs what it found. Log-only: a version
1118    /// change is a decision, and the gateway is not the place to make it. `0` turns the check
1119    /// off.
1120    pub check_interval_hours: u64,
1121    /// How long a session created by `POST /v1/chat/completions` is kept. The loop stores every
1122    /// turn, so each API call leaves one behind; they are tagged `api` and swept after this many
1123    /// hours, so a script polling the endpoint cannot fill the store. `0` keeps them forever.
1124    #[serde(default = "default_api_session_ttl_hours")]
1125    pub api_session_ttl_hours: u64,
1126}
1127
1128pub fn default_api_session_ttl_hours() -> u64 {
1129    24
1130}
1131
1132impl Default for GatewayConfig {
1133    fn default() -> Self {
1134        Self {
1135            check_interval_hours: 6,
1136            api_session_ttl_hours: default_api_session_ttl_hours(),
1137        }
1138    }
1139}
1140
1141/// How long a dashboard login lasts before the browser has to sign in again.
1142pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;
1143
1144/// What the CLI does when a tool's policy is `ask`.
1145#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1146#[serde(rename_all = "lowercase")]
1147pub enum Approval {
1148    /// Prompt. The default, and the only setting that lets you see what a tool is about to do.
1149    #[default]
1150    Ask,
1151    /// Never prompt: behave as if `--yes` were always passed.
1152    Auto,
1153    /// Ask the aux route (`#340`). An `ask`-policy call is put to a cheap model as **allow**,
1154    /// **deny** or **escalate**; only the escalate costs a card. A `deny` policy is untouched —
1155    /// the judge may clear a call that was going to be asked about, never widen the registry —
1156    /// and every doubt (a dead route, a timeout, an answer in the wrong words) escalates, because
1157    /// a timeout that read as "carry on" would be a command nobody approved.
1158    Smart,
1159}
1160
1161/// Terminal behaviour. Every field here is read by the CLI; a setting nothing reads is a lie
1162/// in the starter config.
1163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1164#[serde(default)]
1165pub struct CliConfig {
1166    /// Colour. `None` means decide from the stream: a terminal, and `NO_COLOR` unset.
1167    pub color: Option<bool>,
1168    /// Markdown in replies. `None` means on when colour is on, off when piping.
1169    pub markdown: Option<bool>,
1170    /// What an `ask` policy does. `"ask"` prompts, `"auto"` never does, `"smart"` asks the aux
1171    /// route first and escalates to you when it is unsure.
1172    pub approval: Approval,
1173    /// How many commands the REPL remembers for arrow-up.
1174    pub history_size: usize,
1175    /// What an interactive exit does to the screen.
1176    pub clear_on_exit: ClearOnExit,
1177}
1178
1179impl Default for CliConfig {
1180    fn default() -> Self {
1181        Self {
1182            color: None,
1183            markdown: None,
1184            approval: Approval::Ask,
1185            // Matches the constant the REPL used before this was configurable.
1186            history_size: 1000,
1187            clear_on_exit: ClearOnExit::Screen,
1188        }
1189    }
1190}
1191
1192/// What an interactive exit does to the screen: `[cli] clear_on_exit`.
1193///
1194/// The interface draws in the terminal's ordinary buffer, so its last frame survives the process
1195/// and the shell prompt lands underneath it — which reads exactly like a crash. Clearing and
1196/// printing one line says which of the two happened.
1197#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1198#[serde(rename_all = "lowercase")]
1199pub enum ClearOnExit {
1200    /// Clear the visible screen and keep the scrollback. The default: what was scrolled past is
1201    /// the reader's own copy/paste history, and this program deliberately does not own it.
1202    #[default]
1203    Screen,
1204    /// Clear the visible screen and the scrollback behind it.
1205    All,
1206    /// Clear nothing; the goodbye line is simply printed where the frame ended.
1207    Off,
1208}
1209
1210/// How often the update notice asks the public repository for its latest commit.
1211#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1212#[serde(rename_all = "lowercase")]
1213pub enum UpdateCheck {
1214    /// At most once a day. The default: a notice that arrives a month late is not a notice.
1215    #[default]
1216    Daily,
1217    Weekly,
1218    /// Never. No request is made, and nothing is cached.
1219    Off,
1220}
1221
1222impl UpdateCheck {
1223    /// Seconds that must pass between two checks, `None` for `Off`.
1224    pub fn period_secs(self) -> Option<u64> {
1225        match self {
1226            UpdateCheck::Daily => Some(86_400),
1227            UpdateCheck::Weekly => Some(7 * 86_400),
1228            UpdateCheck::Off => None,
1229        }
1230    }
1231}
1232
1233/// Which branch a *source* install follows: `[update] track`.
1234///
1235/// Two names, because there are two long-lived branches and nothing else: `main` only ever takes
1236/// a release or a hotfix, `develop` is where work lands. `release` and `main` are one ref by
1237/// construction, so a second word for the branch would be the confusion the branch model exists
1238/// to end — the key names a track, and a track names a branch.
1239#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1240#[serde(rename_all = "lowercase")]
1241pub enum Track {
1242    /// `main`: the branch releases are cut from, and what every install did before the key
1243    /// existed. The default.
1244    #[default]
1245    Release,
1246    /// `develop`: the branch work lands on — tomorrow's commits, for a checkout that wants them.
1247    Develop,
1248}
1249
1250impl Track {
1251    /// The word the setting takes and the surfaces print.
1252    pub fn label(self) -> &'static str {
1253        match self {
1254            Track::Release => "release",
1255            Track::Develop => "develop",
1256        }
1257    }
1258
1259    /// The branch it follows. `release` is `main`; this is why the key names a track rather than
1260    /// making a person choose between two words for one branch.
1261    pub fn branch(self) -> &'static str {
1262        match self {
1263            Track::Release => "main",
1264            Track::Develop => "develop",
1265        }
1266    }
1267}
1268
1269/// `[hooks]`: which in-process loop hooks run, and their settings.
1270///
1271/// `order` is the composition order, and the only list: a hook that is not named in it does
1272/// not run, and a settings table for a hook that is not named in it is refused at load rather
1273/// than quietly never used. Absent, it is `["redact-secrets"]`; `order = []` runs nothing.
1274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1275#[serde(default)]
1276pub struct HooksConfig {
1277    pub order: Vec<String>,
1278    /// The `[hooks.<name>]` tables. Read as loose TOML so the parser drops nothing: every key
1279    /// here is checked by [`crate::hooks::validate`], which names the one that is wrong.
1280    #[serde(flatten)]
1281    pub settings: BTreeMap<String, toml::Value>,
1282}
1283
1284impl Default for HooksConfig {
1285    fn default() -> Self {
1286        Self {
1287            order: crate::hooks::DEFAULT_ORDER
1288                .iter()
1289                .map(|n| n.to_string())
1290                .collect(),
1291            settings: BTreeMap::new(),
1292        }
1293    }
1294}
1295
1296/// `[update]`: the notice that says a newer commit exists. It is the only request this tool
1297/// makes that is neither a model call nor something the user asked for, so it has a switch.
1298#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1299#[serde(default)]
1300pub struct UpdateConfig {
1301    pub check: UpdateCheck,
1302    /// Which branch a *source* install follows: `release` is `main`, `develop` is the branch work
1303    /// lands on. The ref comes from here rather than from the checkout's upstream, so a checkout
1304    /// parked on a feature branch is refused instead of quietly becoming an update channel
1305    /// nobody chose. A `release` install has no branch to follow at all: it compares tags, and
1306    /// `eclipse upgrade` refuses the develop track there rather than pretending.
1307    pub track: Track,
1308    /// Where the latest commit is asked for, instead of the public GitHub repository: an
1309    /// http(s) URL that answers with a commit id, either as the whole body or as a JSON
1310    /// object with a `sha` field. Because the user wrote it, it may be a host on a private
1311    /// network, which the `fetch` tool's public-hosts rule would refuse.
1312    #[serde(deserialize_with = "empty_is_none")]
1313    pub remote: Option<String>,
1314    /// Where the newest release is asked for, instead of the public GitHub repository: an
1315    /// http(s) URL answering with the same JSON shape (`tag_name`, `assets[].name` and
1316    /// `assets[].browser_download_url`). `eclipse upgrade` on a release install reads its
1317    /// download URLs from this answer, so a mirror is a mirror. May be a host on your network.
1318    #[serde(deserialize_with = "empty_is_none")]
1319    pub releases: Option<String>,
1320}
1321
1322impl fmt::Debug for WebConfig {
1323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324        f.debug_struct("WebConfig")
1325            .field("host", &self.host)
1326            .field("port", &self.port)
1327            .field(
1328                "auth_token",
1329                &self.auth_token.as_ref().map(|_| "<redacted>"),
1330            )
1331            .finish()
1332    }
1333}
1334
1335/// `[attachments]`: where the pictures someone attaches are kept (`#499`).
1336///
1337/// A picture has two facts that used to conflict — the original file, and a small payload the wire
1338/// will carry — and keeping both means keeping files. These are the two decisions that follow: where
1339/// they go, and how much room they may take.
1340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1341#[serde(default)]
1342pub struct AttachmentsConfig {
1343    /// Where pictures are stored. `None` means `<state_dir>/attachments` — not the workspace,
1344    /// which the agent writes to (a `write_file` could clobber a photo, and `git status` in a
1345    /// project should not list someone's holiday snap), and not a temp directory, which is pruned.
1346    pub dir: Option<PathBuf>,
1347    /// Ceiling for everything kept, in bytes. The oldest files are pruned when an attach would
1348    /// exceed it; only if pruning cannot free enough is the attach refused. 0 = no ceiling, which
1349    /// is the one setting here worth being deliberate about.
1350    pub max_total_bytes: u64,
1351}
1352
1353impl Default for AttachmentsConfig {
1354    fn default() -> Self {
1355        Self {
1356            dir: None,
1357            max_total_bytes: 2 * 1024 * 1024 * 1024,
1358        }
1359    }
1360}
1361
1362#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1363#[serde(default)]
1364pub struct Config {
1365    /// The `config_version` the file was written with, and the one thing here that is metadata
1366    /// rather than a setting: it is not in the catalogue, `config set` refuses it, and the agent
1367    /// never reads it. `0` means "written before the stamp existed" and is the version every
1368    /// install older than this key reports.
1369    ///
1370    /// Top-level because it describes the file, and it must survive a section rename.
1371    pub config_version: u32,
1372    pub provider: ProviderConfig,
1373    pub agent: AgentConfig,
1374    pub tools: ToolsConfig,
1375    pub sessions: SessionsConfig,
1376    pub attachments: AttachmentsConfig,
1377    pub plugins: PluginsConfig,
1378    pub web: WebConfig,
1379    pub gateway: GatewayConfig,
1380    pub cli: CliConfig,
1381    pub update: UpdateConfig,
1382    pub hooks: HooksConfig,
1383    pub context: ContextPolicyConfig,
1384    pub user: UserConfig,
1385    pub skills: SkillsConfig,
1386    pub vision: VisionConfig,
1387    /// Which profile this was loaded as. Not part of the file: it comes from `--profile` /
1388    /// `ECLIPSE_PROFILE`, and only decides which overlay and which directories apply.
1389    #[serde(skip)]
1390    pub profile: Option<String>,
1391    /// The route a run is pinned to (`--route`, else `ECLIPSE_ROUTE`). Not part of the file:
1392    /// pinning is a decision about one invocation. Set through [`Config::pin_route`].
1393    #[serde(skip)]
1394    pub route_pin: Option<String>,
1395    /// Which `.env` files were read and what they held. Not part of the file, and never
1396    /// serialised: values are exactly what must not be printed.
1397    #[serde(skip)]
1398    pub dotenv: Dotenv,
1399    /// `[[mcp]]`: MCP servers declared in `config.toml` (`#352`). The same spec a plugin manifest
1400    /// carries — one loader, two providers — and the one a name clash with a manifest wins, because
1401    /// this file is somebody's decision about this machine while a manifest is what a plugin
1402    /// shipped. Tools they list are reported as `config:mcp:<server>`.
1403    #[serde(default)]
1404    pub mcp: Vec<crate::mcp::Spec>,
1405    /// `--no-mcp`: start no MCP server for this process. Not part of the file — it is a decision
1406    /// about one invocation, and it exists because a server that hangs at startup must not be
1407    /// able to lock someone out of their own agent.
1408    #[serde(skip)]
1409    pub no_mcp: bool,
1410    /// `[flares]`: the budget and cap defaults a flare run starts from (`#171`).
1411    #[serde(default)]
1412    pub flares: FlaresConfig,
1413    /// `[bots.<name>]`: named agent identities (`#509`). A bot is a declaration plus one session
1414    /// whose `origin` is `bot:<name>` — no second runtime and no second store. The gateway reads
1415    /// this table at startup, keeps an agent per bot, and the Bots tab lists what it found.
1416    #[serde(default)]
1417    pub bots: std::collections::BTreeMap<String, BotConfig>,
1418}
1419
1420/// `[flares]`: what a run costs and how wide it may go (`#171`).
1421///
1422/// Every number here is a limit, not a promise: a run is N jobs the lead named, and these are
1423/// what stops an N from being expensive. `count` is only the default for `flares run -n` — the
1424/// model-facing tool never gets a count, it names its jobs.
1425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1426#[serde(default)]
1427pub struct FlaresConfig {
1428    /// The default for `flares run -n`, and the number a local run starts from. An accidental
1429    /// fan-out on a server that serves one model at a time is ten minutes of serial turns.
1430    pub count: usize,
1431    /// The most flares one run may have in flight, whatever the routes would allow.
1432    pub max_concurrent: usize,
1433    /// Per flare, when the job does not say: the same budget `delegate` gives a child.
1434    pub max_iterations: usize,
1435    /// The run's own budget. Not `count x max_iterations` in disguise: this is what stops one
1436    /// wandering flare before it eats the budget of the three beside it.
1437    pub total_iterations: usize,
1438    /// Optional spend cap for the whole run, in tokens. Unset: no cap beyond iterations.
1439    pub total_tokens: Option<u64>,
1440}
1441
1442impl Default for FlaresConfig {
1443    fn default() -> Self {
1444        Self {
1445            count: 3,
1446            max_concurrent: 4,
1447            max_iterations: 6,
1448            total_iterations: 24,
1449            total_tokens: None,
1450        }
1451    }
1452}
1453
1454impl FlaresConfig {
1455    /// What this config can actually do: `max_concurrent`, floored by the slots the named routes
1456    /// bring, and never below one.
1457    pub fn concurrency(&self) -> usize {
1458        self.max_concurrent.max(1)
1459    }
1460
1461    /// How many iterations one flare gets when its job does not say.
1462    pub fn per_flare(&self) -> usize {
1463        self.max_iterations.max(1)
1464    }
1465
1466    /// The run's budget as written. Deliberately **not** floored at one flare's worth: a run set
1467    /// to two iterations with a per-flare default of six gives its first flare two and drops the
1468    /// rest, and saying so is more honest than quietly raising the number the operator typed.
1469    pub fn budget(&self) -> usize {
1470        self.total_iterations.max(1)
1471    }
1472}
1473
1474/// `[bots.<name>]`: one named agent identity (`#509`).
1475///
1476/// Every key is optional, because a bot with no keys is still a bot: a session of its own, in
1477/// the list, with the agent's ordinary prompt. What each key overrides is *only* that bot's run —
1478/// the instructions are added to the system prompt rather than replacing it, and nothing here
1479/// changes what the human's own sessions see.
1480#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1481#[serde(default)]
1482pub struct BotConfig {
1483    /// The file this bot's instructions are read from, relative to this profile's directory
1484    /// unless absolute. **Added** to the assembled system prompt, never a replacement: the run is
1485    /// still the CLI/web agent with the bot's words in front of it.
1486    pub instructions: Option<String>,
1487    /// The skills this bot may see, by name. Absent leaves every root in force; an empty list is
1488    /// a bot that sees none — the difference exists because "I declared nothing" and "I declared
1489    /// nothing for it" are not the same sentence.
1490    pub skills: Option<Vec<String>>,
1491    /// Where this bot's `MEMORY.md` lives, relative to this profile's directory unless absolute.
1492    /// Unset means `<profile>/memory/bots/<name>/MEMORY.md`, so a bot's memory is its own file
1493    /// whether or not anyone said where.
1494    pub memory: Option<String>,
1495    /// The lane that reaches this bot. Unset means web only; `telegram` is slice 3 and is not
1496    /// wired yet, so naming it is refused at startup rather than silently ignored.
1497    pub adapter: Option<String>,
1498}
1499
1500/// The adapters this build can actually drive (`#509`). Slice 3 adds `telegram`; a name that is
1501/// not here is reported by `problems` rather than refused, because the declaration is still
1502/// worth writing down today — the bot answers on the web and the lane arrives with slice 3.
1503pub const BOT_ADAPTERS: &[&str] = &[];
1504
1505/// `[context]`: how a request that no longer fits is shortened. The head (first turn) and
1506/// the tail (newest turns) stay verbatim; what pays is the middle.
1507#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1508#[serde(default)]
1509pub struct ContextPolicyConfig {
1510    /// Share of the model's window at which a request is compacted, e.g. `0.85`. `0` turns the
1511    /// threshold off, which leaves only an explicit `provider.context_budget_tokens` as a rail.
1512    pub compact_at: f64,
1513    /// Turns kept verbatim at the tail. `0` is read as `1`: the newest turn is never dropped.
1514    pub protect_last_n: usize,
1515    /// Ask one model one bounded question about *why* the dropped turns went the way they did,
1516    /// and take its answer only if every name in it appears in the digest it was written from.
1517    /// Off by default: it is the one part of compaction that spends a provider request.
1518    pub judge: bool,
1519    /// How long that one call may take before the deterministic handoff ships without it.
1520    pub judge_timeout_secs: u64,
1521    /// The window to assume when the endpoint advertises none (`/props`, `/v1/models`). `0`
1522    /// means assume nothing: a request is never shortened on a guessed window.
1523    pub window_tokens: usize,
1524    /// Hard cap, in characters, on the compiled handoff that stands in for the dropped middle.
1525    /// A handoff that grows to fill the window would defeat the point of compacting it.
1526    pub handoff_chars: usize,
1527}
1528
1529impl Default for ContextPolicyConfig {
1530    fn default() -> Self {
1531        Self {
1532            compact_at: 0.85,
1533            protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
1534            judge: true,
1535            judge_timeout_secs: 20,
1536            window_tokens: 0,
1537            handoff_chars: 6_000,
1538        }
1539    }
1540}
1541
1542impl ContextPolicyConfig {
1543    /// The budget this policy derives from a window, or 0 when the policy is off.
1544    pub fn budget_for(&self, window_tokens: usize) -> usize {
1545        if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
1546            return 0;
1547        }
1548        (window_tokens as f64 * self.compact_at) as usize
1549    }
1550
1551    /// `compact_at` is a share of a window, so anything outside (0, 1] is a mistake worth
1552    /// naming rather than a silently useless rail.
1553    pub fn validate(&self) -> Result<()> {
1554        if !(0.0..=1.0).contains(&self.compact_at) {
1555            return Err(Error::Config(format!(
1556                "context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
1557                 turn the threshold off",
1558                self.compact_at
1559            )));
1560        }
1561        if self.handoff_chars < 200 {
1562            return Err(Error::Config(format!(
1563                "context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
1564                 and 6000 is the default",
1565                self.handoff_chars
1566            )));
1567        }
1568        Ok(())
1569    }
1570}
1571
1572/// `[user]`: the user model and the agent's memory file.
1573#[derive(Debug, Clone, Serialize, Deserialize)]
1574#[serde(default)]
1575pub struct UserConfig {
1576    /// The user model, relative to this profile's config directory unless absolute.
1577    pub file: String,
1578    /// The agent's memory file, same resolution.
1579    pub memory_file: String,
1580    /// Ceiling for `MEMORY.md` in characters. The `memory` tool refuses past this rather than
1581    /// silently overwriting what is already there.
1582    pub memory_budget_chars: usize,
1583}
1584
1585impl Default for UserConfig {
1586    fn default() -> Self {
1587        Self {
1588            file: "USER.md".into(),
1589            memory_file: "MEMORY.md".into(),
1590            memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
1591        }
1592    }
1593}
1594
1595/// `[skills]`: how much of the prompt the skills index may take.
1596///
1597/// One field, because one thing reads it. Where skills are searched is fixed by the layout
1598/// (shared, profile, workspace, plugins), and a skill is off by being absent; a `dirs` or
1599/// `enabled` key would be a setting nothing consumes.
1600/// `[vision]`: what happens to a picture on a turn (`#346`).
1601#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1602#[serde(default)]
1603pub struct VisionConfig {
1604    /// `native`, `text` or `auto`. The default is `auto`: a model that declares vision gets the
1605    /// bytes, a model that does not gets a description instead.
1606    #[serde(default)]
1607    pub mode: VisionMode,
1608    /// The route that describes pictures, for `text` and for `auto`'s fallback. Empty means there
1609    /// is none, which makes `text` a refusal rather than a silent no-op.
1610    #[serde(default)]
1611    pub route: String,
1612    /// Let a description leave this machine. Off by default: a screenshot is the most private
1613    /// thing this agent touches, and "it went to an API once" cannot be undone by reading a log.
1614    #[serde(default)]
1615    pub allow_cloud: bool,
1616}
1617
1618/// The three modes, spelled in the file the way a person would say them.
1619#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1620#[serde(rename_all = "lowercase")]
1621pub enum VisionMode {
1622    /// The turn's own model sees the picture, or the attach is refused.
1623    Native,
1624    /// The picture is described by `[vision] route` and the turn model reads the description.
1625    Text,
1626    /// Native when the turn model declares vision, a description otherwise.
1627    #[default]
1628    Auto,
1629}
1630
1631#[derive(Debug, Clone, Serialize, Deserialize)]
1632#[serde(default)]
1633pub struct SkillsConfig {
1634    /// Ceiling for the index in the system prompt, in characters. Entries that do not fit are
1635    /// left out and named in `eclipse context show`; 0 = no cap.
1636    pub index_budget_chars: usize,
1637}
1638
1639impl Default for SkillsConfig {
1640    fn default() -> Self {
1641        Self {
1642            index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
1643        }
1644    }
1645}
1646
1647/// `[plugins]`: where plugins live and which ones may load.
1648#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1649#[serde(default)]
1650pub struct PluginsConfig {
1651    /// Root of the shared plugin directory (default `<config_dir>/plugins`). A profile's
1652    /// own `plugins/` directory is always searched first.
1653    pub dir: Option<PathBuf>,
1654    /// Allowlist. A plugin that is not listed is not loaded; an empty list loads none.
1655    pub enabled: Vec<String>,
1656    /// Default ceiling for one MCP server call, for `[[mcp]]` entries that state no
1657    /// `timeout_secs` of their own. Clamped to 1–600 s like any plugin timeout.
1658    pub mcp_timeout_secs: Option<u64>,
1659}
1660
1661impl Config {
1662    /// Load from `explicit` (must exist) or the default path (optional), then apply
1663    /// environment overrides, using the real process environment.
1664    pub fn load(explicit: Option<&Path>) -> Result<Config> {
1665        Self::load_with(explicit, &process_env)
1666    }
1667
1668    pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
1669        Self::load_with_profile(explicit, None, env)
1670    }
1671
1672    /// Load the base config, then the profile's overlay (`profiles/<name>/config.toml`, if it
1673    /// exists) on top of it, then environment overrides. Keys the overlay does not mention
1674    /// keep the base value; a key it does mention replaces it (tables are merged, so a
1675    /// profile can change one provider field without restating the rest).
1676    ///
1677    /// The profile also comes from `ECLIPSE_PROFILE`; an explicit argument wins. The name
1678    /// `default` is the default profile: it may still have an overlay and its own plugins,
1679    /// but its state lives in the plain state directory.
1680    pub fn load_with_profile(
1681        explicit: Option<&Path>,
1682        profile: Option<&str>,
1683        env: EnvFn,
1684    ) -> Result<Config> {
1685        let profile = profile
1686            .map(str::to_string)
1687            .or_else(|| env("ECLIPSE_PROFILE"))
1688            .filter(|p| !p.trim().is_empty());
1689        if let Some(name) = &profile {
1690            validate_profile_name(name)?;
1691        }
1692        // `.env` is read before the TOML is parsed, because the TOML can reference it:
1693        // `api_key = "${OPENAI_API_KEY}"` needs the value to exist by the time it is resolved.
1694        let dotenv = Dotenv::load(env, profile.as_deref())?;
1695        // One lookup for the whole load: the real environment wins, `.env` fills the gaps — and an
1696        // empty `.env` value is a gap, not an answer. `process_env`, `${VAR}` interpolation and
1697        // `pin_route` all treat empty as absent; a raw `.env` value was the one layer that did not,
1698        // so a half-typed `ECLIPSE_API_KEY=` blanked the key the file already had and requests went
1699        // out unauthenticated while looking like a server problem.
1700        let lookup = |k: &str| {
1701            env(k).or_else(|| {
1702                dotenv
1703                    .values
1704                    .get(k)
1705                    .filter(|v| !v.is_empty())
1706                    .map(String::as_str)
1707                    .map(str::to_string)
1708            })
1709        };
1710        let lookup: EnvFn<'_> = &lookup;
1711
1712        let base_path = match explicit {
1713            Some(p) => Some(p.to_path_buf()),
1714            None => config_path(env).filter(|p| p.exists()),
1715        };
1716        // The file a `[hooks]` mistake is blamed on: the overlay when the profile has one.
1717        let mut hooks_path = base_path.clone();
1718        let mut value = match &base_path {
1719            Some(p) => {
1720                let mut parsed = read_toml(p)?;
1721                crate::interpolate::in_value(&mut parsed, p, lookup)?;
1722                parsed
1723            }
1724            None => toml::Value::try_from(Config::default())
1725                .map_err(|e| Error::Config(e.to_string()))?,
1726        };
1727        if let Some(name) = &profile {
1728            if let Some(dir) = profile_dir(env, name) {
1729                let overlay = dir.join("config.toml");
1730                if overlay.exists() {
1731                    let mut over = read_toml(&overlay)?;
1732                    // The profile's own `.env` is already in `lookup`, so a `${VAR}` here can
1733                    // refer to a secret only that profile has.
1734                    crate::interpolate::in_value(&mut over, &overlay, lookup)?;
1735                    if over.get("hooks").is_some() {
1736                        hooks_path = Some(overlay.clone());
1737                    }
1738                    merge_toml(&mut value, over);
1739                }
1740            }
1741        }
1742        let mut cfg: Config = value
1743            .try_into()
1744            .map_err(|e: toml::de::Error| Error::Parse {
1745                path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1746                message: e.to_string(),
1747            })?;
1748        cfg.profile = profile;
1749        cfg.apply_env(lookup);
1750        cfg.dotenv = dotenv;
1751        // At load, so a typo in the route table is the first thing said and not the thing a
1752        // run trips over once it has already started talking to a server.
1753        cfg.validate_routes()?;
1754        cfg.context.validate()?;
1755        // `#509`: a bot name is parsed back out of `origin` and spelled into a URL, so a name
1756        // that cannot survive either is a startup error rather than a tab that never lists it.
1757        cfg.validate_bots()?;
1758        crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
1759            path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1760            message,
1761        })?;
1762        Ok(cfg)
1763    }
1764
1765    /// The profile name in effect, `default` when none was selected.
1766    pub fn profile_name(&self) -> &str {
1767        self.profile.as_deref().unwrap_or("default")
1768    }
1769
1770    /// This profile's state directory (sessions, REPL history).
1771    pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
1772        state_dir_for(env, self.profile.as_deref())
1773            .ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
1774    }
1775
1776    /// Where plugins are looked for, in order: this profile's own `plugins/` directory
1777    /// first, then the shared one (`[plugins] dir`, else `<config_dir>/plugins`). A profile
1778    /// copy of a plugin shadows the shared copy.
1779    pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
1780        let mut out = Vec::new();
1781        if let Some(name) = &self.profile {
1782            if let Some(dir) = profile_dir(env, name) {
1783                out.push(dir.join("plugins"));
1784            }
1785        }
1786        let shared = match &self.plugins.dir {
1787            Some(p) => expand_tilde(p, env),
1788            None => match config_dir(env) {
1789                Some(d) => d.join("plugins"),
1790                None => return out,
1791            },
1792        };
1793        if !out.contains(&shared) {
1794            out.push(shared);
1795        }
1796        out
1797    }
1798
1799    pub fn from_file(path: &Path) -> Result<Config> {
1800        let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
1801        Self::from_toml_str(&text).map_err(|message| Error::Parse {
1802            path: path.to_path_buf(),
1803            message,
1804        })
1805    }
1806
1807    pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
1808        toml::from_str(text).map_err(|e| e.to_string())
1809    }
1810
1811    /// `ECLIPSE_BASE_URL`, `ECLIPSE_API_KEY`, `ECLIPSE_MODEL`.
1812    ///
1813    /// These describe `[provider]`, the `default` route, and nothing else: one variable cannot
1814    /// sensibly be the key for every route in a chain. A named route takes its key from its
1815    /// own `api_key_env`.
1816    pub fn apply_env(&mut self, env: EnvFn) {
1817        if let Some(v) = env("ECLIPSE_BASE_URL") {
1818            self.provider.base_url = v;
1819        }
1820        if let Some(v) = env("ECLIPSE_MODEL") {
1821            self.provider.model = v;
1822        }
1823        // Only when `[provider]` is in use: a config that is all routes must not grow a
1824        // phantom `default` route because the shell happened to export a key.
1825        if self.provider.declares_connection() {
1826            apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
1827        }
1828        for route in &mut self.provider.route {
1829            apply_key_env(&mut route.config, env, None);
1830        }
1831    }
1832
1833    /// Serialise to TOML with every secret-looking value replaced, safe to print.
1834    ///
1835    /// Redaction follows the key name rather than a list of known fields, so a new setting
1836    /// called `api_token` is covered the day it is added instead of the day someone
1837    /// remembers to add it here.
1838    pub fn to_toml_redacted(&self) -> Result<String> {
1839        let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
1840        redact(&mut value);
1841        toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
1842    }
1843
1844    /// Fail early, with an actionable message, if the provider is not configured.
1845    pub fn require_provider(&self) -> Result<()> {
1846        self.chain().map(|_| ())
1847    }
1848
1849    /// The routes the file declares, `default` first when `[provider]` is in use.
1850    ///
1851    /// With no routes at all `default` is always listed, so a bare config still has one
1852    /// route and says what is wrong with it rather than that it has none.
1853    pub fn declared_routes(&self) -> Vec<NamedRoute> {
1854        let mut out = Vec::new();
1855        if self.provider.route.is_empty() || self.provider.declares_connection() {
1856            out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
1857        }
1858        out.extend(self.provider.route.iter().map(|r| {
1859            NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
1860        }));
1861        out
1862    }
1863
1864    /// The routes that exist, for a sentence that has to name them.
1865    pub fn route_names(&self) -> String {
1866        let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1867        if names.is_empty() {
1868            "none".to_string()
1869        } else {
1870            names.join(", ")
1871        }
1872    }
1873
1874    /// Check the route table: every rule is something a run would otherwise find out halfway
1875    /// through, and each message names the route or the key at fault.
1876    ///
1877    /// `[provider]` itself is not checked here — whether `base_url` and `model` are set is
1878    /// asked when a run needs it ([`Config::chain`]), which is why `config show` and
1879    /// `config init` work on a half-written file.
1880    pub fn validate_routes(&self) -> Result<()> {
1881        let p = &self.provider;
1882        let mut seen: Vec<&str> = Vec::new();
1883        for (i, r) in p.route.iter().enumerate() {
1884            let name = r.name.trim();
1885            if name.is_empty() {
1886                return Err(Error::Config(format!(
1887                    "provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
1888                    i + 1
1889                )));
1890            }
1891            if seen.contains(&name) {
1892                return Err(Error::Config(format!(
1893                    "two routes are named `{name}`; route names must be unique"
1894                )));
1895            }
1896            seen.push(name);
1897            if name == DEFAULT_ROUTE && p.declares_connection() {
1898                return Err(Error::Config(format!(
1899                    "a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
1900                     route of that name; rename the route, or move its settings out of [provider]"
1901                )));
1902            }
1903            if r.config.fallback.is_some()
1904                || r.config.aux.is_some()
1905                || r.config.delegate.is_some()
1906                || !r.config.route.is_empty()
1907            {
1908                return Err(Error::Config(format!(
1909                    "route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
1910                     belong directly under [provider], not inside a route"
1911                )));
1912            }
1913            if r.config.base_url.trim().is_empty() {
1914                return Err(Error::Config(format!(
1915                    "route `{name}` has no base_url; a route is a complete provider \
1916                     configuration and does not inherit from [provider]"
1917                )));
1918            }
1919            if r.config.model.trim().is_empty() {
1920                return Err(Error::Config(format!(
1921                    "route `{name}` has no model; a route is a complete provider \
1922                     configuration and does not inherit from [provider]"
1923                )));
1924            }
1925        }
1926        if let Some(fallback) = &p.fallback {
1927            if fallback.is_empty() {
1928                return Err(Error::Config(
1929                    "provider.fallback is empty; name the routes to try in order, or remove the \
1930                     key to use `default` alone"
1931                        .into(),
1932                ));
1933            }
1934            let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1935            let mut listed: Vec<&str> = Vec::new();
1936            for name in fallback {
1937                if !known.contains(name) {
1938                    return Err(Error::Config(format!(
1939                        "provider.fallback names `{name}`, which is not a route. Routes that \
1940                         exist: {}",
1941                        self.route_names()
1942                    )));
1943                }
1944                if listed.contains(&name.as_str()) {
1945                    return Err(Error::Config(format!(
1946                        "provider.fallback lists `{name}` twice; each route is tried at most \
1947                         once per run"
1948                    )));
1949                }
1950                listed.push(name);
1951            }
1952            // `[provider]` set a connection key, so it *is* the route `default` — and `fallback`
1953            // is the whole chain, without it. The endpoint the user wrote down would never be
1954            // called. Refused rather than run: both ways out are one word, and a chain that
1955            // quietly omits the primary is the kind of thing found months later from a bill.
1956            if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
1957                return Err(Error::Config(
1958                    "`[provider]` sets a connection, but provider.fallback is the whole chain \
1959                     and does not list `default`, so that endpoint would never be called. Put \
1960                     `default` first in `fallback`, or move the connection keys into a route \
1961                     and leave `[provider]` to `fallback` alone"
1962                        .into(),
1963                ));
1964            }
1965        }
1966        if let Some(aux) = &p.aux {
1967            if aux.trim().is_empty() {
1968                return Err(Error::Config(
1969                    "provider.aux is empty; name the route that does housekeeping, or remove \
1970                     the key to use the route the run is on"
1971                        .into(),
1972                ));
1973            }
1974            if !self.declared_routes().iter().any(|r| &r.name == aux) {
1975                return Err(Error::Config(format!(
1976                    "provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
1977                    self.route_names()
1978                )));
1979            }
1980        }
1981        if let Some(delegate) = &p.delegate {
1982            if delegate.trim().is_empty() {
1983                return Err(Error::Config(
1984                    "provider.delegate is empty; name the route subagents run on, or remove \
1985                     the key to use the route the run is on"
1986                        .into(),
1987                ));
1988            }
1989            if !self.declared_routes().iter().any(|r| &r.name == delegate) {
1990                return Err(Error::Config(format!(
1991                    "provider.delegate names `{delegate}`, which is not a route. Routes that \
1992                     exist: {}",
1993                    self.route_names()
1994                )));
1995            }
1996        }
1997        // `[vision] route` is checked here for the same reason `aux` is: a name that matches no
1998        // route would otherwise be a picture described by the fallback route the run happens to be
1999        // on, which is a picture sent somewhere nobody chose (`#346`).
2000        let vision_route = self.vision.route.trim();
2001        if !vision_route.is_empty()
2002            && !self
2003                .declared_routes()
2004                .iter()
2005                .any(|r| r.name == vision_route)
2006        {
2007            return Err(Error::Config(format!(
2008                "vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
2009                self.route_names()
2010            )));
2011        }
2012        Ok(())
2013    }
2014
2015    /// Pin this configuration to a route, or leave it unpinned.
2016    ///
2017    /// `flag` is `--route`; without it `ECLIPSE_ROUTE` is read from the environment and then
2018    /// from the `.env` chain, the same layering every other `ECLIPSE_*` setting has. An unknown
2019    /// name is an error that lists the routes that exist, here rather than after a run starts.
2020    pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
2021        let wanted = match flag {
2022            Some(name) if name.trim().is_empty() => {
2023                return Err(Error::Config(
2024                    "--route needs a route name; `eclipse config show` lists them".into(),
2025                ))
2026            }
2027            Some(name) => Some(name.trim().to_string()),
2028            None => env("ECLIPSE_ROUTE")
2029                .or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
2030                .map(|v| v.trim().to_string())
2031                .filter(|v| !v.is_empty()),
2032        };
2033        if let Some(name) = &wanted {
2034            if !self.declared_routes().iter().any(|r| &r.name == name) {
2035                return Err(self.unknown_route(name));
2036            }
2037        }
2038        self.route_pin = wanted;
2039        Ok(())
2040    }
2041
2042    fn unknown_route(&self, name: &str) -> Error {
2043        Error::Config(format!(
2044            "unknown route `{name}`. Routes that exist: {}",
2045            self.route_names()
2046        ))
2047    }
2048
2049    /// The routes a run will use, in order, checked.
2050    ///
2051    /// A pinned run gets exactly one route and [`ChainSource::Pinned`]: pinning means pinned,
2052    /// and nothing downstream may fall back from it. Otherwise it is `[provider] fallback`, or
2053    /// `default` alone, which is every config that existed before routes did.
2054    pub fn chain(&self) -> Result<Chain> {
2055        self.validate_routes()?;
2056        let all = self.declared_routes();
2057        let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
2058        let (routes, source) = if let Some(pin) = &self.route_pin {
2059            let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
2060            (vec![route], ChainSource::Pinned)
2061        } else if let Some(fallback) = &self.provider.fallback {
2062            // validate_routes proved every name is declared.
2063            let routes = fallback.iter().filter_map(|n| find(n)).collect();
2064            (routes, ChainSource::Fallback)
2065        } else if self.provider.declares_connection() || self.provider.route.is_empty() {
2066            (
2067                vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
2068                ChainSource::Default,
2069            )
2070        } else {
2071            return Err(Error::Config(format!(
2072                "routes are declared but nothing says which to use: set `[provider] fallback = \
2073                 [...]`, or pass --route NAME. Routes that exist: {}",
2074                self.route_names()
2075            )));
2076        };
2077        for route in &routes {
2078            route.require_endpoint(source)?;
2079        }
2080        // A pin wins over the role routes. `--route local` is what you say when the text must
2081        // not leave that server; a `[provider] aux = "cheap"` or `delegate = "big"` that ignored
2082        // it would be exactly the leak the pin was meant to close. Recorded as the role routes
2083        // being unset, with `ChainSource::Pinned` saying why.
2084        let pinned = source == ChainSource::Pinned;
2085        let only = routes.first().cloned();
2086        let (aux, delegate) = if pinned {
2087            (only.clone(), only)
2088        } else {
2089            (
2090                self.provider.aux.as_deref().and_then(find),
2091                self.provider.delegate.as_deref().and_then(find),
2092            )
2093        };
2094        if let Some(aux) = &aux {
2095            aux.require_endpoint(source)?;
2096        }
2097        if let Some(delegate) = &delegate {
2098            delegate.require_endpoint(source)?;
2099        }
2100        Ok(Chain {
2101            routes,
2102            source,
2103            aux,
2104            delegate,
2105        })
2106    }
2107
2108    pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
2109        if let Some(d) = &self.sessions.dir {
2110            return Ok(expand_tilde(d, env));
2111        }
2112        Ok(self.state_dir(env)?.join("sessions"))
2113    }
2114
2115    /// `[bots.<name>]`: a bot name is half of a session's `origin` (`bot:<name>`) and a segment of
2116    /// a dashboard URL, so it is checked once at load rather than at the first request that
2117    /// spells it — a name with a `:` in it would make its own sessions unparseable.
2118    ///
2119    /// Lowercase letters, digits, `-` and `_`, one to thirty-two of them: the same rule a profile
2120    /// name follows, because it is the same kind of thing (a word a person types, and a path).
2121    pub fn validate_bots(&self) -> Result<()> {
2122        for name in self.bots.keys() {
2123            let ok = !name.is_empty()
2124                && name.len() <= 32
2125                && name
2126                    .chars()
2127                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
2128            if !ok {
2129                return Err(Error::Config(format!(
2130                    "bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
2131                     32 of them — it becomes part of a session's `origin` and a URL"
2132                )));
2133            }
2134        }
2135        Ok(())
2136    }
2137
2138    /// A path from a bot's declaration (`instructions`, `memory`): `~` expanded, and a relative
2139    /// path taken from this profile's own directory, the same rule `[user] file` follows.
2140    pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
2141        let path = expand_tilde(Path::new(path), env);
2142        if path.is_absolute() {
2143            Some(path)
2144        } else {
2145            self.context_dir(env).map(|dir| dir.join(path))
2146        }
2147    }
2148
2149    /// Where a bot's `MEMORY.md` lives: its declaration, else `<profile>/memory/bots/<name>/` with
2150    /// the human's own file name. Always a file of its own — the one thing a bot must not share
2151    /// with the person it answers.
2152    pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
2153        match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
2154            Some(m) => self.bot_file(env, m),
2155            None => self
2156                .memory_dir(env)
2157                .map(|dir| dir.join("bots").join(name).join(&self.user.memory_file)),
2158        }
2159    }
2160
2161    /// Where attached pictures are kept (`#499`): the override, else `<state_dir>/attachments`.
2162    ///
2163    /// `None` when neither can be worked out — no `HOME`, no `ECLIPSE_HOME` and no override — which
2164    /// the caller reports rather than guessing a directory the agent would write to.
2165    pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
2166        if let Some(dir) = &self.attachments.dir {
2167            return Some(expand_tilde(dir, env));
2168        }
2169        self.state_dir(env).ok().map(|d| d.join("attachments"))
2170    }
2171
2172    /// The four answers a person needs when a profile surprises them: which profile, from which
2173    /// file, under which home, writing sessions where.
2174    ///
2175    /// Every one of them comes from the function that already answers it — `home_root`,
2176    /// `config_path`, `sessions_dir` — so `/profile`, `/settings` and `eclipse doctor` cannot
2177    /// disagree the first time `[sessions] dir` or `ECLIPSE_HOME` moves. `loaded` is the file the
2178    /// caller actually read: `--config` may point outside the root, and naming the default path
2179    /// while running from another one is exactly the mistake this reports.
2180    pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
2181        let overlay = self
2182            .profile
2183            .as_deref()
2184            .filter(|name| *name != "default")
2185            .and_then(|name| profile_dir(env, name))
2186            .map(|dir| dir.join("config.toml"))
2187            .filter(|path| path.exists());
2188        Where {
2189            profile: self.profile.clone(),
2190            config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
2191            overlay,
2192            home: home_root(env),
2193            sessions: self.sessions_dir(env).ok(),
2194        }
2195    }
2196
2197    /// The directory this profile's own files live in: `<config>/profiles/<name>` for a named
2198    /// profile, the config directory itself for the default one.
2199    pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2200        match &self.profile {
2201            Some(name) => profile_dir(env, name),
2202            None => config_path(env)
2203                .and_then(|p| p.parent().map(Path::to_path_buf))
2204                .or_else(|| config_dir(env)),
2205        }
2206    }
2207
2208    /// Where this profile's scripts live: `scripts/` under [`Self::context_dir`], so the
2209    /// profile's own directory when a profile is in effect and the shared one otherwise.
2210    /// Nothing falls back from one to the other — a profile with no scripts has none, which is
2211    /// the same rule the profile's `MEMORY.md` follows.
2212    ///
2213    /// Always absolute: the path is handed to scripts in `ECLIPSE_SCRIPTS_DIR` and compared
2214    /// against the paths a model writes, and `--config some/relative/config.toml` would
2215    /// otherwise make it mean something different from one working directory to the next.
2216    pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
2217        let dir = self.context_dir(env)?.join("scripts");
2218        if dir.is_absolute() {
2219            return Some(dir);
2220        }
2221        std::env::current_dir().ok().map(|cwd| cwd.join(dir))
2222    }
2223
2224    /// Where the agent's memory lives: `memory/` under this profile's directory. `AGENT.md`,
2225    /// `USER.md` and `MEMORY.md` all sit here, because "what the agent has been told" is one
2226    /// thing and answering "where is it?" with three directories is how you end up with a
2227    /// `SOUL.md` nobody remembers writing.
2228    ///
2229    /// `[user] file` and `[user] memory_file` may still be absolute, and an absolute path wins —
2230    /// `Path::join` refuses to descend into one.
2231    pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
2232        self.context_dir(env).map(|d| d.join("memory"))
2233    }
2234
2235    /// Where the global `AGENT.md` lives (the config directory, whatever `--config` says).
2236    pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2237        config_path(env)
2238            .and_then(|p| p.parent().map(Path::to_path_buf))
2239            .or_else(|| config_dir(env))
2240    }
2241
2242    pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
2243        home_dir(env)
2244    }
2245
2246    pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
2247        match &self.tools.workspace_root {
2248            Some(p) => expand_tilde(p, env),
2249            None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
2250        }
2251    }
2252}
2253
2254/// Where this process is running from — the four answers [`Config::where_am_i`] fills in.
2255///
2256/// One struct rather than four calls at each site, because four answers worked out in four places
2257/// is how `/profile` and `eclipse doctor` come to name different session directories the first
2258/// time `[sessions] dir` moves.
2259#[derive(Debug, Clone, Default, PartialEq, Eq)]
2260pub struct Where {
2261    /// `None` for the default profile: `default` is not a directory, it is the absence of one.
2262    pub profile: Option<String>,
2263    /// The base file this process read — `--config`, else the default path. `None` when it was
2264    /// started without one. A profile is an overlay *on top of* this, not a replacement.
2265    pub config: Option<PathBuf>,
2266    /// The profile's own `config.toml`, when it has one. Read after the base, so it wins.
2267    pub overlay: Option<PathBuf>,
2268    /// The root everything lives under: `~/.eclipse`, or `$ECLIPSE_HOME`.
2269    pub home: Option<PathBuf>,
2270    /// `[sessions] dir`, else `<state>/sessions`.
2271    pub sessions: Option<PathBuf>,
2272}
2273
2274impl Where {
2275    /// The name to print: `default` when none was chosen.
2276    pub fn name(&self) -> &str {
2277        self.profile.as_deref().unwrap_or("default")
2278    }
2279
2280    /// Whether this is the default profile — the one whose files sit in the root itself rather
2281    /// than under `profiles/<name>`.
2282    pub fn is_default(&self) -> bool {
2283        matches!(self.profile.as_deref(), None | Some("default"))
2284    }
2285}
2286
2287/// Read and parse one TOML file, with an error that names it.
2288fn read_toml(path: &Path) -> Result<toml::Value> {
2289    let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
2290    toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
2291        path: path.to_path_buf(),
2292        message: message.to_string(),
2293    })
2294}
2295
2296/// Deep-merge `over` into `base`: tables merge key by key, anything else replaces.
2297fn merge_toml(base: &mut toml::Value, over: toml::Value) {
2298    match (base, over) {
2299        (toml::Value::Table(base), toml::Value::Table(over)) => {
2300            for (key, value) in over {
2301                match base.get_mut(&key) {
2302                    Some(slot) => merge_toml(slot, value),
2303                    None => {
2304                        base.insert(key, value);
2305                    }
2306                }
2307            }
2308        }
2309        (slot, over) => *slot = over,
2310    }
2311}
2312
2313/// Replace secret-looking values with `<redacted>`.
2314fn redact(value: &mut toml::Value) {
2315    match value {
2316        toml::Value::Table(table) => {
2317            for (key, slot) in table.iter_mut() {
2318                if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
2319                    *slot = toml::Value::String("<redacted>".into());
2320                    continue;
2321                }
2322                if is_url_key(key) {
2323                    if let toml::Value::String(url) = slot {
2324                        if let Some(clean) = redact_url(url) {
2325                            *slot = toml::Value::String(clean);
2326                            continue;
2327                        }
2328                    }
2329                }
2330                redact(slot);
2331            }
2332        }
2333        toml::Value::Array(items) => items.iter_mut().for_each(redact),
2334        _ => {}
2335    }
2336}
2337
2338/// A key that holds a secret. `_env` keys are the *name* of a variable, not its value, so
2339/// they are printed as they are — hiding `api_key_env = "MY_KEY"` would make the output
2340/// less useful without making it safer.
2341pub(crate) fn is_secret_key(key: &str) -> bool {
2342    let k = key.to_ascii_lowercase();
2343    if k.ends_with("_env") {
2344        return false;
2345    }
2346    // A unit suffix says "a count of these", not "one of these": `window_tokens` is how big the
2347    // context window is, and redacting it hid a number a person needs to set.
2348    const COUNTS: &[&str] = &[
2349        "_tokens",
2350        "_chars",
2351        "_secs",
2352        "_ms",
2353        "_count",
2354        "_size",
2355        "_hours",
2356        "_days",
2357        "_bytes",
2358        "_iterations",
2359        "_call",
2360    ];
2361    if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
2362        return false;
2363    }
2364    k == "api_key"
2365        || k.ends_with("_key")
2366        || k.contains("token")
2367        || k.contains("secret")
2368        || k.contains("password")
2369}
2370
2371/// A key whose value is a URL the user wrote. Those are printed as they are — a base URL is how you
2372/// check what you configured — but a URL can carry a secret of its own, so its userinfo and its
2373/// secret-named query parameters are scrubbed first.
2374fn is_url_key(key: &str) -> bool {
2375    let k = key.to_ascii_lowercase();
2376    k.ends_with("_url") || k == "remote" || k == "releases"
2377}
2378
2379/// A URL with its secrets taken out, or `None` when there was nothing to take out.
2380///
2381/// Two shapes, both legitimate and both printed verbatim before this existed: a basic-auth gateway
2382/// (`https://user:pw@gw.internal/v1`) and a token in the query
2383/// (`https://mirror/releases?access_token=…`). The URL keeps its shape — scheme, host, path and the
2384/// *names* of its parameters — because that is what makes the printout useful.
2385fn redact_url(text: &str) -> Option<String> {
2386    let (body, fragment) = match text.split_once('#') {
2387        Some((b, f)) => (b, Some(f)),
2388        None => (text, None),
2389    };
2390    let (before_query, query) = match body.split_once('?') {
2391        Some((b, q)) => (b, Some(q)),
2392        None => (body, None),
2393    };
2394    let mut changed = false;
2395
2396    // `scheme://user:pass@host/path`: everything between `//` and the last `@` of the authority is
2397    // credentials. An `@` in the path is not one, which is why this stops at the first `/`.
2398    let head = match before_query.find("://") {
2399        Some(scheme_end) => {
2400            let start = scheme_end + 3;
2401            let rest = &before_query[start..];
2402            let authority_end = rest.find('/').unwrap_or(rest.len());
2403            match rest[..authority_end].rfind('@') {
2404                Some(at) => {
2405                    changed = true;
2406                    format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
2407                }
2408                None => before_query.to_string(),
2409            }
2410        }
2411        None => before_query.to_string(),
2412    };
2413
2414    let query = query.map(|q| {
2415        let pairs: Vec<String> = q
2416            .split('&')
2417            .map(|pair| {
2418                let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
2419                if !name.is_empty() && is_secret_key(name) {
2420                    changed = true;
2421                    format!("{name}=<redacted>")
2422                } else {
2423                    pair.to_string()
2424                }
2425            })
2426            .collect();
2427        pairs.join("&")
2428    });
2429
2430    if !changed {
2431        return None;
2432    }
2433    let mut out = head;
2434    if let Some(q) = query {
2435        out.push('?');
2436        out.push_str(&q);
2437    }
2438    if let Some(f) = fragment {
2439        out.push('#');
2440        out.push_str(f);
2441    }
2442    Some(out)
2443}
2444
2445/// The keys whose shipped spelling is not their Rust default.
2446///
2447/// The file is generated from [`Config::default()`], so everything a struct holds appears without
2448/// anyone maintaining a list — adding a field is enough. The exceptions are the `Option<String>`
2449/// keys, which serialise to nothing when unset and would then be the only settings a person could
2450/// not see. Each ships with the spelling the binary reads as "not in use":
2451///
2452/// - `""` for a path, a route, a profile name or an address nobody has chosen yet;
2453/// - `${VAR:-}` for the two that name a secret, so the value lives in `.env` and a missing
2454///   variable is "no secret" rather than a config that refuses to load. `${VAR}` without `:-`
2455///   is a load error naming the key, which is right for a value a config cannot work without and
2456///   wrong for one it can work without.
2457///
2458/// `reasoning_effort` is here for a different reason: its Rust default is `None` on purpose (an
2459/// undeclared backend must not be handed a field it may reject), while the level a fresh install
2460/// resolves is the shipped `medium`, and the file is where a person reads that.
2461const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
2462    ("provider", "api_key", "${OPENAI_API_KEY:-}"),
2463    ("provider", "api_key_env", ""),
2464    ("provider", "profile", ""),
2465    (
2466        "provider",
2467        "reasoning_effort",
2468        crate::reasoning::SHIPPED_DEFAULT,
2469    ),
2470    ("provider", "aux", ""),
2471    ("provider", "delegate", ""),
2472    ("agent", "output_schema", ""),
2473    ("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
2474    ("web", "default_profile", ""),
2475    ("update", "remote", ""),
2476    ("update", "releases", ""),
2477    // Not a placeholder: the struct default is `allow`, and the shipped file has asked since the
2478    // first install. A fresh install that writes files without a prompt would be a regression in
2479    // everything but the type system, so the stricter value is the one the file carries.
2480    ("tools", "write_file", "ask"),
2481    ("tools", "patch", "ask"),
2482];
2483
2484/// One entry of [`SHIPPED_SPELLING`] as TOML: quoted, escaped, and identical to what
2485/// `toml::Value::String` writes, so a spelling that contains `"` or `\` cannot break the file.
2486fn shipped_text(spelling: &str) -> String {
2487    toml::Value::String(spelling.to_string()).to_string()
2488}
2489
2490/// The order sections appear in the file: the ones a new install edits first, first.
2491const SECTION_ORDER: &[&str] = &[
2492    "provider",
2493    "agent",
2494    "tools",
2495    "flares",
2496    "sessions",
2497    "attachments",
2498    "context",
2499    "plugins",
2500    "cli",
2501    "web",
2502    "gateway",
2503    "update",
2504    "hooks",
2505    "user",
2506    "skills",
2507    "vision",
2508];
2509
2510/// The shipped `config.toml`: every setting this build reads, and no prose.
2511///
2512/// The file is for reading and editing — one key per line, in the section named after the thing it
2513/// configures, with nothing between the lines to scroll past. The explanation for a key is not
2514/// here: it is in the manual `eclipse config docs` renders from [`settings::about`], the same
2515/// string the settings window and `config explain` show. One description per key in the whole
2516/// product, so it cannot drift from the code.
2517///
2518/// Two kinds of line, and the difference is the convention:
2519///
2520/// - `key = value` — the setting is in use at that value. `""` and `[]` are how a key whose "off"
2521///   state is empty is written, and `""` reads back as "not set" ([`empty_is_none`]). A secret is
2522///   `"${VAR:-}"` so its value lives in `.env` and a missing variable means no secret.
2523/// - `# key =` — the setting is not in use, and *no* value could express that: a temperature, a
2524///   cap, a colour, an explicit boolean. TOML has no empty number, so absence is the spelling, and
2525///   a commented line is how the file still shows the key and where it goes. `config set` turns it
2526///   into a real line ([`settings::set_in_text`]).
2527///
2528/// Generated from the schema, never written by hand: `Config::default()` serialised, plus
2529/// [`settings::ABSENT_BY_DEFAULT`] for the keys whose only default is absence, plus
2530/// [`SHIPPED_SPELLING`]. A field added to a struct is in the next `config init` with no second
2531/// edit, and `the_starter_config_carries_every_setting_the_build_reads` asserts the file's keys and
2532/// the catalogue agree exactly, so neither can silently miss one.
2533pub fn starter_config() -> Result<String> {
2534    let defaults = toml::Value::try_from(Config::default())
2535        .map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
2536    let mut out = String::with_capacity(8 * 1024);
2537    out.push_str("# Every setting this build reads, and nothing else.\n");
2538    out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
2539    out.push_str("# A commented key is not in use; an empty value means the same.\n");
2540    out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
2541    for section in SECTION_ORDER {
2542        out.push_str(&format!("\n[{section}]\n"));
2543        let table = defaults.get(*section).and_then(toml::Value::as_table);
2544        let mut lines: Vec<(String, String)> = Vec::new();
2545        let mut nested: Vec<&str> = Vec::new();
2546        if let Some(table) = table {
2547            for (key, value) in table {
2548                match value {
2549                    toml::Value::Table(_) => nested.push(key.as_str()),
2550                    other => {
2551                        let shipped = SHIPPED_SPELLING
2552                            .iter()
2553                            .find(|(s, k, _)| s == section && k == key)
2554                            .map(|(_, _, spelling)| shipped_text(spelling));
2555                        lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
2556                    }
2557                }
2558            }
2559        }
2560        // Keys whose default is absence: visible, and set to nothing. A key the struct *does*
2561        // write is never doubled — the schema and the hand-written list cannot disagree here.
2562        for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
2563            if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
2564                let shipped = SHIPPED_SPELLING
2565                    .iter()
2566                    .find(|(s, k, _)| s == section && k == key)
2567                    .map(|(_, _, spelling)| shipped_text(spelling));
2568                lines.push(((*key).to_string(), shipped.unwrap_or_default()));
2569            }
2570        }
2571        lines.sort();
2572        for (key, text) in lines {
2573            if text.is_empty() {
2574                out.push_str(&format!("# {key} =\n"));
2575            } else {
2576                out.push_str(&format!("{key} = {text}\n"));
2577            }
2578        }
2579        // A hook's own options are a table, not a setting, and are written as one so the block is
2580        // copy-pasteable. `[hooks.<name>]` for a hook that is not in `order` is a parse error, so
2581        // this follows the serialised default exactly rather than adding anything.
2582        nested.sort();
2583        for key in nested {
2584            let Some(sub) = table.and_then(|t| t.get(key)) else {
2585                continue;
2586            };
2587            let mut wrapped = toml::map::Map::new();
2588            wrapped.insert(key.to_string(), sub.clone());
2589            if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
2590                out.push('\n');
2591                out.push_str(&text);
2592            }
2593        }
2594        // The hook that is on by default has no settings table in the default config (its options
2595        // are optional), and `order` has to name a hook this build has. Its block is written
2596        // empty, with each key it accepts named and commented: the one place a table's shape comes
2597        // from the hook's own declaration rather than from a hand-written section.
2598        if *section == "hooks" {
2599            let default_hooks = Config::default().hooks;
2600            for name in &default_hooks.order {
2601                if default_hooks.settings.contains_key(name) {
2602                    continue;
2603                }
2604                let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
2605                    continue;
2606                };
2607                out.push_str(&format!("\n[hooks.{name}]\n"));
2608                let mut keys = info.settings.to_vec();
2609                keys.sort_unstable();
2610                for key in keys {
2611                    out.push_str(&format!("# {key} =\n"));
2612                }
2613            }
2614        }
2615    }
2616    Ok(out)
2617}
2618
2619/// Every variable the shipped `.env` lists, in the order it lists them, with empty values.
2620///
2621/// Empty is the whole point: with [`Dotenv`] treating an empty assignment as absent — the same as
2622/// the line not being there — a file that names every variable and sets none of them behaves
2623/// exactly like a file with one line in it, and it is a directory of what can be set.
2624///
2625/// Only variables that are actually read from `.env` are here. `ECLIPSE_HOME`, `ECLIPSE_CONFIG` and
2626/// `ECLIPSE_PROFILE` are read to *find* the file, so a `.env` cannot set them ([`ENV_SHELL_ONLY`]),
2627/// and the rest are plumbing this tool puts in a child's environment ([`ENV_INTERNAL`]).
2628pub const ENV_TEMPLATE: &[&str] = &[
2629    "ECLIPSE_BASE_URL",
2630    "ECLIPSE_MODEL",
2631    "ECLIPSE_API_KEY",
2632    "ECLIPSE_REASONING_EFFORT",
2633    "ECLIPSE_ROUTE",
2634    "OPENAI_API_KEY",
2635    "ECLIPSE_WEB_AUTH_TOKEN",
2636    "ECLIPSE_WEB_USER",
2637    "ECLIPSE_WEB_PASSWORD_HASH",
2638];
2639
2640/// One line per variable, for the manual: what it is for.
2641///
2642/// The `.env` is shipped as a list of names and nothing else — a name with no explanation is a
2643/// puzzle, and the explanation does not belong in a secrets file. This table is the other half,
2644/// and [`every_classified_variable_has_a_description`] keeps it level with the three lists above.
2645pub const ENV_ABOUT: &[(&str, &str)] = &[
2646    ("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
2647    ("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
2648    ("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
2649    ("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
2650    ("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
2651    ("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
2652    ("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
2653    ("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
2654    ("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
2655    ("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
2656    ("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
2657    ("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
2658    ("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
2659    ("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
2660    ("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"),
2661    ("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
2662    ("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
2663    ("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
2664    ("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
2665    ("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
2666];
2667
2668/// What one variable is for, or `""` — the same lookup shape as [`settings::about`].
2669pub fn env_about(name: &str) -> &'static str {
2670    ENV_ABOUT
2671        .iter()
2672        .find(|(n, _)| *n == name)
2673        .map(|(_, about)| *about)
2674        .unwrap_or("")
2675}
2676
2677/// Variables read before a `.env` is opened, or from the process environment only. Setting one of
2678/// these *inside* `.env` would be inert, which is worse than absent: it looks like a setting.
2679pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];
2680
2681/// Variables this tool sets in a child's environment (a plugin, an MCP server, a spawned tool
2682/// call). Nobody sets these by hand, and a value in `.env` would be overwritten anyway.
2683pub const ENV_INTERNAL: &[&str] = &[
2684    "ECLIPSE_BIN",
2685    "ECLIPSE_ARGS",
2686    "ECLIPSE_ARGS_BYTES",
2687    "ECLIPSE_TOOL",
2688    "ECLIPSE_TOOL_SOCKET",
2689    "ECLIPSE_WORKSPACE",
2690    "ECLIPSE_PLUGIN_DIR",
2691    "ECLIPSE_SCRIPTS_DIR",
2692];
2693
2694/// The shipped `.env`: every variable, nothing set, and the dashboard token already generated.
2695///
2696/// The token is the one value a first install cannot invent for you — the dashboard refuses to
2697/// start without it — so `config init` fills exactly that one line and leaves the rest empty.
2698pub fn starter_env(token: &str) -> String {
2699    let mut out = String::with_capacity(1024);
2700    out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
2701    out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
2702    for name in ENV_TEMPLATE {
2703        if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
2704            out.push_str(&format!("{name}={token}\n"));
2705        } else {
2706            out.push_str(&format!("{name}=\n"));
2707        }
2708    }
2709    out
2710}
2711
2712/// The file a named profile starts from: an overlay, not a whole config. Only the keys a
2713/// profile usually changes are here, uncommented examples included — a profile that restated
2714/// every default would pin them, and then a change to the base config would stop reaching it.
2715pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
2716# Examples are commented out on purpose — an empty value here *replaces* the base value.
2717
2718[provider]
2719# base_url = "http://127.0.0.1:8080/v1"
2720# model = "qwen3-coder:30b"
2721# profile = "llamacpp"
2722
2723[tools]
2724# shell = "ask"
2725"#;
2726
2727/// What `config init` did, so the caller can report it without re-deriving paths.
2728#[derive(Debug, Clone, PartialEq, Eq)]
2729pub struct InitReport {
2730    pub config: PathBuf,
2731    pub dotenv: PathBuf,
2732    /// False when a `.env` was already there: an existing file holds secrets and is never
2733    /// overwritten, not even by `--force`.
2734    pub dotenv_written: bool,
2735}
2736
2737/// Write the starter config, and the `.env` **where the loader will read it**, with a freshly
2738/// generated dashboard token (the token is never returned or printed).
2739///
2740/// Refuses to overwrite the config unless `force`. The `.env` is *never* overwritten: it
2741/// holds the user's secrets, and consent to replace a config is not consent to lose those.
2742/// Both files are created `0600` on Unix.
2743///
2744/// The two files are not always neighbours: `[dotenv]` is read from the config *directory*
2745/// (`$ECLIPSE_HOME`, or `~/.eclipse`) whatever `--config` points at, so a `.env` written beside a
2746/// `--config /other/config.toml` would never be opened — `config init` would report a token that
2747/// the next start cannot see. Without a home directory there is no place the loader reads, and the
2748/// file goes beside the config as before.
2749pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
2750    if path.exists() && !force {
2751        return Err(Error::Config(format!(
2752            "{} already exists (use --force to overwrite)",
2753            path.display()
2754        )));
2755    }
2756    let dir = path.parent().unwrap_or(Path::new("."));
2757    std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2758    write_private(path, &starter_config()?)?;
2759
2760    let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
2761    std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
2762    let dotenv = secrets_dir.join(".env");
2763    let mut dotenv_written = false;
2764    if !dotenv.exists() {
2765        let token = crate::token::generate()?;
2766        write_private(&dotenv, &starter_env(&token))?;
2767        dotenv_written = true;
2768    }
2769    // The template this file was generated from, kept so a later version can tell "the operator
2770    // chose this" from "we shipped this" (`config migrate`). Best effort: a config that was written
2771    // is a config that works, and a missing baseline costs nothing but a kept default.
2772    let _ = migrate::write_baseline(path);
2773    Ok(InitReport {
2774        config: path.to_path_buf(),
2775        dotenv,
2776        dotenv_written,
2777    })
2778}
2779
2780/// The value `[section] key = ...` holds in this TOML text, unquoted, if the key is set.
2781/// Commented-out template lines do not count: they are documentation, not config.
2782pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
2783    let mut in_section = false;
2784    for line in text.lines() {
2785        let trimmed = line.trim();
2786        if let Some(name) = section_header(trimmed) {
2787            in_section = name == section;
2788            continue;
2789        }
2790        if !in_section || trimmed.starts_with('#') {
2791            continue;
2792        }
2793        if let Some((k, v)) = key_value(trimmed) {
2794            if k == key {
2795                return Some(v);
2796            }
2797        }
2798    }
2799    None
2800}
2801
2802/// Set `[section] key = "value"` in this TOML text and return the whole text back.
2803///
2804/// Everything the wizard does not ask about survives untouched — comments, ordering, other
2805/// sections — because this rewrites one line rather than re-serialising the config. An
2806/// uncommented line is replaced in place; a commented template line (`# key = ...`) becomes
2807/// the real one; otherwise the key is added under the section header, and the section itself
2808/// is appended if it was missing.
2809pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
2810    toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
2811}
2812
2813/// Set `[section] key = <value>` where `value` is already TOML — `9000`, `true`, `["a", "b"]`,
2814/// `"text"` with its quotes. The line-editing rules are [`toml_set_string`]'s.
2815pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
2816    place_line(text, section, key, &format!("{key} = {value}"))
2817}
2818
2819// ── `[[mcp]]` entries (`#352`) ────────────────────────────────────────────────────────────────
2820//
2821// An entry is an array-of-tables *block*, not a line, so `place_line` cannot reach it: it edits one
2822// key inside one section. These three writers therefore work on line ranges, and each touches only
2823// the block it names — a `mcp add` leaves every hand-written entry, and every comment around it,
2824// exactly as it was. Re-rendering the whole file from the parsed config would be far less code and
2825// would delete every comment a person wrote, which is the one thing `toml_set_value` exists to
2826// avoid.
2827
2828/// One `[[mcp]]` block: its line range (`end` exclusive) and the name it declares, if the block
2829/// reads at all. A malformed block keeps its place and has no name, so no name-based verb can
2830/// silently match it.
2831struct McpSpan {
2832    name: Option<String>,
2833    start: usize,
2834    end: usize,
2835}
2836
2837fn is_table_header(trimmed: &str) -> bool {
2838    trimmed.starts_with('[')
2839}
2840
2841fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
2842    let mut spans: Vec<McpSpan> = Vec::new();
2843    let mut open: Option<usize> = None;
2844    let mut closed_by_header = true;
2845    for (i, line) in lines.iter().enumerate() {
2846        let trimmed = line.trim();
2847        if open.is_some() && is_table_header(trimmed) {
2848            if let Some(start) = open.take() {
2849                spans.push(McpSpan {
2850                    name: None,
2851                    start,
2852                    end: i,
2853                });
2854                closed_by_header = true;
2855            }
2856        }
2857        if trimmed == "[[mcp]]" {
2858            open = Some(i);
2859        }
2860    }
2861    if let Some(start) = open {
2862        spans.push(McpSpan {
2863            name: None,
2864            start,
2865            end: lines.len(),
2866        });
2867        closed_by_header = false;
2868    }
2869    // A block ends where the next one *starts being described*, not where its header sits: blank
2870    // lines and the comment directly above the next `[[mcp]]` are the next entry's. Trimming them
2871    // here is what keeps `disabled` out from under that comment, and what stops a removal from
2872    // taking the neighbour's note with it. The last block keeps its trailing lines — at the end of
2873    // the file there is nobody else they could belong to.
2874    let count = spans.len();
2875    for (i, span) in spans.iter_mut().enumerate() {
2876        let at_eof = i + 1 == count && !closed_by_header;
2877        while span.end > span.start + 1 {
2878            let tail = lines[span.end - 1].trim();
2879            let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
2880            if tail.is_empty() || belongs_to_next {
2881                span.end -= 1;
2882            } else {
2883                break;
2884            }
2885        }
2886    }
2887    for span in &mut spans {
2888        let body = lines[span.start + 1..span.end].join("\n");
2889        span.name = toml::from_str::<crate::mcp::Spec>(&body)
2890            .ok()
2891            .map(|spec| spec.name);
2892    }
2893    spans
2894}
2895
2896/// Collapse runs of blank lines left behind by a removal. Comments are never touched: a file that
2897/// gains a double blank line is untidy, and a file that loses somebody's note is broken.
2898fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
2899    let mut end = lines.len();
2900    while end > 0 && lines[end - 1].trim().is_empty() {
2901        end -= 1;
2902    }
2903    let mut out: Vec<String> = Vec::with_capacity(end);
2904    let mut blanks = 0;
2905    for line in &lines[..end] {
2906        if line.trim().is_empty() {
2907            blanks += 1;
2908            if blanks > 1 {
2909                continue;
2910            }
2911        } else {
2912            blanks = 0;
2913        }
2914        out.push(line.clone());
2915    }
2916    out
2917}
2918
2919/// How one entry is written back out: only the keys it actually sets, in the order the docs list
2920/// them. Rendering the whole struct would emit `args = []`, `env = []`, `policies = {}` and every
2921/// default beside the two lines a person meant to write.
2922fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
2923    let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
2924    let mut out = String::from("[[mcp]]\n");
2925    out.push_str(&format!("name = {}\n", quote(&entry.name)));
2926    if entry.transport == crate::mcp::Transport::Http {
2927        out.push_str("transport = \"http\"\n");
2928    }
2929    if !entry.command.is_empty() {
2930        out.push_str(&format!("command = {}\n", quote(&entry.command)));
2931    }
2932    if !entry.args.is_empty() {
2933        let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
2934        out.push_str(&format!("args = [{}]\n", args.join(", ")));
2935    }
2936    if let Some(url) = &entry.url {
2937        out.push_str(&format!("url = {}\n", quote(url)));
2938    }
2939    if let Some(var) = &entry.token_env {
2940        out.push_str(&format!("token_env = {}\n", quote(var)));
2941    }
2942    if entry.cwd != crate::plugins::Cwd::default() {
2943        let cwd = match entry.cwd {
2944            crate::plugins::Cwd::Workspace => "workspace",
2945            crate::plugins::Cwd::Plugin => "plugin",
2946        };
2947        out.push_str(&format!("cwd = \"{cwd}\"\n"));
2948    }
2949    if let Some(secs) = entry.timeout_secs {
2950        out.push_str(&format!("timeout_secs = {secs}\n"));
2951    }
2952    if entry.policy != Policy::Ask {
2953        let policy = match entry.policy {
2954            Policy::Deny => "deny",
2955            Policy::Ask => "ask",
2956            Policy::Allow => "allow",
2957        };
2958        out.push_str(&format!("policy = \"{policy}\"\n"));
2959    }
2960    if !entry.policies.is_empty() {
2961        let pairs: Vec<String> = entry
2962            .policies
2963            .iter()
2964            .map(|(tool, policy)| {
2965                let policy = match policy {
2966                    Policy::Deny => "deny",
2967                    Policy::Ask => "ask",
2968                    Policy::Allow => "allow",
2969                };
2970                format!("{tool} = \"{policy}\"")
2971            })
2972            .collect();
2973        out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
2974    }
2975    if !entry.prefix.is_empty() {
2976        out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
2977    }
2978    if !entry.env.is_empty() {
2979        let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
2980        out.push_str(&format!("env = [{}]\n", env.join(", ")));
2981    }
2982    if entry.override_builtin {
2983        out.push_str("override = true\n");
2984    }
2985    if entry.disabled {
2986        out.push_str("disabled = true\n");
2987    }
2988    out
2989}
2990
2991/// Add `[[mcp]]` entry — to `config.toml`, which is the file this edits (`#352`).
2992pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
2993    entry
2994        .validate()
2995        .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
2996    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
2997    let spans = mcp_spans(&lines);
2998    if let Some(existing) = spans
2999        .iter()
3000        .find(|s| s.name.as_deref() == Some(&entry.name))
3001    {
3002        return Err(format!(
3003            "`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
3004            entry.name,
3005            existing.start + 1,
3006            entry.name
3007        ));
3008    }
3009    let rendered = render_mcp_entry(entry);
3010    match spans.last() {
3011        Some(last) => {
3012            let at = last.end;
3013            let mut fresh: Vec<String> = Vec::new();
3014            // One blank line between entries; a block that already ends with one does not get two.
3015            if at > 0 && !lines[at - 1].trim().is_empty() {
3016                fresh.push(String::new());
3017            }
3018            fresh.extend(rendered.lines().map(str::to_string));
3019            lines.splice(at..at, fresh);
3020        }
3021        None => {
3022            if lines.last().is_some_and(|l| !l.trim().is_empty()) {
3023                lines.push(String::new());
3024            }
3025            lines.extend(rendered.lines().map(str::to_string));
3026        }
3027    }
3028    let out = join_lines(tidy_blanks(lines));
3029    readback_mcp(&out, &entry.name, |spec| spec == entry)
3030}
3031
3032/// Remove the `[[mcp]]` entry called `name`. Only that block goes.
3033pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
3034    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3035    let spans = mcp_spans(&lines);
3036    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3037        let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3038        return Err(if known.is_empty() {
3039            format!("no `[[mcp]]` entry for `{name}` in this file")
3040        } else {
3041            format!(
3042                "no `[[mcp]]` entry for `{name}`; this file declares {}",
3043                known.join(", ")
3044            )
3045        });
3046    };
3047    // A comment directly above the header describes this entry, so it goes with it — stopping at
3048    // the first blank line, which is where the previous entry's own trailing note lives.
3049    let mut start = span.start;
3050    while start > 0 && lines[start - 1].trim_start().starts_with('#') {
3051        start -= 1;
3052    }
3053    // Take the blank line *after* the block with it when there is one, so removing an entry does
3054    // not leave a hole where the next entry's separation used to be.
3055    let mut end = span.end;
3056    if end < lines.len() && lines[end].trim().is_empty() {
3057        end += 1;
3058    }
3059    lines.drain(start..end);
3060    readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
3061}
3062
3063/// Switch an entry off (or back on) in place: `disabled = true` inside its own block.
3064pub fn mcp_set_disabled(
3065    text: &str,
3066    name: &str,
3067    disabled: bool,
3068) -> std::result::Result<String, String> {
3069    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3070    let spans = mcp_spans(&lines);
3071    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3072        return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
3073    };
3074    let line = if disabled {
3075        "disabled = true".to_string()
3076    } else {
3077        // Written rather than deleted: a person reading the file sees the server was switched off
3078        // deliberately, and the loader treats `false` exactly like absence.
3079        "disabled = false".to_string()
3080    };
3081    let body = span.start + 1..span.end;
3082    match lines[body.clone()].iter().position(|l| {
3083        l.trim_start()
3084            .strip_prefix("disabled")
3085            .is_some_and(|rest| rest.trim_start().starts_with('='))
3086    }) {
3087        Some(offset) => lines[span.start + 1 + offset] = line,
3088        None => lines.insert(span.end, line),
3089    }
3090    readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
3091}
3092
3093/// Change the `[[mcp]]` entry called `name` in place (`#517`).
3094///
3095/// `change` is handed **the entry the file declares**, not a shape from a form: a key the surface
3096/// does not show (`disabled`, `env`, `policies`, `override`, `cwd`) is not a key the person cleared.
3097/// The text that comes back differs only in the lines whose *value* changed, which is why both
3098/// renderings are compared: a hand-written entry keeps its own quoting, its own order and every
3099/// comment, and a field set back to its default loses its line rather than gaining a default one.
3100/// The rename is refused rather than done, because a rename is a remove and an add.
3101pub fn mcp_update(
3102    text: &str,
3103    name: &str,
3104    change: impl FnOnce(&mut crate::mcp::Spec),
3105) -> std::result::Result<String, String> {
3106    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3107    let spans = mcp_spans(&lines);
3108    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3109        let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3110        return Err(if known.is_empty() {
3111            format!("no `[[mcp]]` entry for `{name}` in this file")
3112        } else {
3113            format!(
3114                "no `[[mcp]]` entry for `{name}`; this file declares {}",
3115                known.join(", ")
3116            )
3117        });
3118    };
3119    let body = lines[span.start + 1..span.end].join("\n");
3120    let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
3121        format!(
3122            "the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
3123            span.start + 1,
3124            crate::config::settings::one_line(&e.to_string())
3125        )
3126    })?;
3127    let mut after = before.clone();
3128    change(&mut after);
3129    if after.name != name {
3130        return Err(format!(
3131            "an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
3132             name instead"
3133        ));
3134    }
3135    after
3136        .validate()
3137        .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3138    let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
3139        render_mcp_entry(spec)
3140            .lines()
3141            .skip(1) // the `[[mcp]]` header, which stays where it is
3142            .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
3143            .collect()
3144    };
3145    let (old, new) = (rendered(&before), rendered(&after));
3146    let (mut start, mut end) = (span.start + 1, span.end);
3147    // Walk the block one key (plus its continuation lines) at a time and keep everything the new
3148    // entry still says in the same place.
3149    let block: Vec<String> = lines[start..end].to_vec();
3150    let mut rebuilt: Vec<String> = Vec::new();
3151    let mut seen: Vec<String> = Vec::new();
3152    let mut i = 0;
3153    while i < block.len() {
3154        let line = &block[i];
3155        let trimmed = line.trim();
3156        if trimmed.is_empty() || trimmed.starts_with('#') {
3157            rebuilt.push(line.clone());
3158            i += 1;
3159            continue;
3160        }
3161        let first = i;
3162        let mut depth = bracket_depth(line);
3163        i += 1;
3164        while depth > 0 && i < block.len() {
3165            depth += bracket_depth(&block[i]);
3166            i += 1;
3167        }
3168        match key_of(&block[first]) {
3169            Some(key) => {
3170                seen.push(key.clone());
3171                match (old.get(&key), new.get(&key)) {
3172                    // Unchanged: the file's own line, byte for byte.
3173                    (Some(was), Some(is)) if was == is => {
3174                        rebuilt.extend(block[first..i].iter().cloned())
3175                    }
3176                    (_, Some(is)) => rebuilt.push(is.clone()),
3177                    // Cleared to its default: the line goes, and nothing else moves.
3178                    (_, None) => {}
3179                }
3180            }
3181            // A line that names no key is somebody's text; it is never dropped.
3182            None => rebuilt.extend(block[first..i].iter().cloned()),
3183        }
3184    }
3185    for (key, line) in &new {
3186        if !seen.contains(key) {
3187            rebuilt.push(line.clone());
3188        }
3189    }
3190    start = start.min(lines.len());
3191    end = end.min(lines.len());
3192    lines.splice(start..end, rebuilt);
3193    let out = join_lines(lines);
3194    readback_mcp(&out, name, |spec| spec == &after)
3195}
3196
3197/// The `key` of a `key = value` line, or `None` for a comment, a blank line or a continuation.
3198fn key_of(line: &str) -> Option<String> {
3199    let trimmed = line.trim();
3200    if trimmed.starts_with('#') {
3201        return None;
3202    }
3203    let (key, _) = trimmed.split_once('=')?;
3204    let key = key.trim();
3205    let plain = !key.is_empty()
3206        && !key.contains(char::is_whitespace)
3207        && key
3208            .chars()
3209            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
3210    plain.then(|| key.to_string())
3211}
3212
3213/// How many brackets a line opens: a value that ends above zero continues on the next line.
3214/// Quotes are honoured, so an `args = ["a=b"]` is still one line.
3215fn bracket_depth(line: &str) -> i32 {
3216    let mut depth = 0;
3217    let mut quote: Option<char> = None;
3218    let mut escaped = false;
3219    for c in line.chars() {
3220        if let Some(q) = quote {
3221            if escaped {
3222                escaped = false;
3223            } else if c == '\\' {
3224                escaped = true;
3225            } else if c == q {
3226                quote = None;
3227            }
3228            continue;
3229        }
3230        match c {
3231            '"' | '\'' => quote = Some(c),
3232            '[' | '{' => depth += 1,
3233            ']' | '}' => depth -= 1,
3234            '#' => break, // a trailing comment is prose, not value
3235            _ => {}
3236        }
3237    }
3238    depth
3239}
3240
3241/// The guard every writer here shares, in `set_in_text`'s voice: the text must load, and the entry
3242/// it names must read back as what was asked. Anything else means nothing is written.
3243fn readback_mcp(
3244    text: &str,
3245    name: &str,
3246    ok: impl Fn(&crate::mcp::Spec) -> bool,
3247) -> std::result::Result<String, String> {
3248    let cfg = parse_text(text).map_err(|e| {
3249        format!(
3250            "that would not load, so nothing was saved: {}",
3251            settings::one_line(&e.to_string())
3252        )
3253    })?;
3254    match cfg.mcp.iter().find(|s| s.name == name) {
3255        Some(spec) if ok(spec) => Ok(text.to_string()),
3256        Some(_) => {
3257            Err("the file would not read that entry back as written; nothing was saved".into())
3258        }
3259        None => Err(format!(
3260            "the edit lost `{name}` on the way back in; nothing was saved"
3261        )),
3262    }
3263}
3264
3265fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
3266    let cfg = parse_text(text).map_err(|e| {
3267        format!(
3268            "that would not load, so nothing was saved: {}",
3269            settings::one_line(&e.to_string())
3270        )
3271    })?;
3272    if cfg.mcp.iter().any(|s| s.name == name) {
3273        return Err(format!("`{name}` survived the removal; nothing was saved"));
3274    }
3275    Ok(text.to_string())
3276}
3277
3278/// Replace the line for `[section] key` with `replacement`, or insert one after the section header.
3279///
3280/// The one traversal both a value and a comment go through, so "where a key's line goes" is decided
3281/// once: a commented `# key = …` in that section is the line to replace, and a section with neither
3282/// gets the line directly under its header.
3283fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
3284    let quoted = replacement.to_string();
3285    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3286    let mut in_section = false;
3287    let mut header_at: Option<usize> = None;
3288    let mut commented_at: Option<usize> = None;
3289    for (i, line) in lines.iter().enumerate() {
3290        let trimmed = line.trim();
3291        if let Some(name) = section_header(trimmed) {
3292            in_section = name == section;
3293            if in_section && header_at.is_none() {
3294                header_at = Some(i);
3295            }
3296            continue;
3297        }
3298        if !in_section {
3299            continue;
3300        }
3301        if let Some((k, _)) = key_value(trimmed) {
3302            if k == key {
3303                lines[i] = quoted;
3304                return join_lines(lines);
3305            }
3306        } else if let Some(rest) = trimmed.strip_prefix('#') {
3307            // `# key = "default"` is how the starter documents an optional key.
3308            if let Some((k, _)) = key_value(rest.trim()) {
3309                if k == key && commented_at.is_none() {
3310                    commented_at = Some(i);
3311                }
3312            }
3313        }
3314    }
3315    match (header_at, commented_at) {
3316        (_, Some(i)) => lines[i] = quoted,
3317        (Some(i), None) => lines.insert(i + 1, quoted),
3318        (None, None) => {
3319            lines.push(String::new());
3320            lines.push(format!("[{section}]"));
3321            lines.push(quoted);
3322        }
3323    }
3324    join_lines(lines)
3325}
3326
3327/// Insert `# key =` under `[section]`, which is how a shipped file says "this key exists and is not
3328/// in use" for a key whose off state has no spelling (a number, a colour, an explicit boolean).
3329///
3330/// The companion to [`toml_set_value`], and deliberately not a call to it with a `#` in the key:
3331/// this line is *inert*, and a migration that wrote it as a value would be imposing something.
3332pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
3333    place_line(text, section, key, &format!("# {key} ="))
3334}
3335
3336/// Write `config_version = N` into this TOML text, at the top, where the generated file puts it.
3337///
3338/// Top-level because it describes the file and must survive a section being renamed, and replacing
3339/// the existing line rather than appending keeps it at the top of a file that already has one.
3340pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
3341    let line = format!("config_version = {version}");
3342    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3343    if let Some(at) = lines.iter().position(|l| {
3344        l.trim_start()
3345            .strip_prefix("config_version")
3346            .is_some_and(|rest| rest.trim_start().starts_with('='))
3347    }) {
3348        lines[at] = line;
3349    } else {
3350        // Under the header comments and above the first table: TOML wants top-level scalars before
3351        // the first `[section]`, and the header comment is the file's own front page. The spacing
3352        // is normalised to what `config init` writes — no blank line above the stamp, one below —
3353        // so a migrated file and a fresh one cannot be told apart by looking at them.
3354        let first_table = lines
3355            .iter()
3356            .position(|l| section_header(l.trim()).is_some())
3357            .unwrap_or(lines.len());
3358        let mut insert_at = 0;
3359        while insert_at < first_table
3360            && (lines[insert_at].trim_start().starts_with('#')
3361                || lines[insert_at].trim().is_empty())
3362        {
3363            insert_at += 1;
3364        }
3365        lines.insert(insert_at, String::new());
3366        lines.insert(insert_at, line);
3367        while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
3368            lines.remove(insert_at - 1);
3369            insert_at -= 1;
3370        }
3371    }
3372    let out = join_lines(lines);
3373    // Proved, like every other write here: a file that does not parse afterwards is not written.
3374    parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
3375    Ok(out)
3376}
3377
3378/// Comment `[section] key = …` out of this TOML text, so the file falls back to the default.
3379///
3380/// Commented, not deleted: the neighbours of that line explain the key, and a person who unsets
3381/// `web.port` should still be able to see what it is called. A key that is not there at all is
3382/// left alone — unsetting what is already unset is not an error.
3383pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
3384    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3385    let mut in_section = false;
3386    for line in lines.iter_mut() {
3387        let trimmed = line.trim();
3388        if let Some(name) = section_header(trimmed) {
3389            in_section = name == section;
3390            continue;
3391        }
3392        if !in_section || trimmed.starts_with('#') {
3393            continue;
3394        }
3395        if let Some((k, _)) = key_value(trimmed) {
3396            if k == key {
3397                let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
3398                *line = format!("{indent}# {trimmed}");
3399                return join_lines(lines);
3400            }
3401        }
3402    }
3403    join_lines(lines)
3404}
3405
3406/// `[section]` → `section`, and nothing else (a `[[table]]` array header is not a section we
3407/// edit, and `[a.b]` is its own name, not `a`).
3408pub(crate) fn section_header(trimmed: &str) -> Option<&str> {
3409    if trimmed.starts_with("[[") {
3410        return None;
3411    }
3412    let rest = trimmed.strip_prefix('[')?;
3413    let name = rest.strip_suffix(']')?;
3414    if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
3415        return None;
3416    }
3417    Some(name)
3418}
3419
3420/// `key = value` → (`key`, unquoted value). Anything without an `=` or with an empty key is
3421/// not a key/value line.
3422pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
3423    let (k, v) = trimmed.split_once('=')?;
3424    let k = k.trim();
3425    if k.is_empty() || k.contains([' ', '"', '\\']) {
3426        return None;
3427    }
3428    let v = v.trim();
3429    let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
3430        Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
3431        None => v.to_string(),
3432    };
3433    Some((k, unquoted))
3434}
3435
3436fn escape_toml(value: &str) -> String {
3437    value.replace('\\', "\\\\").replace('"', "\\\"")
3438}
3439
3440fn join_lines(lines: Vec<String>) -> String {
3441    let mut out = lines.join("\n");
3442    if !out.ends_with('\n') {
3443        out.push('\n');
3444    }
3445    out
3446}
3447
3448/// Write config text back with the same permissions as the starter (`0600`) — the file can
3449/// carry `api_key`, and a config people paste into bug reports should still be readable only
3450/// by them.
3451pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
3452    write_private(path, text)
3453}
3454
3455/// Parse config text exactly as the loader would. A writer uses this to prove what it is
3456/// about to save is loadable *before* it replaces the user's file.
3457pub fn parse_text(text: &str) -> Result<Config> {
3458    let cfg: Config =
3459        toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3460    crate::hooks::validate(&cfg.hooks)
3461        .map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3462    Ok(cfg)
3463}
3464
3465/// Set `KEY=value` in a `.env`, creating it `0600` if it does not exist. An existing line for
3466/// that key is replaced; every other line, comment included, is kept. Values are written raw:
3467/// a `.env` is not TOML and the loader takes the rest of the line as the value.
3468pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
3469    let existing = std::fs::read_to_string(path).unwrap_or_default();
3470    let line = format!("{key}={value}");
3471    let mut out = String::new();
3472    let mut replaced = false;
3473    for l in existing.lines() {
3474        let is_key = l
3475            .trim_start()
3476            .strip_prefix(key)
3477            .map(|rest| rest.starts_with('='))
3478            .unwrap_or(false);
3479        if is_key {
3480            out.push_str(&line);
3481            out.push('\n');
3482            replaced = true;
3483        } else {
3484            out.push_str(l);
3485            out.push('\n');
3486        }
3487    }
3488    if !replaced {
3489        if !out.is_empty() && !out.ends_with('\n') {
3490            out.push('\n');
3491        }
3492        out.push_str(&line);
3493        out.push('\n');
3494    }
3495    write_private(path, &out)
3496}
3497
3498/// The value of `KEY` in a `.env` file, if it has one.
3499pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
3500    std::fs::read_to_string(path).ok()?.lines().find_map(|l| {
3501        let rest = l.trim_start().strip_prefix(key)?;
3502        let value = rest.strip_prefix('=')?;
3503        Some(value.trim().to_string())
3504    })
3505}
3506
3507/// Write a file that only its owner may read: created `0600` on Unix, and replaced in place
3508/// rather than appended to.
3509pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
3510    // `#408`: this truncated the file before writing it, so a crash, a full disk or a `kill -9`
3511    // between the two left a zero-length `config.toml` — which loads as *defaults*, so every
3512    // `provider.*` value silently vanished. Write beside and rename instead; `0600` is set on the
3513    // temporary file, so there is no window where the secrets are readable by anyone else.
3514    crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
3515}
3516
3517#[test]
3518fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
3519    // The rule from #295: an empty value *is* absence. So `key = ""` has to be writable, and it has
3520    // to verify — which it could not while `set_in_text` demanded the value come back as `""`. The
3521    // 0.9.0-shaped file (every key commented) exposed it: a migration adding 78 keys hit the first
3522    // empty-string key and refused the whole file.
3523    let text = starter_config().unwrap();
3524    let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
3525    assert_eq!(
3526        Config::from_toml_str(&without).unwrap().agent.output_schema,
3527        None
3528    );
3529    let back = settings::set_in_text(
3530        &without,
3531        "agent.output_schema",
3532        &toml::Value::String(String::new()),
3533    )
3534    .expect("an empty value can be written");
3535    assert!(back.contains("output_schema = \"\""), "{back}");
3536    assert_eq!(
3537        Config::from_toml_str(&back).unwrap().agent.output_schema,
3538        None,
3539        "and it reads as unset, which is what it means"
3540    );
3541    assert_eq!(
3542        toml_value(&back, "agent", "output_schema"),
3543        Some(String::new()),
3544        "the line is there; what it holds is nothing"
3545    );
3546}
3547
3548#[cfg(test)]
3549mod tests {
3550    // ---------------------------------------------------------------------------------------
3551    // `#171`: two route keys say how many flares a route holds, and `[flares]` says what a run
3552    // costs. The arithmetic that combines them lives in `flares::slots`, but the reading of the
3553    // keys is here.
3554    // ---------------------------------------------------------------------------------------
3555
3556    #[test]
3557    fn a_route_can_say_how_many_flares_it_holds() {
3558        let cfg = Config::from_toml_str(
3559            r#"
3560[provider]
3561fallback = ["local", "cloud"]
3562
3563[[provider.route]]
3564name = "local"
3565base_url = "http://127.0.0.1:8080/v1"
3566model = "qwen"
3567profile = "llamacpp"
3568group = "gpu0"
3569max_parallel = 2
3570
3571[[provider.route]]
3572name = "cloud"
3573base_url = "https://api.example.com/v1"
3574model = "big"
3575"#,
3576        )
3577        .unwrap();
3578        let routes = cfg.declared_routes();
3579        let local = routes.iter().find(|r| r.name == "local").unwrap();
3580        assert_eq!(local.parallel(), 2, "the route said two slots");
3581        assert_eq!(local.group.as_deref(), Some("gpu0"));
3582        let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
3583        // An API states no shape, so the profile decides: openai is four, a local server one.
3584        assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
3585        assert!(cloud.group.is_none());
3586        assert_eq!(
3587            local.default_parallel(),
3588            1,
3589            "llamacpp serves one model at a time"
3590        );
3591
3592        // `0` is read as `1`: a route with no slot is a route flares cannot use, and starving
3593        // them silently is worse than a slow run.
3594        let zero = Config::from_toml_str(
3595            r#"
3596[[provider.route]]
3597name = "local"
3598base_url = "http://127.0.0.1:8080/v1"
3599model = "qwen"
3600max_parallel = 0
3601"#,
3602        )
3603        .unwrap();
3604        assert_eq!(zero.declared_routes()[0].parallel(), 1);
3605
3606        // A wrong type is the route's error, not a mysterious one about `provider.route`.
3607        let bad = Config::from_toml_str(
3608            r#"
3609[[provider.route]]
3610name = "local"
3611base_url = "http://127.0.0.1:8080/v1"
3612model = "qwen"
3613max_parallel = "two"
3614"#,
3615        )
3616        .unwrap_err()
3617        .to_string();
3618        assert!(bad.contains("route `local`"), "{bad}");
3619        assert!(bad.contains("max_parallel"), "{bad}");
3620    }
3621
3622    #[test]
3623    fn flares_default_to_three_on_one_local_slot() {
3624        let cfg = Config::from_toml_str("").unwrap();
3625        assert_eq!(cfg.flares.count, 3, "the local default");
3626        assert_eq!(cfg.flares.concurrency(), 4);
3627        assert_eq!(cfg.flares.per_flare(), 6);
3628        assert_eq!(cfg.flares.budget(), 24);
3629
3630        let cfg = Config::from_toml_str(
3631            r#"
3632[flares]
3633count = 5
3634max_concurrent = 0
3635max_iterations = 0
3636total_iterations = 2
3637"#,
3638        )
3639        .unwrap();
3640        assert_eq!(cfg.flares.count, 5);
3641        // Zero is never a usable cap: the same rule as `[tools] concurrency`, and a run allowed
3642        // fewer turns than one flare would fail before it began.
3643        assert_eq!(cfg.flares.concurrency(), 1);
3644        assert_eq!(cfg.flares.per_flare(), 1);
3645        assert_eq!(cfg.flares.budget(), 2);
3646    }
3647
3648    use super::*;
3649    use std::collections::HashMap;
3650
3651    /// The shipped config, generated — the fixture every test about the file itself starts from.
3652    fn starter() -> String {
3653        starter_config().expect("the starter config generates")
3654    }
3655
3656    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
3657        let m: HashMap<String, String> = pairs
3658            .iter()
3659            .map(|(k, v)| (k.to_string(), v.to_string()))
3660            .collect();
3661        move |k| m.get(k).cloned()
3662    }
3663
3664    /// Load `text` as a config file exactly as the binary would, and say what happened.
3665    fn load_hooks(text: &str) -> std::result::Result<Config, String> {
3666        let tmp = tempfile::tempdir().unwrap();
3667        let path = tmp.path().join("config.toml");
3668        std::fs::write(&path, text).unwrap();
3669        let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
3670        Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
3671    }
3672
3673    #[test]
3674    fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
3675        let want = crate::hooks::DEFAULT_ORDER;
3676        let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
3677        assert_eq!(c.hooks.order, want);
3678        assert_eq!(Config::default().hooks.order, want);
3679        let c = load_hooks("").unwrap();
3680        assert_eq!(c.hooks.order, want);
3681        assert!(
3682            !want.contains(&"recall-sessions"),
3683            "a new session is a new session: recall is opt-in, and `session_search` is how the \
3684             agent reaches the archive"
3685        );
3686    }
3687
3688    #[test]
3689    fn an_empty_order_turns_every_hook_off() {
3690        let c = load_hooks("[hooks]\norder = []\n").unwrap();
3691        assert!(c.hooks.order.is_empty());
3692    }
3693
3694    #[test]
3695    fn a_settings_table_alone_keeps_the_default_order() {
3696        let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
3697        assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
3698    }
3699
3700    #[test]
3701    fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
3702        let err =
3703            load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
3704        assert!(err.contains("`redact-secret`"), "{err}");
3705        assert!(
3706            err.contains("Hooks that exist: recall-sessions, redact-secrets"),
3707            "{err}"
3708        );
3709        assert!(err.contains("config.toml"), "the file is named: {err}");
3710    }
3711
3712    #[test]
3713    fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
3714        let err =
3715            load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
3716        assert!(err.contains("[hooks.redact-secrets]"), "{err}");
3717        assert!(err.contains("never run"), "{err}");
3718        assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
3719    }
3720
3721    #[test]
3722    fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
3723        let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
3724        assert!(err.contains("[hooks.nope]"), "{err}");
3725        assert!(err.contains("Hooks that exist"), "{err}");
3726    }
3727
3728    #[test]
3729    fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
3730        let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
3731        assert!(err.contains("unknown key `alow`"), "{err}");
3732        assert!(err.contains("accepts: allow"), "{err}");
3733    }
3734
3735    #[test]
3736    fn a_stray_key_directly_under_hooks_is_refused() {
3737        let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
3738        assert!(err.contains("`enabled`"), "{err}");
3739        assert!(err.contains("`order`"), "{err}");
3740    }
3741
3742    #[test]
3743    fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
3744        let err =
3745            load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
3746        assert!(err.contains("twice"), "{err}");
3747        let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
3748        assert!(err.contains("must be a list of strings"), "{err}");
3749        let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
3750        assert!(err.contains("empty string"), "{err}");
3751        let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
3752        assert!(err.contains("only strings"), "{err}");
3753    }
3754
3755    #[test]
3756    fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
3757        let tmp = tempfile::tempdir().unwrap();
3758        let home = tmp.path().join("home");
3759        let dir = home.join(".eclipse");
3760        std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
3761        std::fs::write(
3762            dir.join("config.toml"),
3763            "[hooks]\norder = [\"redact-secrets\"]\n",
3764        )
3765        .unwrap();
3766        std::fs::write(
3767            dir.join("profiles/work/config.toml"),
3768            "[hooks]\norder = [\"typo\"]\n",
3769        )
3770        .unwrap();
3771        let env = env_of(&[("HOME", home.to_str().unwrap())]);
3772        let err = Config::load_with_profile(None, Some("work"), &env)
3773            .unwrap_err()
3774            .to_string();
3775        assert!(err.contains("profiles/work/config.toml"), "{err}");
3776        assert!(err.contains("`typo`"), "{err}");
3777    }
3778
3779    /// An empty value is "not in use", and it has to be true in one place: a shipped `.env` names
3780    /// every variable and sets none of them, so `NAME=` has to read as absent — in the loader that
3781    /// resolves `${VAR}`, in the token the dashboard needs, and not one call site at a time.
3782    #[test]
3783    fn an_empty_value_is_not_a_value_in_the_dotenv() {
3784        let dir = tempfile::tempdir().unwrap();
3785        let home = dir.path();
3786        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
3787        let path = home.join(".eclipse/.env");
3788        std::fs::write(
3789            &path,
3790            "ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
3791        )
3792        .unwrap();
3793        let home_s = home.to_str().unwrap().to_string();
3794        let env = env_of(&[("HOME", &home_s)]);
3795        let loaded = Dotenv::load(&env, None).unwrap();
3796        assert_eq!(
3797            loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
3798            Some("m")
3799        );
3800        assert!(
3801            !loaded.values.contains_key("ECLIPSE_API_KEY"),
3802            "an empty assignment is absent: {:?}",
3803            loaded.values.keys().collect::<Vec<_>>()
3804        );
3805        assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
3806    }
3807
3808    /// A later line still wins even when it empties a key: "this host does not use it" is a thing
3809    /// a profile's `.env` has to be able to say about the shared one.
3810    #[test]
3811    fn a_later_empty_assignment_unsets_an_earlier_one() {
3812        let dir = tempfile::tempdir().unwrap();
3813        let home = dir.path();
3814        std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
3815        std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
3816        std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
3817        let home_s = home.to_str().unwrap().to_string();
3818        let env = env_of(&[("HOME", &home_s)]);
3819        let loaded = Dotenv::load(&env, Some("work")).unwrap();
3820        assert_eq!(loaded.files.len(), 2);
3821        assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
3822    }
3823
3824    /// The shipped `.env` is a directory of what can be set: every variable the build reads from
3825    /// it, nothing set, and the token the dashboard cannot invent for you.
3826    #[test]
3827    fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
3828        let text = starter_env("tok");
3829        for name in ENV_TEMPLATE {
3830            assert!(
3831                text.contains(&format!("\n{name}=")),
3832                "`{name}` is in the shipped .env"
3833            );
3834        }
3835        for line in text.lines().filter(|l| !l.starts_with('#')) {
3836            let (name, value) = line.split_once('=').expect("KEY=VALUE");
3837            if name == "ECLIPSE_WEB_AUTH_TOKEN" {
3838                assert_eq!(value, "tok", "the one value a first install cannot invent");
3839            } else {
3840                assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
3841            }
3842        }
3843    }
3844
3845    /// The classification is exhaustive against the source, not against a list beside it: a new
3846    /// `ECLIPSE_*` variable has to be decided on — shipped, shell-only, or internal — before it
3847    /// compiles past this test. Without it the shipped `.env` silently stops being complete.
3848    #[test]
3849    fn every_environment_variable_the_build_reads_is_classified() {
3850        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
3851        let mut seen = Vec::new();
3852        let mut dirs = vec![
3853            root.join("eclipse-core/src"),
3854            root.join("eclipse-cli/src"),
3855            root.join("eclipse-web/src"),
3856        ];
3857        while let Some(dir) = dirs.pop() {
3858            let Ok(entries) = std::fs::read_dir(&dir) else {
3859                continue;
3860            };
3861            for entry in entries.flatten() {
3862                let path = entry.path();
3863                if path.is_dir() {
3864                    dirs.push(path);
3865                    continue;
3866                }
3867                if path.extension().and_then(|e| e.to_str()) != Some("rs") {
3868                    continue;
3869                }
3870                let text = std::fs::read_to_string(&path).unwrap_or_default();
3871                for name in env_names(&text) {
3872                    if !seen.contains(&name) {
3873                        seen.push(name);
3874                    }
3875                }
3876            }
3877        }
3878        assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
3879        for name in &seen {
3880            let known = ENV_TEMPLATE.contains(&name.as_str())
3881                || ENV_SHELL_ONLY.contains(&name.as_str())
3882                || ENV_INTERNAL.contains(&name.as_str());
3883            assert!(
3884                known,
3885                "`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
3886            );
3887        }
3888        // And the other direction: a name in the template has to be one something acts on — read
3889        // by the build, or interpolated by the config the build ships. A variable nobody consumes
3890        // is a line in a secrets file that does nothing, which reads as a setting that is broken.
3891        let shipped = starter();
3892        for name in ENV_TEMPLATE {
3893            let read = seen.iter().any(|s| s == name);
3894            let interpolated = shipped.contains(&format!("${{{name}"));
3895            assert!(
3896                read || interpolated,
3897                "`{name}` is in the shipped .env and nothing reads or interpolates it"
3898            );
3899        }
3900    }
3901
3902    /// The manual's environment table and the `.env` template describe the same set: a name in
3903    /// one and not the other is either a variable nobody can look up or a paragraph about a
3904    /// variable that does not exist.
3905    #[test]
3906    fn every_classified_variable_has_a_description() {
3907        let classified: Vec<&str> = ENV_TEMPLATE
3908            .iter()
3909            .chain(ENV_SHELL_ONLY)
3910            .chain(ENV_INTERNAL)
3911            .copied()
3912            .collect();
3913        for name in &classified {
3914            assert!(
3915                !env_about(name).is_empty(),
3916                "`{name}` is classified and has no line in ENV_ABOUT"
3917            );
3918        }
3919        for (name, about) in ENV_ABOUT {
3920            assert!(
3921                classified.contains(name),
3922                "ENV_ABOUT explains `{name}`, which the build does not read"
3923            );
3924            assert!(
3925                about.len() > 30 && !about.ends_with('.'),
3926                "one sentence, no full stop: {about}"
3927            );
3928        }
3929    }
3930
3931    /// Every `"ECLIPSE_…"` literal in a source file, quoted form only (a doc comment naming one is
3932    /// prose, not a read).
3933    fn env_names(text: &str) -> Vec<String> {
3934        let mut out = Vec::new();
3935        let mut rest = text;
3936        while let Some(at) = rest.find("\"ECLIPSE_") {
3937            let after = &rest[at + 1..];
3938            let Some(end) = after.find('"') else {
3939                break;
3940            };
3941            let name = &after[..end];
3942            // A name, not a prefix: `"ECLIPSE_"` used to build one at run time ends in an
3943            // underscore, and this scanner's own search literal is in the tree it scans.
3944            let complete = name
3945                .chars()
3946                .last()
3947                .is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
3948            if complete
3949                && name
3950                    .chars()
3951                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
3952            {
3953                out.push(name.to_string());
3954            }
3955            rest = &after[end + 1..];
3956        }
3957        out
3958    }
3959
3960    #[test]
3961    fn an_empty_optional_string_loads_as_unset() {
3962        // The shipped spelling of a secret is `${VAR:-}`, which resolves to "" when the variable
3963        // is absent — and "" has to mean "no secret", not "an empty one".
3964        let c = Config::from_toml_str(
3965            "[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
3966        )
3967        .unwrap();
3968        assert_eq!(c.provider.api_key, None);
3969        assert_eq!(c.provider.api_key_env, None);
3970        assert_eq!(c.web.auth_token, None);
3971        // A path is not an option and "" is already its absent state.
3972        assert_eq!(c.provider.model, "m");
3973        // The shipped spelling is `${VAR:-}`, and that resolves through the *loader* — an absent
3974        // variable is no key, not the string with the braces left in it.
3975        let dir = tempfile::tempdir().unwrap();
3976        let path = dir.path().join("config.toml");
3977        std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
3978        let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
3979        assert_eq!(
3980            from_var.provider.api_key, None,
3981            "an absent variable is no key"
3982        );
3983    }
3984
3985    /// The file ships every setting and no prose, and it is the schema's own file: the assertion
3986    /// is against the catalogue, not against a list written here, so a field added to a struct
3987    /// cannot reach this build without reaching the next install's config.
3988    #[test]
3989    fn the_starter_config_carries_every_setting_the_build_reads() {
3990        let text = starter();
3991        let c = parse_text(&text).unwrap();
3992        let settings = Config::default().settings();
3993        assert!(
3994            settings.len() > 80,
3995            "the catalogue is the yardstick: {settings:?}"
3996        );
3997        for setting in &settings {
3998            let key = setting.key.clone();
3999            let present = text.lines().any(|l| {
4000                l.trim_start_matches("# ")
4001                    .trim_start()
4002                    .starts_with(&format!("{key} ="))
4003            });
4004            assert!(
4005                present,
4006                "[{}] `{key}` is missing from the shipped file:\n{text}",
4007                setting.section
4008            );
4009        }
4010        // No prose: the header is three lines, and every other comment is a `key =` that is not
4011        // in use. A paragraph in this file is the thing the manual exists to replace.
4012        for line in text.lines().filter(|l| l.starts_with('#')) {
4013            assert!(
4014                line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
4015                "a comment in the settings file should be a key, not a sentence: {line}"
4016            );
4017        }
4018        let prose = text
4019            .lines()
4020            .filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
4021            .count();
4022        assert!(prose <= 3, "only the three header lines: {prose}");
4023        // It loads, and the hooks block it writes is the order this build actually defaults to.
4024        assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
4025        assert_eq!(c.hooks.order, Config::default().hooks.order);
4026        assert!(c.hooks.settings.contains_key("redact-secrets"));
4027        crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
4028        assert!(
4029            !c.hooks.settings.contains_key("recall-sessions"),
4030            "a settings table for a hook that is not in `order` cannot run"
4031        );
4032        // And every key in it is one the build reads: a config that answers "nothing reads this"
4033        // about its own file is a config that teaches people to ignore the checker.
4034        let value: toml::Value = toml::from_str(&text).unwrap();
4035        let unknown = c.unknown_keys(&value);
4036        assert!(
4037            unknown.is_empty(),
4038            "unknown keys in the shipped file: {unknown:?}"
4039        );
4040        assert_eq!(
4041            c.config_version, CONFIG_VERSION,
4042            "the file stamps its shape"
4043        );
4044    }
4045
4046    #[test]
4047    fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
4048        let c = load_hooks(
4049            "[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
4050        )
4051        .unwrap();
4052        let shown = c.to_toml_redacted().unwrap();
4053        let again = Config::from_toml_str(&shown).unwrap();
4054        assert_eq!(again.hooks, c.hooks);
4055    }
4056
4057    #[test]
4058    fn defaults_have_no_endpoint_or_key() {
4059        let c = Config::default();
4060        assert!(c.provider.base_url.is_empty());
4061        assert!(c.provider.api_key.is_none());
4062        assert!(c.require_provider().is_err());
4063        // The file tools confine every path themselves, so the default is not to ask; the shell
4064        // asks, but only about commands that cannot be undone.
4065        assert_eq!(c.tools.write_file, Policy::Allow);
4066        assert_eq!(c.tools.shell, Policy::Ask);
4067        assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
4068    }
4069
4070    #[test]
4071    fn cli_section_defaults_and_parses() {
4072        // Absent: the documented defaults, and `None` meaning "decide from the stream".
4073        let d = Config::from_toml_str("").unwrap().cli;
4074        assert_eq!(d.color, None);
4075        assert_eq!(d.markdown, None);
4076        assert_eq!(d.approval, Approval::Ask);
4077        assert_eq!(d.history_size, 1000);
4078
4079        let c = Config::from_toml_str(
4080            "[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
4081        )
4082        .unwrap()
4083        .cli;
4084        assert_eq!(c.color, Some(false));
4085        assert_eq!(c.markdown, Some(true));
4086        assert_eq!(c.approval, Approval::Auto);
4087        assert_eq!(c.history_size, 50);
4088    }
4089
4090    #[test]
4091    fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
4092        // Guessing here would mean either prompting someone who asked not to be prompted, or
4093        // not prompting someone who asked to be. Refuse instead.
4094        let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
4095        assert!(err.contains("approval"), "{err}");
4096    }
4097
4098    #[test]
4099    fn web_section_parses_its_ttl_and_default_profile() {
4100        let d = Config::from_toml_str("").unwrap().web;
4101        assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
4102        assert_eq!(d.default_profile, None);
4103
4104        let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
4105            .unwrap()
4106            .web;
4107        assert_eq!(w.session_ttl_hours, 1);
4108        assert_eq!(w.default_profile.as_deref(), Some("work"));
4109    }
4110
4111    /// A `config.toml` on its own has to load: copying the starter file to another host, or
4112    /// losing `.env`, must not take every command down behind a dashboard credential. The token
4113    /// loads empty and only the dashboard refuses it.
4114    #[test]
4115    fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
4116        let dir = tempfile::tempdir().unwrap();
4117        let path = dir.path().join("config.toml");
4118        std::fs::write(&path, starter()).unwrap();
4119        // `|_| None` is the whole environment: nothing set, and no config dir to find a `.env`
4120        // in, which is exactly what a copied file sees on a new machine.
4121        let c = Config::load_with(Some(&path), &|_| None)
4122            .expect("the starter config loads with no .env at all");
4123        assert_eq!(
4124            c.web.auth_token, None,
4125            "an unset token loads as no token, not as a load error and not as an empty secret"
4126        );
4127        assert_eq!(c.provider.model, Config::default().provider.model);
4128    }
4129
4130    #[test]
4131    fn starter_config_parses_and_matches_defaults() {
4132        let c = Config::from_toml_str(&starter()).unwrap();
4133        let d = Config::default();
4134        assert_eq!(c.tools.read_file, d.tools.read_file);
4135        assert_eq!(c.tools.fetch, d.tools.fetch);
4136        assert_eq!(c.web.port, d.web.port);
4137        assert!(c.provider.base_url.is_empty());
4138    }
4139
4140    #[test]
4141    fn partial_file_fills_defaults() {
4142        let c = Config::from_toml_str(
4143            "[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
4144        )
4145        .unwrap();
4146        assert_eq!(c.provider.base_url, "http://x/v1");
4147        assert_eq!(c.tools.shell, Policy::Deny);
4148        assert_eq!(c.tools.write_file, Policy::Allow);
4149        assert_eq!(
4150            c.agent.max_iterations,
4151            usize::MAX,
4152            "no cap unless the box asks for one"
4153        );
4154        assert!(c.require_provider().is_ok());
4155
4156        for word in ["unlimited", "none", "inf", "0", "-1"] {
4157            let raw = format!("[agent]\nmax_iterations = {word}\n");
4158            let raw = if word.parse::<i64>().is_ok() {
4159                raw
4160            } else {
4161                format!("[agent]\nmax_iterations = \"{word}\"\n")
4162            };
4163            let c = Config::from_toml_str(&raw).unwrap();
4164            assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
4165        }
4166
4167        let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
4168        assert_eq!(c.agent.max_iterations, 12, "a number is a cap");
4169
4170        let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
4171        let printed = toml::to_string(&words).unwrap();
4172        assert!(
4173            printed.contains("max_iterations = \"unlimited\""),
4174            "the schema says the word, not a length: {printed}"
4175        );
4176
4177        let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
4178        assert!(
4179            refused.is_err(),
4180            "a word that is not one of ours is an error"
4181        );
4182    }
4183
4184    #[test]
4185    fn unknown_policy_is_rejected() {
4186        assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
4187    }
4188
4189    #[test]
4190    fn env_overrides_file() {
4191        let dir = tempfile::tempdir().unwrap();
4192        let p = dir.path().join("c.toml");
4193        std::fs::write(
4194            &p,
4195            "[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
4196        )
4197        .unwrap();
4198        let env = env_of(&[
4199            ("ECLIPSE_BASE_URL", "http://env/v1"),
4200            ("ECLIPSE_API_KEY", "env-key"),
4201        ]);
4202        let c = Config::load_with(Some(&p), &env).unwrap();
4203        assert_eq!(c.provider.base_url, "http://env/v1");
4204        assert_eq!(c.provider.model, "file-model");
4205        assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
4206    }
4207
4208    #[test]
4209    fn api_key_env_indirection() {
4210        let env = env_of(&[("MY_KEY", "secret")]);
4211        let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
4212        c.apply_env(&env);
4213        assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
4214    }
4215
4216    #[test]
4217    fn debug_redacts_api_key() {
4218        let mut c = Config::default();
4219        c.provider.api_key = Some("hunter2".into());
4220        assert!(!format!("{c:?}").contains("hunter2"));
4221    }
4222
4223    #[test]
4224    fn debug_and_redacted_toml_hide_web_token() {
4225        let mut c = Config::default();
4226        c.web.auth_token = Some("s3cret-token-value".into());
4227        assert!(!format!("{c:?}").contains("s3cret"));
4228        assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
4229    }
4230
4231    /// `Config` derives `Debug` and holds the loaded `.env`; the values in it are the whole point of
4232    /// the file. `config show` was safe, `{cfg:?}` was not — and a panic message or a failing
4233    /// `assert_eq!` is exactly where it would have gone out.
4234    #[test]
4235    fn debug_never_prints_a_dotenv_value() {
4236        let dir = tempfile::tempdir().unwrap();
4237        let root = dir.path().join("root");
4238        std::fs::create_dir_all(&root).unwrap();
4239        std::fs::write(
4240            root.join(".env"),
4241            "ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
4242        )
4243        .unwrap();
4244        let cfg_path = root.join("config.toml");
4245        std::fs::write(
4246            &cfg_path,
4247            "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
4248        )
4249        .unwrap();
4250        let env = env_of(&[
4251            ("ECLIPSE_HOME", root.to_str().unwrap()),
4252            ("HOME", dir.path().to_str().unwrap()),
4253        ]);
4254
4255        let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4256        let debug = format!("{cfg:?}");
4257        assert!(
4258            !debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
4259            "the .env values must never be printed: {debug}"
4260        );
4261        assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
4262        assert!(debug.contains("Dotenv"), "{debug}");
4263        // And the token reached the provider, so this is a real loaded .env, not an empty one.
4264        assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
4265    }
4266
4267    #[test]
4268    fn redacted_toml_hides_key_and_round_trips() {
4269        let mut c = Config::default();
4270        c.provider.api_key = Some("hunter2".into());
4271        c.provider.model = "m".into();
4272        let t = c.to_toml_redacted().unwrap();
4273        assert!(!t.contains("hunter2"));
4274        assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
4275    }
4276
4277    /// The update track is a word in the file and a branch in the code: `release` and `main` are
4278    /// one ref, which is why the key names a track. A word this build does not know is a parse
4279    /// error, never a silent fall back to the release track.
4280    #[test]
4281    fn the_update_track_names_a_branch_and_takes_two_words() {
4282        assert_eq!(Config::default().update.track, Track::Release);
4283        assert_eq!(Track::Release.branch(), "main");
4284        assert_eq!(Track::Develop.branch(), "develop");
4285        let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
4286        assert_eq!(cfg.update.track, Track::Develop);
4287        assert_eq!(cfg.update.track.label(), "develop");
4288        let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
4289            .unwrap_err()
4290            .to_string();
4291        assert!(
4292            err.contains("main") && err.contains("develop"),
4293            "the refusal lists the words it takes: {err}"
4294        );
4295    }
4296
4297    /// A URL is printed as it is, because that is how you check what you configured — but a URL can
4298    /// carry a secret, and both legitimate spellings were printed verbatim by `config show`.
4299    #[test]
4300    fn a_url_keeps_its_shape_and_loses_its_secrets() {
4301        let mut c = Config::default();
4302        c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
4303        c.update.remote =
4304            Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
4305        c.update.releases = Some("https://mirror.internal/api#frag".into());
4306
4307        let t = c.to_toml_redacted().unwrap();
4308        assert!(
4309            !t.contains("hunter2") && !t.contains("abc123"),
4310            "the secrets are gone: {t}"
4311        );
4312        // The shape survives: scheme, host, path, and the *names* of the parameters.
4313        assert!(
4314            t.contains("https://<redacted>@gw.internal/v1"),
4315            "the userinfo is replaced, not the URL: {t}"
4316        );
4317        assert!(
4318            t.contains("access_token=<redacted>&page=2"),
4319            "the secret parameter keeps its name and loses its value: {t}"
4320        );
4321        assert!(t.contains("https://mirror.internal/api#frag"), "{t}");
4322
4323        // And the same URL is not the one place a secret survives: `{cfg:?}` scrubs it too.
4324        let debug = format!("{c:?}");
4325        assert!(!debug.contains("hunter2"), "{debug}");
4326
4327        // A URL with nothing secret in it is left exactly as written.
4328        let plain = Config::default();
4329        assert!(plain
4330            .to_toml_redacted()
4331            .unwrap()
4332            .contains(&plain.provider.base_url));
4333    }
4334
4335    #[test]
4336    fn one_root_layout() {
4337        // One directory, everything in it. Deliberately not XDG: the reason is in `home_root`.
4338        let env = env_of(&[("HOME", "/home/u")]);
4339        assert_eq!(
4340            config_path(&env).unwrap(),
4341            PathBuf::from("/home/u/.eclipse/config.toml")
4342        );
4343        assert_eq!(
4344            Config::default().sessions_dir(&env).unwrap(),
4345            PathBuf::from("/home/u/.eclipse/state/sessions")
4346        );
4347        assert_eq!(
4348            Config::default().memory_dir(&env).unwrap(),
4349            PathBuf::from("/home/u/.eclipse/memory")
4350        );
4351        // XDG is not consulted, even when it is set: two roots is the thing this layout exists
4352        // to prevent, and honouring XDG "sometimes" would be the worst of both.
4353        let env = env_of(&[
4354            ("HOME", "/home/u"),
4355            ("XDG_CONFIG_HOME", "/x/cfg"),
4356            ("XDG_STATE_HOME", "/x/state"),
4357        ]);
4358        assert_eq!(
4359            config_path(&env).unwrap(),
4360            PathBuf::from("/home/u/.eclipse/config.toml")
4361        );
4362        // ECLIPSE_HOME is the one way to move it.
4363        let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
4364        assert_eq!(
4365            config_path(&env).unwrap(),
4366            PathBuf::from("/opt/ecl/config.toml")
4367        );
4368    }
4369
4370    #[test]
4371    fn missing_default_file_is_ok_but_explicit_missing_is_error() {
4372        let dir = tempfile::tempdir().unwrap();
4373        let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
4374        assert!(Config::load_with(None, &env).is_ok());
4375        assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
4376    }
4377
4378    #[test]
4379    fn auto_prune_is_off_by_default_and_can_be_enabled() {
4380        assert!(!Config::default().sessions.auto_prune);
4381        let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
4382            .unwrap();
4383        assert!(c.sessions.auto_prune);
4384        assert_eq!(c.sessions.retention_keep_count, 5);
4385    }
4386
4387    #[test]
4388    fn sessions_dir_expands_tilde() {
4389        let env = env_of(&[("HOME", "/home/u")]);
4390        let mut c = Config::default();
4391        c.sessions.dir = Some("~/s".into());
4392        assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
4393    }
4394
4395    #[test]
4396    fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
4397        let dir = tempfile::tempdir().unwrap();
4398        let p = dir.path().join("a/b/config.toml");
4399        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4400        let report = write_starter_config(&p, false, &env).unwrap();
4401        assert!(report.dotenv_written);
4402        assert_eq!(
4403            report.dotenv,
4404            dir.path().join(".env"),
4405            "the .env goes where the loader reads it, not beside a config elsewhere"
4406        );
4407
4408        let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
4409        let token = dotenv
4410            .lines()
4411            .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4412            .expect("the token lives in .env");
4413        assert_eq!(token.len(), 64, "a generated token, not a placeholder");
4414        assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
4415        assert!(
4416            !std::fs::read_to_string(&p).unwrap().contains(token),
4417            "the config carries the reference, never the secret"
4418        );
4419
4420        #[cfg(unix)]
4421        {
4422            use std::os::unix::fs::PermissionsExt;
4423            for f in [&p, &report.dotenv] {
4424                assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
4425            }
4426        }
4427
4428        // End to end: the value is resolvable through the chain the loader uses. The config
4429        // has to sit where the loader looks, or its `.env` is a different file's.
4430        let root = dir.path().join("root");
4431        let cfg_dir = root.clone();
4432        std::fs::create_dir_all(&cfg_dir).unwrap();
4433        let real = cfg_dir.join("config.toml");
4434        let env = env_of(&[
4435            ("ECLIPSE_HOME", root.to_str().unwrap()),
4436            ("HOME", dir.path().to_str().unwrap()),
4437        ]);
4438        let written = write_starter_config(&real, false, &env).unwrap();
4439        let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
4440        let token = std::fs::read_to_string(&written.dotenv)
4441            .unwrap()
4442            .lines()
4443            .find_map(|l| {
4444                l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
4445                    .map(str::to_string)
4446            })
4447            .unwrap();
4448        assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
4449        assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
4450    }
4451
4452    /// A `.env` line with no value is a half-typed line, not a setting: every other layer treats
4453    /// empty as absent, and the loader used to hand the raw empty string through — which blanked the
4454    /// key the config file already had and made requests go out unauthenticated.
4455    #[test]
4456    fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
4457        let dir = tempfile::tempdir().unwrap();
4458        let root = dir.path().join("root");
4459        std::fs::create_dir_all(&root).unwrap();
4460        std::fs::write(
4461            root.join(".env"),
4462            "ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
4463        )
4464        .unwrap();
4465        let cfg_path = root.join("config.toml");
4466        std::fs::write(
4467            &cfg_path,
4468            "[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
4469             base_url = \"http://127.0.0.1:9999/v1\"\n",
4470        )
4471        .unwrap();
4472        let env = env_of(&[
4473            ("ECLIPSE_HOME", root.to_str().unwrap()),
4474            ("HOME", dir.path().to_str().unwrap()),
4475        ]);
4476
4477        let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4478        assert_eq!(
4479            cfg.provider.api_key.as_deref(),
4480            Some("sk-from-the-file"),
4481            "an empty .env value must not blank the key"
4482        );
4483        assert_eq!(cfg.provider.model, "keep-me", "nor the model");
4484        assert_eq!(
4485            cfg.provider.base_url, "http://127.0.0.1:9999/v1",
4486            "nor the base URL"
4487        );
4488    }
4489
4490    #[test]
4491    fn context_files_are_seeded_and_existing_ones_are_kept() {
4492        let tmp = tempfile::tempdir().unwrap();
4493        let memory = tmp.path().join("memory");
4494        let created = seed_context_files(&memory).unwrap();
4495        assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
4496        assert!(memory.join("AGENT.md").exists());
4497        assert!(memory.join("USER.md").exists());
4498        assert!(memory.join("MEMORY.md").exists());
4499        assert_eq!(
4500            std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
4501            ""
4502        );
4503
4504        // Re-run: nothing is overwritten.
4505        let created = seed_context_files(&memory).unwrap();
4506        assert!(
4507            created.is_empty(),
4508            "existing files are left alone: {created:?}"
4509        );
4510
4511        // All three hold an operator's text, not just the one this test used to check: a rewrite
4512        // of a starter is the failure mode (#295), so the assertion has to be byte for byte on
4513        // every file that can carry a person's words.
4514        let written = [
4515            ("AGENT.md", "run make, no cargo test\n"),
4516            ("USER.md", "I am the operator; keep it short\n"),
4517            ("MEMORY.md", "- one durable fact\n"),
4518        ];
4519        for (name, body) in written {
4520            std::fs::write(memory.join(name), body).unwrap();
4521        }
4522        let created = seed_context_files(&memory).unwrap();
4523        assert!(created.is_empty(), "{created:?}");
4524        for (name, body) in written {
4525            assert_eq!(
4526                std::fs::read_to_string(memory.join(name)).unwrap(),
4527                body,
4528                "{name} was rewritten"
4529            );
4530        }
4531    }
4532
4533    /// "Once" is a fact about a directory, not about a process or an install: a profile whose
4534    /// `memory/` has the files is left alone exactly as the base install is, and a profile that
4535    /// has never been used is a first install and gets the starters. Seeding one must not touch
4536    /// the other, which is what makes it safe for `setup` to run against any profile (#295).
4537    #[test]
4538    fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
4539        let tmp = tempfile::tempdir().unwrap();
4540        let base = tmp.path().join("memory");
4541        let lived_in = tmp.path().join("profiles/work/memory");
4542        let fresh = tmp.path().join("profiles/lab/memory");
4543
4544        assert_eq!(seed_context_files(&base).unwrap().len(), 3);
4545        std::fs::write(base.join("USER.md"), "the operator\n").unwrap();
4546
4547        std::fs::create_dir_all(&lived_in).unwrap();
4548        for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4549            std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
4550        }
4551
4552        assert!(
4553            seed_context_files(&lived_in).unwrap().is_empty(),
4554            "an existing profile's files are not rewritten"
4555        );
4556        assert_eq!(
4557            seed_context_files(&fresh).unwrap().len(),
4558            3,
4559            "a profile that has never been used is a first install"
4560        );
4561
4562        assert_eq!(
4563            std::fs::read_to_string(base.join("USER.md")).unwrap(),
4564            "the operator\n"
4565        );
4566        for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4567            assert_eq!(
4568                std::fs::read_to_string(lived_in.join(name)).unwrap(),
4569                format!("{name} as it was lived in\n")
4570            );
4571        }
4572    }
4573
4574    /// `--config /other/config.toml`: the config is there, the secrets are in the config
4575    /// directory. Writing the `.env` beside the config put it where no start would ever read it —
4576    /// `config init` reported a dashboard token that the next launch did not have.
4577    #[test]
4578    fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
4579        let dir = tempfile::tempdir().unwrap();
4580        let home = dir.path().join("home");
4581        std::fs::create_dir_all(&home).unwrap();
4582        let elsewhere = dir.path().join("other");
4583        let path = elsewhere.join("config.toml");
4584        let env = env_of(&[
4585            ("ECLIPSE_HOME", home.to_str().unwrap()),
4586            ("HOME", dir.path().to_str().unwrap()),
4587        ]);
4588
4589        let report = write_starter_config(&path, false, &env).unwrap();
4590        let token = std::fs::read_to_string(&report.dotenv)
4591            .unwrap()
4592            .lines()
4593            .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4594            .expect("the token lives in .env")
4595            .to_string();
4596        assert_eq!(report.dotenv, home.join(".env"));
4597
4598        let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
4599        assert_eq!(
4600            cfg.web.auth_token.as_deref(),
4601            Some(token.as_str()),
4602            "the token `config init` reported is the token the next start reads"
4603        );
4604    }
4605
4606    #[test]
4607    fn config_init_refuses_to_overwrite_a_config_without_force() {
4608        let dir = tempfile::tempdir().unwrap();
4609        let p = dir.path().join("c/config.toml");
4610        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4611        write_starter_config(&p, false, &env).unwrap();
4612        assert!(write_starter_config(&p, false, &env).is_err());
4613    }
4614
4615    #[test]
4616    fn config_init_never_overwrites_an_existing_dotenv() {
4617        let dir = tempfile::tempdir().unwrap();
4618        let p = dir.path().join("d/config.toml");
4619        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4620        let first = write_starter_config(&p, false, &env).unwrap();
4621        let before = std::fs::read_to_string(&first.dotenv).unwrap();
4622
4623        // `--force` replaces the config. It is not consent to lose the user's secrets.
4624        let again = write_starter_config(&p, true, &env).unwrap();
4625        assert!(!again.dotenv_written);
4626        assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
4627    }
4628
4629    #[test]
4630    fn a_profile_overlay_merges_over_the_base_config() {
4631        let tmp = tempfile::tempdir().unwrap();
4632        let home = tmp.path().join("home");
4633        let cfg_dir = home.join(".eclipse");
4634        std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
4635        std::fs::write(
4636            cfg_dir.join("config.toml"),
4637            "[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
4638             temperature = 0.2\n[agent]\nmax_iterations = 7\n",
4639        )
4640        .unwrap();
4641        std::fs::write(
4642            cfg_dir.join("profiles/work/config.toml"),
4643            "[provider]\nmodel = \"work-model\"\n",
4644        )
4645        .unwrap();
4646        let env = env_of(&[("HOME", home.to_str().unwrap())]);
4647
4648        let base = Config::load_with(None, &env).unwrap();
4649        assert_eq!(base.provider.model, "base-model");
4650        assert_eq!(base.profile_name(), "default");
4651
4652        let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
4653        // The overlay replaced one key and left its siblings alone.
4654        assert_eq!(work.provider.model, "work-model");
4655        assert_eq!(work.provider.base_url, "http://base/v1");
4656        assert_eq!(work.provider.temperature, Some(0.2));
4657        assert_eq!(work.agent.max_iterations, 7);
4658        assert_eq!(work.profile_name(), "work");
4659        // Same config file, different state.
4660        assert_eq!(
4661            work.sessions_dir(&env).unwrap(),
4662            home.join(".eclipse/profiles/work/state/sessions")
4663        );
4664        assert_eq!(
4665            base.sessions_dir(&env).unwrap(),
4666            home.join(".eclipse/state/sessions")
4667        );
4668        assert_eq!(
4669            work.state_dir(&env).unwrap(),
4670            home.join(".eclipse/profiles/work/state")
4671        );
4672    }
4673
4674    #[test]
4675    fn the_profile_comes_from_the_environment_and_the_argument_wins() {
4676        let tmp = tempfile::tempdir().unwrap();
4677        let home = tmp.path().join("home");
4678        std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
4679        std::fs::write(
4680            home.join(".eclipse/profiles/env/config.toml"),
4681            "[agent]\nmax_iterations = 3\n",
4682        )
4683        .unwrap();
4684        let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
4685        let from_env = Config::load_with(None, &env).unwrap();
4686        assert_eq!(from_env.profile_name(), "env");
4687        assert_eq!(from_env.agent.max_iterations, 3);
4688
4689        let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
4690        assert_eq!(explicit.profile_name(), "other");
4691        // No overlay for "other": the base defaults apply, which is no cap at all.
4692        assert_eq!(explicit.agent.max_iterations, usize::MAX);
4693    }
4694
4695    #[test]
4696    fn the_default_profile_keeps_the_plain_state_directory() {
4697        let env = env_of(&[("HOME", "/home/u")]);
4698        assert_eq!(
4699            state_dir_for(&env, Some("default")).unwrap(),
4700            PathBuf::from("/home/u/.eclipse/state")
4701        );
4702        assert_eq!(
4703            state_dir_for(&env, None).unwrap(),
4704            PathBuf::from("/home/u/.eclipse/state")
4705        );
4706        assert_eq!(
4707            state_dir_for(&env, Some("work")).unwrap(),
4708            PathBuf::from("/home/u/.eclipse/profiles/work/state")
4709        );
4710    }
4711
4712    #[test]
4713    fn a_profile_name_must_be_a_safe_directory_name() {
4714        for bad in ["", "../etc", "a/b", "sp ace"] {
4715            assert!(
4716                validate_profile_name(bad).is_err(),
4717                "{bad:?} should be rejected"
4718            );
4719        }
4720        assert!(validate_profile_name("work-2026_x").is_ok());
4721        let env = env_of(&[("HOME", "/home/u")]);
4722        assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
4723    }
4724
4725    #[test]
4726    fn plugin_directories_put_the_profile_first() {
4727        let tmp = tempfile::tempdir().unwrap();
4728        let home = tmp.path().join("home");
4729        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
4730        let env = env_of(&[("HOME", home.to_str().unwrap())]);
4731        let mut cfg = Config::default();
4732        let default_dirs = cfg.plugins_dirs(&env);
4733        assert_eq!(
4734            default_dirs,
4735            vec![home.join(".eclipse/plugins")],
4736            "the default profile has no profile plugin dir"
4737        );
4738
4739        cfg.profile = Some("work".into());
4740        let dirs = cfg.plugins_dirs(&env);
4741        assert_eq!(dirs.len(), 2);
4742        assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
4743        assert_eq!(dirs[1], home.join(".eclipse/plugins"));
4744
4745        cfg.plugins.dir = Some("~/elsewhere/plugins".into());
4746        assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
4747    }
4748
4749    #[test]
4750    fn plugins_are_off_until_named() {
4751        let cfg = Config::default();
4752        assert!(cfg.plugins.enabled.is_empty());
4753        assert!(cfg.plugins.dir.is_none());
4754        let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
4755        assert_eq!(parsed.plugins.enabled, ["a", "b"]);
4756    }
4757
4758    // ---- editing a config file in place (what `eclipse setup` does) ----------------------
4759
4760    #[test]
4761    fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
4762        let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
4763        let text = toml_set_string(&text, "provider", "model", "some-model");
4764        assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
4765        assert!(text.contains("model = \"some-model\""), "{text}");
4766        // The shipped file is what a person reads and edits: nothing else may move.
4767        assert!(text.contains("# Every setting this build reads"));
4768        assert!(text.contains("[agent]"));
4769        assert!(
4770            !text.contains("base_url = \"\""),
4771            "the empty blank must be gone: {text}"
4772        );
4773        // And it is still a config the real loader accepts.
4774        let cfg: Config = toml::from_str(&text).expect("edited config must parse");
4775        assert_eq!(cfg.provider.base_url, "http://h:1/v1");
4776        assert_eq!(cfg.provider.model, "some-model");
4777    }
4778
4779    #[test]
4780    fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
4781        let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
4782        assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
4783        assert_eq!(
4784            text.matches("\nprofile = ").count(),
4785            1,
4786            "no duplicate key (the commented [web] default_profile is a different key): {text}"
4787        );
4788        let cfg: Config = toml::from_str(&text).unwrap();
4789        assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
4790    }
4791
4792    #[test]
4793    fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
4794        // `[sessions] dir` and `[plugins] dir` both exist; only the one asked for may change.
4795        let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
4796        let cfg: Config = toml::from_str(&text).unwrap();
4797        assert_eq!(
4798            cfg.sessions.dir.as_deref(),
4799            Some(std::path::Path::new("/tmp/sessions-here"))
4800        );
4801        assert_eq!(cfg.plugins.dir, None, "{text}");
4802    }
4803
4804    #[test]
4805    fn setting_a_key_in_a_missing_section_adds_the_section() {
4806        let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
4807        let cfg: Config = toml::from_str(&text).unwrap();
4808        assert_eq!(cfg.web.host, "0.0.0.0");
4809        assert_eq!(cfg.agent.max_iterations, 5);
4810    }
4811
4812    #[test]
4813    fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
4814        let text = starter();
4815        assert_eq!(
4816            toml_value(&text, "provider", "base_url"),
4817            Some(String::new())
4818        );
4819        // An absent-by-default key is present in the file *as a comment*, and reads as unset:
4820        // nothing is imposed by shipping the key, which is the whole point of the two kinds of
4821        // line. `config set` is what turns one into a value.
4822        assert_eq!(toml_value(&text, "provider", "temperature"), None);
4823        assert!(text.contains("# temperature ="), "{text}");
4824        assert_eq!(
4825            toml_value(&text, "agent", "max_iterations"),
4826            Some("unlimited".to_string()),
4827            "the cap is written, and its off value is the word `unlimited`"
4828        );
4829    }
4830
4831    #[test]
4832    fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
4833        let dir = tempfile::tempdir().unwrap();
4834        let cfg_path = dir.path().join("config.toml");
4835        let dotenv = dir.path().join(".env");
4836        save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
4837        save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
4838        save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
4839        save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
4840        let body = std::fs::read_to_string(&dotenv).unwrap();
4841        assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
4842        assert_eq!(
4843            dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
4844            Some("sk-2")
4845        );
4846        assert_eq!(
4847            dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
4848            Some("tok"),
4849            "an unrelated secret must survive"
4850        );
4851        #[cfg(unix)]
4852        {
4853            use std::os::unix::fs::PermissionsExt;
4854            for f in [&cfg_path, &dotenv] {
4855                let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
4856                assert_eq!(mode, 0o600, "{}", f.display());
4857            }
4858        }
4859    }
4860
4861    #[test]
4862    fn trace_content_is_off_by_default_and_can_be_set() {
4863        assert!(!Config::default().agent.trace_content);
4864        let cfg = Config::from_toml_str(
4865            "[agent]
4866trace_content = true
4867",
4868        )
4869        .unwrap();
4870        assert!(cfg.agent.trace_content);
4871    }
4872
4873    #[test]
4874    fn an_output_schema_is_absent_until_somebody_asks_for_one() {
4875        // A default schema would make every reply in a conversation have to be JSON, so there is
4876        // no default at all: it is opt-in, per install or per run.
4877        assert_eq!(Config::default().agent.output_schema, None);
4878        let cfg = Config::from_toml_str(
4879            "[agent]
4880output_schema = \"schemas/plan.json\"
4881",
4882        )
4883        .unwrap();
4884        assert_eq!(
4885            cfg.agent.output_schema.as_deref(),
4886            Some("schemas/plan.json")
4887        );
4888    }
4889
4890    #[test]
4891    fn the_user_section_has_the_defaults_the_docs_promise() {
4892        let cfg = Config::default();
4893        assert_eq!(cfg.user.file, "USER.md");
4894        assert_eq!(cfg.user.memory_file, "MEMORY.md");
4895        assert_eq!(cfg.user.memory_budget_chars, 3000);
4896        assert_eq!(
4897            cfg.agent.context_file_max_chars,
4898            crate::context_files::DEFAULT_MAX_FILE_CHARS
4899        );
4900        assert_eq!(
4901            cfg.agent.context_files_budget_chars,
4902            crate::context_files::DEFAULT_BUDGET_CHARS
4903        );
4904    }
4905
4906    #[test]
4907    fn the_context_and_memory_budgets_can_be_set_in_the_file() {
4908        let cfg = Config::from_toml_str(
4909            "[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
4910             [user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
4911        )
4912        .unwrap();
4913        assert_eq!(cfg.agent.context_file_max_chars, 100);
4914        assert_eq!(cfg.agent.context_files_budget_chars, 200);
4915        assert_eq!(cfg.user.file, "WHO.md");
4916        assert_eq!(cfg.user.memory_file, "FACTS.md");
4917        assert_eq!(cfg.user.memory_budget_chars, 50);
4918    }
4919
4920    #[test]
4921    fn the_default_profile_keeps_its_files_in_the_config_directory() {
4922        let env = |k: &str| match k {
4923            "HOME" => Some("/home/m".to_string()),
4924            _ => None,
4925        };
4926        let mut cfg = Config::default();
4927        assert_eq!(
4928            cfg.context_dir(&env),
4929            Some(PathBuf::from("/home/m/.eclipse"))
4930        );
4931        cfg.profile = Some("work".into());
4932        assert_eq!(
4933            cfg.context_dir(&env),
4934            Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
4935        );
4936    }
4937
4938    #[test]
4939    fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
4940        let env = |k: &str| match k {
4941            "HOME" => Some("/home/m".to_string()),
4942            _ => None,
4943        };
4944        let mut cfg = Config::default();
4945        assert_eq!(
4946            cfg.scripts_dir(&env),
4947            Some(PathBuf::from("/home/m/.eclipse/scripts"))
4948        );
4949        cfg.profile = Some("work".into());
4950        assert_eq!(
4951            cfg.scripts_dir(&env),
4952            Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
4953        );
4954        let no_home = |_: &str| None;
4955        assert_eq!(Config::default().scripts_dir(&no_home), None);
4956    }
4957
4958    #[test]
4959    fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
4960        let env = |k: &str| match k {
4961            "ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
4962            _ => None,
4963        };
4964        let dir = Config::default().scripts_dir(&env).unwrap();
4965        assert!(dir.is_absolute(), "{}", dir.display());
4966        assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
4967    }
4968
4969    #[test]
4970    fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
4971        assert_eq!(Config::default().tools.script, Policy::Ask);
4972        let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
4973        assert_eq!(cfg.tools.script, Policy::Deny);
4974        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
4975        assert_eq!(starter.tools.script, Policy::Ask);
4976        assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
4977    }
4978
4979    #[test]
4980    fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
4981        let cfg = Config::default();
4982        assert_eq!(cfg.vision.mode, VisionMode::Auto);
4983        assert_eq!(cfg.vision.route, "");
4984        assert!(!cfg.vision.allow_cloud);
4985    }
4986
4987    #[test]
4988    fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
4989        for (text, mode) in [
4990            ("native", VisionMode::Native),
4991            ("text", VisionMode::Text),
4992            ("auto", VisionMode::Auto),
4993        ] {
4994            let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
4995            assert_eq!(cfg.vision.mode, mode, "{text}");
4996        }
4997    }
4998
4999    #[test]
5000    fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
5001        let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
5002        let sentence = err.to_string();
5003        assert!(sentence.contains("telepathy"), "{sentence}");
5004        assert!(sentence.contains("native"), "{sentence}");
5005        assert!(sentence.contains("text"), "{sentence}");
5006        assert!(sentence.contains("auto"), "{sentence}");
5007    }
5008
5009    #[test]
5010    fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
5011        let cfg = Config::from_toml_str(
5012            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5013             [vision]\nroute = \"sight\"\n",
5014        )
5015        .unwrap();
5016        let err = cfg.validate_routes().unwrap_err().to_string();
5017        assert!(err.contains("vision.route"), "{err}");
5018        assert!(err.contains("sight"), "{err}");
5019        assert!(err.contains("default"), "{err}");
5020    }
5021
5022    #[test]
5023    fn a_vision_route_that_exists_validates() {
5024        let cfg = Config::from_toml_str(
5025            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5026             [vision]\nroute = \"default\"\n",
5027        )
5028        .unwrap();
5029        cfg.validate_routes().unwrap();
5030        assert_eq!(cfg.vision.route, "default");
5031    }
5032
5033    #[test]
5034    fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
5035        assert_eq!(Config::default().skills.index_budget_chars, 4000);
5036        let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
5037        assert_eq!(cfg.skills.index_budget_chars, 250);
5038        assert!(starter().contains("[skills]"));
5039        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5040        assert_eq!(starter.skills.index_budget_chars, 4000);
5041    }
5042
5043    #[test]
5044    fn the_redacted_config_shows_the_skills_section() {
5045        let mut cfg = Config::default();
5046        cfg.skills.index_budget_chars = 123;
5047        let shown = cfg.to_toml_redacted().unwrap();
5048        assert!(shown.contains("[skills]"), "{shown}");
5049        assert!(shown.contains("index_budget_chars = 123"), "{shown}");
5050    }
5051
5052    #[test]
5053    fn the_starter_writes_the_context_file_settings() {
5054        let text = starter();
5055        let cfg = Config::from_toml_str(&text).unwrap();
5056        assert_eq!(cfg.user.memory_file, "MEMORY.md");
5057        for key in ["context_files_budget_chars", "[user]", "USER.md"] {
5058            assert!(text.contains(key), "the shipped file names `{key}`");
5059        }
5060    }
5061
5062    // ---- routes (M12, slice 1) ----
5063
5064    const TWO_ROUTES: &str = "\
5065[provider]
5066fallback = [\"local\", \"big\"]
5067[[provider.route]]
5068name = \"local\"
5069base_url = \"http://127.0.0.1:8081/v1\"
5070model = \"small\"
5071[[provider.route]]
5072name = \"big\"
5073base_url = \"http://10.0.0.2:8000/v1\"
5074model = \"large\"
5075api_key = \"hunter2\"
5076timeout_secs = 30
5077";
5078
5079    fn parse(text: &str) -> Config {
5080        Config::from_toml_str(text).unwrap()
5081    }
5082
5083    fn refusal(text: &str) -> String {
5084        let c = parse(text);
5085        c.validate_routes()
5086            .and_then(|_| c.chain().map(|_| ()))
5087            .unwrap_err()
5088            .to_string()
5089    }
5090
5091    #[test]
5092    fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
5093        let c = parse(
5094            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
5095             [[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
5096        );
5097        let r = c.declared_routes();
5098        assert_eq!(
5099            r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
5100            ["default", "r"],
5101            "[provider] is the route called default"
5102        );
5103        assert_eq!(r[0].config.timeout_secs, 7);
5104        assert_eq!(
5105            r[1].config.timeout_secs, 120,
5106            "the route got the built-in default, not [provider]'s 7"
5107        );
5108    }
5109
5110    #[test]
5111    fn provider_may_be_omitted_when_fallback_names_a_route() {
5112        let c = parse(TWO_ROUTES);
5113        c.validate_routes().unwrap();
5114        let chain = c.chain().unwrap();
5115        assert_eq!(chain.source, ChainSource::Fallback);
5116        let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5117        assert_eq!(names, ["local", "big"]);
5118        assert_eq!(chain.routes[1].config.timeout_secs, 30);
5119        assert!(
5120            c.declared_routes().iter().all(|r| r.name != "default"),
5121            "no phantom default route appears"
5122        );
5123    }
5124
5125    #[test]
5126    fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
5127        // `fallback` is the whole chain. Writing a base_url into `[provider]` and then a
5128        // fallback that does not list `default` is a config where the endpoint the user typed
5129        // is never called — the sort of thing discovered later from a bill.
5130        let text = r#"
5131[provider]
5132base_url = "https://api.example.com/v1"
5133model = "gpt"
5134fallback = ["local"]
5135
5136[[provider.route]]
5137name = "local"
5138base_url = "http://127.0.0.1:8080/v1"
5139model = "qwen3-coder"
5140"#;
5141        let err = parse(text).validate_routes().unwrap_err().to_string();
5142        assert!(err.contains("would never be called"), "{err}");
5143        assert!(
5144            err.contains("Put `default` first"),
5145            "it says what to type: {err}"
5146        );
5147    }
5148
5149    #[test]
5150    fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
5151        let text = r#"
5152[provider]
5153base_url = "https://api.example.com/v1"
5154model = "gpt"
5155fallback = ["default", "local"]
5156
5157[[provider.route]]
5158name = "local"
5159base_url = "http://127.0.0.1:8080/v1"
5160model = "qwen3-coder"
5161"#;
5162        let c = parse(text);
5163        c.validate_routes().unwrap();
5164        let chain = c.chain().unwrap();
5165        let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5166        assert_eq!(names, ["default", "local"]);
5167        assert_eq!(chain.routes[0].config.model, "gpt");
5168    }
5169
5170    #[test]
5171    fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
5172        // `max_retries = 0` at provider level is a tuning key, not a server: a config that
5173        // uses only routes must not grow a `default` route with no endpoint, or every error
5174        // that lists the routes offers one that cannot be used.
5175        let text = "\
5176[provider]
5177max_retries = 0
5178fallback = [\"local\", \"big\"]
5179[[provider.route]]
5180name = \"local\"
5181base_url = \"http://127.0.0.1:8081/v1\"
5182model = \"small\"
5183[[provider.route]]
5184name = \"big\"
5185base_url = \"http://127.0.0.1:8082/v1\"
5186model = \"large\"
5187";
5188        let c = parse(text);
5189        c.validate_routes().unwrap();
5190        let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
5191        assert_eq!(names, ["local", "big"], "no phantom default route");
5192
5193        let mut pinned = parse(text);
5194        let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
5195        let e = e.to_string();
5196        assert!(
5197            e.contains("unknown route `default`") && e.contains("local, big"),
5198            "{e}"
5199        );
5200        assert!(!e.contains("provider.base_url"), "{e}");
5201    }
5202
5203    #[test]
5204    fn two_routes_with_the_same_name_are_refused_naming_it() {
5205        let e = refusal(
5206            "[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
5207             [[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5208        );
5209        assert!(e.contains("`a`") && e.contains("unique"), "{e}");
5210    }
5211
5212    #[test]
5213    fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
5214        let e = refusal("[[provider.route]]\nname=\"  \"\nbase_url=\"u\"\nmodel=\"m\"\n");
5215        assert!(
5216            e.contains("provider.route #1") && e.contains("no name"),
5217            "{e}"
5218        );
5219        let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
5220        assert!(e.contains("provider.route #1"), "{e}");
5221    }
5222
5223    #[test]
5224    fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
5225        let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5226        let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
5227        assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
5228        let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
5229        assert_eq!(c.chain().unwrap().routes[0].name, "default");
5230    }
5231
5232    #[test]
5233    fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
5234        let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
5235        assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
5236        let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
5237        assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
5238    }
5239
5240    #[test]
5241    fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
5242        let e = refusal(
5243            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5244             [[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
5245        );
5246        assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
5247    }
5248
5249    #[test]
5250    fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
5251        let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
5252        assert!(e.contains("`cloud`"), "{e}");
5253        assert!(e.contains("local, big"), "{e}");
5254    }
5255
5256    #[test]
5257    fn an_empty_fallback_is_a_typo_not_a_policy() {
5258        let e = refusal("[provider]\nfallback = []\n");
5259        assert!(e.contains("provider.fallback is empty"), "{e}");
5260    }
5261
5262    #[test]
5263    fn a_fallback_that_lists_a_route_twice_is_refused() {
5264        let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
5265        assert!(e.contains("`local` twice"), "{e}");
5266    }
5267
5268    #[test]
5269    fn a_fallback_or_route_table_inside_a_route_is_refused() {
5270        let e = refusal(
5271            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
5272        );
5273        assert!(e.contains("`r`") && e.contains("directly"), "{e}");
5274    }
5275
5276    const WITH_AUX: &str = "\
5277[provider]
5278base_url = \"http://d/v1\"
5279model = \"dm\"
5280aux = \"cheap\"
5281[[provider.route]]
5282name = \"cheap\"
5283base_url = \"http://c/v1\"
5284model = \"cm\"
5285";
5286
5287    #[test]
5288    fn aux_names_a_route_and_the_role_table_says_so() {
5289        let chain = parse(WITH_AUX).chain().unwrap();
5290        assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
5291        assert_eq!(chain.aux.unwrap().config.model, "cm");
5292        let roles = parse(WITH_AUX).chain().unwrap().roles();
5293        assert_eq!(roles.len(), 2, "only roles that exist get a row");
5294        assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
5295        assert_eq!(
5296            roles[1].to_string(),
5297            "delegate \u{2192} default (no delegate route set)"
5298        );
5299    }
5300
5301    #[test]
5302    fn delegate_names_a_route_and_the_role_table_says_so() {
5303        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
5304        let chain = c.chain().unwrap();
5305        assert_eq!(
5306            chain.delegate.as_ref().map(|r| r.name.as_str()),
5307            Some("cheap")
5308        );
5309        assert!(chain.aux.is_none());
5310        let roles = chain.roles();
5311        assert_eq!(
5312            roles[0].to_string(),
5313            "judgement \u{2192} default (no aux route set)"
5314        );
5315        assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
5316    }
5317
5318    #[test]
5319    fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
5320        // Both keys set, and `--route cheap`: every role is on `cheap`, because a pin bounds
5321        // where this run's text may go.
5322        let mut c =
5323            parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5324        c.pin_route(Some("cheap"), &|_| None).unwrap();
5325        let chain = c.chain().unwrap();
5326        assert_eq!(chain.source, ChainSource::Pinned);
5327        assert_eq!(
5328            chain.aux.as_ref().map(|r| r.name.as_str()),
5329            Some("cheap"),
5330            "the pinned route, not the key's own value"
5331        );
5332        assert_eq!(
5333            chain.delegate.as_ref().map(|r| r.name.as_str()),
5334            Some("cheap")
5335        );
5336        for role in chain.roles() {
5337            assert!(role.pinned, "{role} should be pinned");
5338            assert!(!role.set, "{role} should not claim the key decided it");
5339            assert_eq!(role.route, "cheap");
5340            assert!(role.to_string().ends_with("(pinned)"), "{role}");
5341        }
5342
5343        // The same config without a pin keeps both keys.
5344        let c =
5345            parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5346        let chain = c.chain().unwrap();
5347        assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
5348    }
5349
5350    #[test]
5351    fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
5352        let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
5353        assert!(
5354            e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
5355            "{e}"
5356        );
5357        // Empty means unset, the same as an absent line — the shipped config writes it that way.
5358        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
5359        c.validate_routes()
5360            .expect("an empty delegate is a config that loads");
5361        let e = refusal(
5362            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
5363             [provider]\nfallback=[\"r\"]\n",
5364        );
5365        assert!(
5366            e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
5367            "{e}"
5368        );
5369        let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
5370        assert!(e.contains("delegate"), "{e}");
5371    }
5372
5373    #[test]
5374    fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5375        assert_eq!(Config::default().tools.delegate, Policy::Ask);
5376        let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
5377        assert_eq!(cfg.tools.delegate, Policy::Deny);
5378        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5379        assert_eq!(starter.tools.delegate, Policy::Ask);
5380        assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
5381    }
5382
5383    #[test]
5384    fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
5385        let chain = parse(TWO_ROUTES).chain().unwrap();
5386        assert!(chain.aux.is_none());
5387        assert_eq!(
5388            chain.roles()[0].to_string(),
5389            "judgement \u{2192} local (no aux route set)"
5390        );
5391        let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5392        assert_eq!(
5393            bare.chain().unwrap().roles()[0].to_string(),
5394            "judgement \u{2192} default (no aux route set)"
5395        );
5396    }
5397
5398    #[test]
5399    fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
5400        let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
5401        assert!(
5402            e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
5403            "{e}"
5404        );
5405        // Empty is not a misspelling to refuse any more: it is the shipped spelling of "no aux
5406        // route", and the file a first install writes has it in it (`empty_is_none`). A name that
5407        // is *set* and unknown is still refused, above.
5408        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
5409        c.validate_routes()
5410            .expect("an empty aux route is a config that loads");
5411        assert!(c.chain().unwrap().aux.is_none());
5412    }
5413
5414    #[test]
5415    fn aux_inside_a_route_is_refused_like_fallback_and_route() {
5416        let e = refusal(
5417            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
5418             [provider]\nfallback=[\"r\"]\n",
5419        );
5420        assert!(
5421            e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
5422            "{e}"
5423        );
5424    }
5425
5426    #[test]
5427    fn a_wrong_typed_aux_is_an_error_naming_the_key() {
5428        let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
5429        assert!(e.contains("aux"), "{e}");
5430    }
5431
5432    #[test]
5433    fn aux_may_name_the_default_route_when_provider_is_one() {
5434        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
5435        assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
5436        let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
5437             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5438        assert!(refusal(tuning_only).contains("Routes that exist: r"));
5439    }
5440
5441    #[test]
5442    fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
5443        let bad =
5444            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
5445        let e = Config::from_toml_str(bad).unwrap_err();
5446        assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
5447        let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
5448        assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
5449    }
5450
5451    #[test]
5452    fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
5453        let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
5454        assert!(
5455            e.contains("fallback") && e.contains("--route") && e.contains("r"),
5456            "{e}"
5457        );
5458    }
5459
5460    #[test]
5461    fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
5462        let c = parse(
5463            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5464             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5465        );
5466        let chain = c.chain().unwrap();
5467        assert_eq!(chain.source, ChainSource::Default);
5468        assert_eq!(chain.routes.len(), 1);
5469        assert_eq!(chain.routes[0].name, "default");
5470        let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
5471        assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
5472    }
5473
5474    #[test]
5475    fn a_bare_config_still_says_what_is_wrong_with_provider() {
5476        let e = Config::default()
5477            .require_provider()
5478            .unwrap_err()
5479            .to_string();
5480        assert!(e.contains("provider.base_url is not set"), "{e}");
5481        assert!(e.contains("eclipse config init"), "{e}");
5482        let c = parse("[provider]\nbase_url=\"u\"\n");
5483        assert!(c
5484            .require_provider()
5485            .unwrap_err()
5486            .to_string()
5487            .contains("provider.model is not set"));
5488    }
5489
5490    #[test]
5491    fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
5492        let mut c = parse(TWO_ROUTES);
5493        c.pin_route(Some("big"), &env_of(&[])).unwrap();
5494        let chain = c.chain().unwrap();
5495        assert_eq!(chain.source, ChainSource::Pinned);
5496        assert_eq!(chain.routes.len(), 1);
5497        assert_eq!(chain.routes[0].name, "big");
5498    }
5499
5500    #[test]
5501    fn an_unknown_pin_lists_the_routes_that_exist() {
5502        let mut c = parse(TWO_ROUTES);
5503        let e = c
5504            .pin_route(Some("nope"), &env_of(&[]))
5505            .unwrap_err()
5506            .to_string();
5507        assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
5508        let e = c
5509            .pin_route(Some(" "), &env_of(&[]))
5510            .unwrap_err()
5511            .to_string();
5512        assert!(e.contains("--route needs a route name"), "{e}");
5513    }
5514
5515    #[test]
5516    fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
5517        let mut c = parse(TWO_ROUTES);
5518        c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
5519            .unwrap();
5520        assert_eq!(c.route_pin.as_deref(), Some("big"));
5521        c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
5522            .unwrap();
5523        assert_eq!(c.route_pin.as_deref(), Some("local"));
5524        let mut c = parse(TWO_ROUTES);
5525        c.dotenv
5526            .values
5527            .insert("ECLIPSE_ROUTE".into(), "local".into());
5528        c.pin_route(None, &env_of(&[])).unwrap();
5529        assert_eq!(
5530            c.route_pin.as_deref(),
5531            Some("local"),
5532            "the .env chain counts too"
5533        );
5534        let mut c = parse(TWO_ROUTES);
5535        c.pin_route(None, &env_of(&[])).unwrap();
5536        assert_eq!(c.route_pin, None);
5537    }
5538
5539    #[test]
5540    fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
5541        let mut c = parse(
5542            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5543             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
5544        );
5545        c.apply_env(&env_of(&[
5546            ("R_KEY", "from-r"),
5547            ("ECLIPSE_API_KEY", "for-default"),
5548        ]));
5549        assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
5550        assert_eq!(
5551            c.provider.route[0].config.api_key.as_deref(),
5552            Some("from-r")
5553        );
5554
5555        let mut only_routes = parse(TWO_ROUTES);
5556        only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
5557        assert_eq!(
5558            only_routes.provider.api_key, None,
5559            "no phantom default route"
5560        );
5561        assert_eq!(only_routes.provider.route[0].config.api_key, None);
5562    }
5563
5564    #[test]
5565    fn the_redacted_config_hides_every_routes_key_and_round_trips() {
5566        let c = parse(TWO_ROUTES);
5567        let t = c.to_toml_redacted().unwrap();
5568        assert!(!t.contains("hunter2"), "{t}");
5569        assert!(
5570            t.contains("[[provider.route]]") && t.contains("<redacted>"),
5571            "{t}"
5572        );
5573        let back = parse(&t);
5574        assert_eq!(back.provider.fallback, c.provider.fallback);
5575        assert_eq!(back.provider.route.len(), 2);
5576        assert_eq!(back.provider.route[1].config.timeout_secs, 30);
5577    }
5578
5579    #[test]
5580    fn a_config_without_routes_prints_no_provider_route_keys() {
5581        // The table, not the letters: `[vision] route` is a key of its own, and a substring check
5582        // for the word would have made that a regression instead of a setting.
5583        let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5584        let t = c.to_toml_redacted().unwrap();
5585        let parsed: toml::Value = toml::from_str(&t).unwrap();
5586        let provider = parsed.get("provider").expect("a provider table");
5587        for absent in ["route", "fallback", "aux", "delegate"] {
5588            assert!(
5589                provider.get(absent).is_none(),
5590                "`provider.{absent}` printed for a config with one route: {t}"
5591            );
5592        }
5593    }
5594
5595    #[test]
5596    fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
5597        let tmp = tempfile::tempdir().unwrap();
5598        let path = tmp.path().join("c.toml");
5599        std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
5600        let e = Config::load_with(Some(&path), &env_of(&[]))
5601            .unwrap_err()
5602            .to_string();
5603        assert!(e.contains("`ghost`"), "{e}");
5604    }
5605
5606    #[test]
5607    fn context_policy_defaults_and_the_rail_it_derives() {
5608        let c = ContextPolicyConfig::default();
5609        assert!(
5610            c.judge,
5611            "the model half is the judgement pass, and it ships on: compile plus one bounded call"
5612        );
5613        assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
5614        assert_eq!(c.compact_at, 0.85);
5615        assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
5616        assert_eq!(c.window_tokens, 0, "no window is invented");
5617        assert_eq!(c.budget_for(0), 0, "no window, no rail");
5618        assert_eq!(c.budget_for(327_680), 278_528);
5619        let off = ContextPolicyConfig {
5620            compact_at: 0.0,
5621            ..c.clone()
5622        };
5623        assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
5624        let half = ContextPolicyConfig {
5625            compact_at: 0.5,
5626            ..c
5627        };
5628        assert_eq!(half.budget_for(131_072), 65_536);
5629    }
5630
5631    #[test]
5632    fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
5633        for bad in ["1.5", "-0.2"] {
5634            let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
5635            let err = c.context.validate().unwrap_err().to_string();
5636            assert!(
5637                err.contains("context.compact_at"),
5638                "{bad} must be named in the error: {err}"
5639            );
5640        }
5641        assert!(parse("[context]\ncompact_at = 0.6\n")
5642            .context
5643            .validate()
5644            .is_ok());
5645        assert!(parse("[context]\ncompact_at = 0\n")
5646            .context
5647            .validate()
5648            .is_ok());
5649    }
5650}
5651
5652#[cfg(test)]
5653mod mcp_editor_tests {
5654    use super::*;
5655    use crate::mcp::Spec;
5656
5657    fn spec(text: &str) -> Spec {
5658        toml::from_str(text).unwrap()
5659    }
5660
5661    fn add(spec: &Spec) -> String {
5662        let out = mcp_add(CONFIG, spec).unwrap();
5663        // Every writer proves itself the same way: the file it returns loads.
5664        parse_text(&out).unwrap();
5665        out
5666    }
5667
5668    const CONFIG: &str = r#"# my config
5669[provider]
5670base_url = "http://127.0.0.1:8081/v1"
5671model = "m"
5672
5673# this comment belongs to the first entry
5674[[mcp]]
5675name = "first"
5676command = "one"
5677
5678# and this one to the second
5679[[mcp]]
5680name = "second"
5681command = "two"
5682policy = "allow"
5683"#;
5684
5685    #[test]
5686    fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
5687        let out = add(&spec(
5688            "name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
5689        ));
5690        let cfg = parse_text(&out).unwrap();
5691        assert_eq!(
5692            cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
5693            ["first", "second", "third"]
5694        );
5695        let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
5696        assert_eq!(third.args, ["--x"]);
5697        assert_eq!(third.prefix, "t_");
5698        // The two hand-written entries and both comments are untouched, byte for byte.
5699        for line in [
5700            "# my config",
5701            "# this comment belongs to the first entry",
5702            "# and this one to the second",
5703        ] {
5704            assert!(out.contains(line), "lost {line:?}:\n{out}");
5705        }
5706        assert!(
5707            out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
5708            "{out}"
5709        );
5710        assert!(
5711            !out.contains("args = []"),
5712            "only what was set is written:\n{out}"
5713        );
5714    }
5715
5716    #[test]
5717    fn a_duplicate_name_is_refused_and_named_by_line() {
5718        let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
5719        assert!(err.contains("already declared at line 7"), "{err}");
5720    }
5721
5722    #[test]
5723    fn an_unusable_entry_is_refused_before_anything_is_written() {
5724        // http with a command: `Spec::validate`'s own refusal, wrapped in the writer's voice.
5725        let err = mcp_add(
5726            CONFIG,
5727            &spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
5728        )
5729        .unwrap_err();
5730        assert!(err.starts_with("that entry is not usable"), "{err}");
5731        assert!(err.contains("belong to the stdio transport"), "{err}");
5732    }
5733
5734    #[test]
5735    fn remove_takes_the_named_block_and_the_blank_line_after_it() {
5736        let out = mcp_remove(CONFIG, "first").unwrap();
5737        let cfg = parse_text(&out).unwrap();
5738        assert_eq!(
5739            cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
5740            ["second"]
5741        );
5742        // The second entry's comment stays with the second entry.
5743        assert!(out.contains("# and this one to the second"), "{out}");
5744        assert!(!out.contains("name = \"first\""), "{out}");
5745        assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
5746    }
5747
5748    #[test]
5749    fn remove_says_what_the_file_does_declare() {
5750        let err = mcp_remove(CONFIG, "nope").unwrap_err();
5751        assert!(err.contains("declares first, second"), "{err}");
5752        let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
5753        let err = mcp_remove(bare, "nope").unwrap_err();
5754        assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
5755    }
5756
5757    #[test]
5758    fn disable_flips_the_line_inside_its_own_block() {
5759        let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
5760        let cfg = parse_text(&off).unwrap();
5761        assert!(
5762            cfg.mcp
5763                .iter()
5764                .find(|s| s.name == "second")
5765                .unwrap()
5766                .disabled
5767        );
5768        assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
5769        // Written into the block that already exists, not appended to the file.
5770        let second_at = off.find("name = \"second\"").unwrap();
5771        let tail = &off[second_at..];
5772        assert!(tail.contains("disabled = true"), "{off}");
5773        assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));
5774
5775        let on = mcp_set_disabled(&off, "second", false).unwrap();
5776        let cfg = parse_text(&on).unwrap();
5777        assert!(
5778            !cfg.mcp
5779                .iter()
5780                .find(|s| s.name == "second")
5781                .unwrap()
5782                .disabled
5783        );
5784        assert!(
5785            on.contains("disabled = false"),
5786            "said out loud, not deleted:\n{on}"
5787        );
5788    }
5789
5790    #[test]
5791    fn disable_on_an_entry_without_the_key_inserts_one() {
5792        let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
5793        assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
5794        assert!(parse_text(&off).unwrap().mcp[0].disabled);
5795    }
5796
5797    /// `#517`: an edit is a line-level splice inside one block. The neighbours — and this entry's
5798    /// own comments and ordering — round trip byte for byte; only the lines whose value changed
5799    /// move, which is the whole reason this is not a remove followed by an add.
5800    #[test]
5801    fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
5802        let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
5803        parse_text(&out).unwrap();
5804        assert_eq!(
5805            out,
5806            CONFIG.replace(
5807                "command = \"two\"\npolicy = \"allow\"",
5808                "command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
5809            ),
5810            "one added line, and not one other character moved:\n{out}"
5811        );
5812    }
5813
5814    /// A field set back to its default loses its line rather than gaining a default one, and a
5815    /// new one is appended in the renderer's order — again, nothing else moves.
5816    #[test]
5817    fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
5818        let on = mcp_update(CONFIG, "second", |entry| {
5819            entry.token_env = Some("HA_TOKEN".into())
5820        })
5821        .unwrap();
5822        assert_eq!(
5823            on,
5824            CONFIG.replace(
5825                "command = \"two\"\npolicy = \"allow\"",
5826                "command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
5827            ),
5828            "{on}"
5829        );
5830        let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
5831        assert_eq!(
5832            off, CONFIG,
5833            "clearing a field removes its line and nothing else"
5834        );
5835    }
5836
5837    /// A comment written *inside* a block belongs to that block, so it survives an edit to a
5838    /// neighbouring line of the same entry.
5839    #[test]
5840    fn an_edit_keeps_a_comment_written_inside_the_block() {
5841        let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
5842        let out = mcp_update(inner, "a", |entry| {
5843            entry.args = vec!["--y".into()];
5844        })
5845        .unwrap();
5846        assert_eq!(
5847            out,
5848            "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
5849             args = [\"--y\"]\n",
5850            "{out}"
5851        );
5852    }
5853
5854    /// A rename is a remove and an add, and the writer says so rather than doing half of one.
5855    #[test]
5856    fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
5857        let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
5858        assert!(err.contains("an edit does not rename"), "{err}");
5859
5860        let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
5861        assert!(err.contains("declares first, second"), "{err}");
5862
5863        // And an unusable result is the validator's sentence, before anything is written.
5864        let err = mcp_update(CONFIG, "second", |entry| {
5865            entry.transport = crate::mcp::Transport::Http;
5866            entry.url = Some("http://h/mcp".into());
5867        })
5868        .unwrap_err();
5869        assert!(err.starts_with("that entry is not usable"), "{err}");
5870        assert!(err.contains("belong to the stdio transport"), "{err}");
5871    }
5872
5873    #[test]
5874    fn an_empty_file_gets_its_first_entry_cleanly() {
5875        let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
5876        assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
5877        assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
5878    }
5879
5880    #[test]
5881    fn a_second_entry_is_separated_by_exactly_one_blank_line() {
5882        let out = add(&spec("name = \"third\"\ncommand = \"three\""));
5883        assert!(!out.contains("\n\n\n"), "{out}");
5884        assert!(
5885            out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
5886            "{out}"
5887        );
5888    }
5889}