Skip to main content

mur_common/config/
mod.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3
4mod attribution;
5mod backend;
6mod conversations;
7mod ops;
8mod scratch;
9mod search;
10mod skills;
11mod turn_track;
12
13pub use attribution::*;
14pub use backend::*;
15pub use conversations::*;
16pub use ops::*;
17pub use scratch::*;
18pub use search::*;
19pub use skills::*;
20pub use turn_track::*;
21
22use ops::{
23    default_heartbeat_interval_secs, default_heartbeat_stale_after_intervals, default_rotate_at_mb,
24};
25
26pub const DEFAULT_LOCAL_LLM_MODEL: &str = "qwen3.5:4b";
27
28/// Default model id seeded for the built-in "MUR" agent and used to name the
29/// bundled MLX weights. This is the DEFAULT VALUE only — it is written into the
30/// seed agent's profile and can be changed by the user afterwards; it is not a
31/// behavioural constant baked into logic.
32pub const DEFAULT_BUNDLED_MODEL_ID: &str = "Qwen3.5-2B-MLX-4bit";
33
34pub const DEFAULT_MAX_RETRIES: u32 = 1;
35pub const DEFAULT_BACKOFF_BASE_MS: u64 = 500;
36pub const DEFAULT_COOLDOWN_SECS: u64 = 60;
37pub const DEFAULT_ROUTING_THRESHOLD: u32 = 2000;
38pub const DEFAULT_SMART_MAX_ESCALATIONS: u32 = 1;
39
40/// Smart background routing is opt-in. Its failure mode is silent and
41/// irreversible for the turn it degrades, which is the kind of automation that
42/// has to be asked for. See the capability-gate spec §2.
43pub const DEFAULT_SMART_ENABLED: bool = false;
44
45/// The Ollama provider default endpoint. Single definition — `BackendConfig`
46/// resolution (`default_ollama_endpoint`), `config_migrate`, and the
47/// conversations `doctor`/`preflight` probes all read this constant instead of
48/// repeating the literal.
49pub const DEFAULT_OLLAMA_ENDPOINT: &str = "http://localhost:11434";
50
51fn default_max_retries() -> u32 {
52    DEFAULT_MAX_RETRIES
53}
54fn default_backoff_base_ms() -> u64 {
55    DEFAULT_BACKOFF_BASE_MS
56}
57fn default_cooldown_secs() -> u64 {
58    DEFAULT_COOLDOWN_SECS
59}
60fn default_smart_max_escalations() -> u32 {
61    DEFAULT_SMART_MAX_ESCALATIONS
62}
63fn default_smart_enabled() -> bool {
64    DEFAULT_SMART_ENABLED
65}
66
67/// Smart background routing: auto-pick a cheap model for low-stakes/background
68/// requests instead of always dialing the agent's primary model_ref. Defaults
69/// OFF — enable it globally (`mur model smart on`) or per agent. `cheap: None`
70/// auto-picks the cheapest registry entry that can serve the request
71/// (`mur_common::model::pick_cheap_model`).
72#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
73pub struct SmartConfig {
74    #[serde(default = "default_smart_enabled")]
75    pub enabled: bool,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub cheap: Option<String>,
78    #[serde(default = "default_smart_max_escalations")]
79    pub max_escalations: u32,
80}
81
82impl Default for SmartConfig {
83    fn default() -> Self {
84        Self {
85            enabled: DEFAULT_SMART_ENABLED,
86            cheap: None,
87            max_escalations: DEFAULT_SMART_MAX_ESCALATIONS,
88        }
89    }
90}
91
92/// Config-layered model selection + failure fallback. See
93/// docs/superpowers/specs/2026-07-12-intelligent-model-switch-design.md.
94#[derive(Debug, Clone, Serialize, Deserialize, Default)]
95pub struct ModelSwitchConfig {
96    /// Global default model_ref when an agent has no `model_ref`.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub default: Option<String>,
99    /// Global fallback chain (ordered model_refs).
100    #[serde(default, skip_serializing_if = "Vec::is_empty")]
101    pub fallback_chain: Vec<String>,
102    #[serde(default)]
103    pub retry: RetryConfig,
104    #[serde(default)]
105    pub routing: RoutingConfig,
106    #[serde(default)]
107    pub smart: SmartConfig,
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct RetryConfig {
112    #[serde(default = "default_max_retries")]
113    pub max_retries: u32,
114    #[serde(default = "default_backoff_base_ms")]
115    pub backoff_base_ms: u64,
116    #[serde(default = "default_cooldown_secs")]
117    pub cooldown_secs: u64,
118}
119
120impl Default for RetryConfig {
121    fn default() -> Self {
122        Self {
123            max_retries: DEFAULT_MAX_RETRIES,
124            backoff_base_ms: DEFAULT_BACKOFF_BASE_MS,
125            cooldown_secs: DEFAULT_COOLDOWN_SECS,
126        }
127    }
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
131pub struct RoutingConfig {
132    #[serde(default)]
133    pub enabled: bool,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub cheap: Option<String>,
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub frontier: Option<String>,
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub threshold_input_tokens: Option<u32>,
140}
141
142/// Partial view of [`SmartConfig`] for per-agent overrides: `None` on a field
143/// means "inherit the global value". A distinct type rather than reusing
144/// `SmartConfig`, because a full config standing in for a partial is exactly
145/// what made an omitted field silently mean `false` instead of "unset".
146#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
147pub struct SmartOverride {
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub enabled: Option<bool>,
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub cheap: Option<String>,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub max_escalations: Option<u32>,
154}
155
156/// Partial view of [`RoutingConfig`]. Same inheritance rule as
157/// [`SmartOverride`].
158#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
159pub struct RoutingOverride {
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub enabled: Option<bool>,
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub cheap: Option<String>,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub frontier: Option<String>,
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub threshold_input_tokens: Option<u32>,
168    /// Legacy nesting. Smart used to be overridden at `routing.smart`;
169    /// profiles written before the promotion to `AgentProfile.smart` — and
170    /// every exported `.muragent` bundle — still carry it, so it stays
171    /// readable forever. MUR never writes it.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub smart: Option<SmartOverride>,
174}
175
176impl SmartConfig {
177    /// Global values with an agent's override layered on, field by field.
178    pub fn merged(&self, ov: Option<&SmartOverride>) -> SmartConfig {
179        let Some(o) = ov else { return self.clone() };
180        SmartConfig {
181            enabled: o.enabled.unwrap_or(self.enabled),
182            cheap: o.cheap.clone().or_else(|| self.cheap.clone()),
183            max_escalations: o.max_escalations.unwrap_or(self.max_escalations),
184        }
185    }
186}
187
188impl RoutingConfig {
189    /// Global values with an agent's override layered on, field by field.
190    pub fn merged(&self, ov: Option<&RoutingOverride>) -> RoutingConfig {
191        let Some(o) = ov else { return self.clone() };
192        RoutingConfig {
193            enabled: o.enabled.unwrap_or(self.enabled),
194            cheap: o.cheap.clone().or_else(|| self.cheap.clone()),
195            frontier: o.frontier.clone().or_else(|| self.frontier.clone()),
196            threshold_input_tokens: o.threshold_input_tokens.or(self.threshold_input_tokens),
197        }
198    }
199}
200
201/// Global MUR configuration (~/.mur/config.yaml)
202#[derive(Debug, Clone, Serialize, Deserialize, Default)]
203pub struct Config {
204    #[serde(default)]
205    pub embedding: EmbeddingConfig,
206
207    #[serde(default)]
208    pub llm: LlmConfig,
209
210    #[serde(default)]
211    pub models: ModelSwitchConfig,
212
213    #[serde(default)]
214    pub retrieval: RetrievalConfig,
215
216    #[serde(default)]
217    pub paths: PathConfig,
218
219    #[serde(default)]
220    pub server: ServerConfig,
221
222    #[serde(default)]
223    pub community: CommunityConfig,
224
225    #[serde(default)]
226    pub conversations: ConversationsConfig,
227
228    #[serde(default)]
229    pub sync: SyncConfig,
230
231    // --- P1.1 additions ---
232    #[serde(default)]
233    pub storage: StorageConfig,
234
235    #[serde(default)]
236    pub sources_global: SourcesGlobalConfig,
237
238    // --- E3 additions ---
239    #[serde(default)]
240    pub sleep_cycle: SleepCycleConfig,
241
242    // --- M2 additions ---
243    #[serde(default)]
244    pub skills: SkillsConfig,
245
246    // --- M6c additions ---
247    #[serde(default)]
248    pub skill_llm: SkillLlmConfig,
249
250    // --- M7a additions ---
251    #[serde(default)]
252    pub cross_agent: CrossAgentConfig,
253
254    // --- nudge additions ---
255    #[serde(default)]
256    pub nudge: NudgeConfig,
257
258    // --- mobile P4 additions ---
259    #[serde(default)]
260    pub mobile_relay: MobileRelayConfig,
261
262    // --- Ambient capture & harvest (2026-06-11 spec) ---
263    #[serde(default)]
264    pub session: SessionCfg,
265
266    #[serde(default)]
267    pub harvest: HarvestCfg,
268
269    // --- OAuth bridge (cc-proxy) routing for subscription tokens ---
270    #[serde(default)]
271    pub cc_proxy: CcProxyConfig,
272
273    // --- Agent CLI TUI ---
274    #[serde(default)]
275    pub cli: CliConfig,
276
277    // --- parallel_jobs MCP tool ---
278    #[serde(default)]
279    pub parallel_jobs: ParallelJobsConfig,
280
281    /// Memory-federation snapshot settings (`federation_snapshot:`).
282    #[serde(default)]
283    pub federation_snapshot: SnapshotConfig,
284
285    /// Proactive memory capture (`memory:`, federation P2).
286    #[serde(default)]
287    pub memory: MemoryConfig,
288
289    // --- fleet_run runtime built-in tool ---
290    #[serde(default)]
291    pub fleet_run: FleetRunConfig,
292
293    /// Daemon-side dispatch of cross-router fleets (`fleet_dispatch:`, #2116).
294    #[serde(default)]
295    pub fleet_dispatch: FleetDispatchConfig,
296
297    // --- git push broker (agent-side tools + daemon sweeper) ---
298    #[serde(default)]
299    pub git_push: GitPushConfig,
300
301    // --- `mur open` display policy ---
302    #[serde(default)]
303    pub open_items: OpenItemsConfig,
304
305    // --- Hub Fleet Manager redesign ---
306    #[serde(default)]
307    pub fleet: FleetConfig,
308
309    /// `mur update` post-upgrade behavior (`update:`, issue #866).
310    #[serde(default)]
311    pub update: UpdateConfig,
312
313    /// Job/fleet/workflow run-status heartbeat tuning (`runs:`).
314    #[serde(default)]
315    pub runs: RunsConfig,
316
317    /// Capture-queue rotation (`capture:`).
318    #[serde(default)]
319    pub capture: CaptureConfig,
320
321    /// Global execution limits (`limits:`), the outermost scope of spec
322    /// 2026-09-12 §3.1. Written textually by `mur limits --global`, never by
323    /// load-modify-save (that drops blocks other binaries own).
324    #[serde(default)]
325    pub limits: crate::limits::Limits,
326
327    /// Durable-monitor notification channels (`notifications:`). Absent
328    /// means log-only: `desktop` is opt-in.
329    #[serde(default)]
330    pub notifications: NotificationsConfig,
331
332    /// AgentResolver (`monitor_resolver:`), spec §混合處置策略 step 3.
333    /// Absent means off — see [`MonitorResolverConfig`].
334    #[serde(default)]
335    pub monitor_resolver: MonitorResolverConfig,
336
337    /// Pre-dispatch triage (`triage:`). Absent means shadow mode: triage
338    /// runs and records, and never stops a dispatch.
339    #[serde(default)]
340    pub triage: TriageConfig,
341
342    /// MUR's credit line on work an agent publishes (`attribution:`).
343    #[serde(default)]
344    pub attribution: AttributionConfig,
345
346    /// Per-agent scratch dir retention and doctor threshold (`scratch:`).
347    #[serde(default)]
348    pub scratch: ScratchConfig,
349
350    /// Per-turn copy-on-write track tuning (`turn_track:`).
351    #[serde(default)]
352    pub turn_track: TurnTrackConfig,
353
354    /// Code-search tool bounds (`search:`), e.g. `search.ast_grep`.
355    #[serde(default)]
356    pub search: SearchConfig,
357}
358
359impl Config {
360    /// Read from disk, falling back to defaults. Legacy conversation model
361    /// fields are migrated **in memory only** — this is called from agent
362    /// runtime processes (`mur-agent-runtime`), which must never write the
363    /// user's config file.
364    pub fn load_or_default(path: &std::path::Path) -> Self {
365        let Ok(text) = std::fs::read_to_string(path) else {
366            return Self::default();
367        };
368        let text = crate::config_migrate::migrate_conversations_yaml(&text).unwrap_or(text);
369        let mut cfg: Self = serde_yaml_ng::from_str(&text).unwrap_or_default();
370        cfg.sanitize();
371        cfg
372    }
373
374    /// Like [`Config::load_or_default`], but a file that is present and does
375    /// not parse is an error rather than silently the defaults. For a reader
376    /// that already holds a good copy and must not trade it for defaults
377    /// (the agent runtime's hot reload). An absent file is still the defaults.
378    pub fn try_load(path: &std::path::Path) -> Result<Self, String> {
379        let text = match std::fs::read_to_string(path) {
380            Ok(t) => t,
381            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
382            Err(e) => return Err(format!("{}: {e}", path.display())),
383        };
384        let text = crate::config_migrate::migrate_conversations_yaml(&text).unwrap_or(text);
385        let mut cfg: Self =
386            serde_yaml_ng::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
387        cfg.sanitize();
388        Ok(cfg)
389    }
390
391    /// Clamp values that are legal YAML but illegal at runtime. Called once
392    /// from [`Config::load_or_default`] — never from call sites, so every
393    /// reader (CLI, executor heartbeat ticker, `status_of`'s stale
394    /// threshold) sees the sanitized value.
395    fn sanitize(&mut self) {
396        // A zero interval would make the stale threshold zero (a healthy
397        // run instantly reports STALLED) and `tokio::time::interval` panics
398        // on a zero period — both from one user-edited line.
399        if self.runs.heartbeat_interval_secs == 0 {
400            self.runs.heartbeat_interval_secs = default_heartbeat_interval_secs();
401        }
402        // A zero rotate size would rotate on every single append.
403        if self.capture.rotate_at_mb == 0 {
404            self.capture.rotate_at_mb = default_rotate_at_mb();
405        }
406        if self.runs.heartbeat_stale_after_intervals == 0 {
407            self.runs.heartbeat_stale_after_intervals = default_heartbeat_stale_after_intervals();
408        }
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    #[test]
415    fn update_defaults_apply_when_block_absent_and_fields_parse() {
416        let c: super::Config = serde_yaml_ng::from_str("{}").unwrap();
417        assert_eq!(c.update, super::UpdateConfig::default());
418        assert!(c.update.codesign_identity.is_none());
419        assert!(c.update.restart_exclude.is_empty());
420
421        let c: super::Config = serde_yaml_ng::from_str(
422            "update:\n  codesign_identity: \"Developer ID Application: X (TEAM)\"\n  restart_exclude: [dr_worker_1]\n",
423        )
424        .unwrap();
425        assert_eq!(
426            c.update.codesign_identity.as_deref(),
427            Some("Developer ID Application: X (TEAM)")
428        );
429        assert_eq!(c.update.restart_exclude, vec!["dr_worker_1".to_string()]);
430    }
431
432    #[test]
433    fn federation_snapshot_defaults_apply_when_block_absent() {
434        let c: super::Config = serde_yaml_ng::from_str("{}").unwrap();
435        assert_eq!(c.federation_snapshot.poll_secs, 30);
436        assert_eq!(c.federation_snapshot.request_max_age_secs, 600);
437        assert_eq!(
438            c.federation_snapshot.min_lifecycle,
439            crate::skill::stats::LifecycleState::Stable
440        );
441        // Memory capture (P2a): defaults to auto_announce; `off` parses.
442        assert_eq!(c.memory.capture, super::CaptureMode::AutoAnnounce);
443        let c: super::Config = serde_yaml_ng::from_str("memory:\n  capture: off\n").unwrap();
444        assert_eq!(c.memory.capture, super::CaptureMode::Off);
445    }
446
447    use super::*;
448
449    #[test]
450    fn default_bundled_model_id_is_qwen35_2b() {
451        assert_eq!(
452            crate::config::DEFAULT_BUNDLED_MODEL_ID,
453            "Qwen3.5-2B-MLX-4bit"
454        );
455    }
456
457    #[test]
458    fn nudge_config_defaults() {
459        let c = NudgeConfig::default();
460        assert!(c.enabled);
461        assert_eq!(c.daily_cap, 3);
462        assert_eq!(c.snooze_days, 7);
463        assert_eq!(c.threshold, 3);
464    }
465
466    #[test]
467    fn config_has_nudge_section_with_defaults() {
468        let c: Config = serde_yaml_ng::from_str("{}").unwrap();
469        assert_eq!(c.nudge.daily_cap, 3);
470    }
471
472    #[test]
473    fn storage_config_default_is_lancedb() {
474        let c = StorageConfig::default();
475        assert_eq!(c.vector_backend, "lancedb");
476        assert_eq!(c.qdrant_url, None);
477        assert_eq!(c.qdrant_api_key_ref, None);
478    }
479
480    #[test]
481    fn sources_global_config_has_sensible_defaults() {
482        let c = SourcesGlobalConfig::default();
483        assert_eq!(c.poll_interval_secs, 600);
484        assert_eq!(c.max_chunks_per_sync, 10_000);
485        assert_eq!(c.max_parallel_sources, 3);
486        assert_eq!(c.default_weight, 1.0);
487        assert_eq!(c.embedding_batch_size, 32);
488    }
489
490    #[test]
491    fn config_default_has_storage_and_sources_global() {
492        let c = Config::default();
493        assert_eq!(c.storage.vector_backend, "lancedb");
494        assert_eq!(c.sources_global.default_weight, 1.0);
495    }
496
497    #[test]
498    fn config_loads_yaml_without_new_fields() {
499        // Existing users' config.yaml won't mention storage or sources_global.
500        // It must still parse.
501        let yaml = r#"
502embedding:
503  provider: ollama
504  model: test-model
505  dimensions: 512
506  ollama_endpoint: http://localhost:11434
507"#;
508        let c: Config = serde_yaml::from_str(yaml).expect("parses");
509        assert_eq!(c.storage.vector_backend, "lancedb");
510        assert_eq!(c.sources_global.max_parallel_sources, 3);
511    }
512
513    #[test]
514    fn llm_config_to_backend_config_anthropic_passthrough() {
515        let cfg = LlmConfig {
516            provider: "anthropic".into(),
517            model: "claude-haiku-4-5".into(),
518            api_key_env: Some("ANTHROPIC_API_KEY".into()),
519            api_key_ref: None,
520            openai_url: None,
521        };
522        let b = cfg.to_backend_config();
523        assert_eq!(b.provider, "anthropic");
524        assert_eq!(b.model, "claude-haiku-4-5");
525        assert_eq!(b.api_key_env.as_deref(), Some("ANTHROPIC_API_KEY"));
526        assert_eq!(b.endpoint, None);
527        assert_eq!(b.timeout_secs, None);
528    }
529
530    #[test]
531    fn llm_config_to_backend_config_openai_url_maps_to_endpoint() {
532        let cfg = LlmConfig {
533            provider: "openai".into(),
534            model: "gpt-4o-mini".into(),
535            api_key_env: None,
536            api_key_ref: None,
537            openai_url: Some("https://api.together.xyz/v1".into()),
538        };
539        let b = cfg.to_backend_config();
540        assert_eq!(b.provider, "openai");
541        assert_eq!(b.endpoint.as_deref(), Some("https://api.together.xyz/v1"));
542        assert_eq!(b.api_key_env, None); // factory will fall back to OPENAI_API_KEY
543    }
544
545    #[test]
546    fn llm_config_to_backend_config_ollama_openai_url_maps_to_endpoint() {
547        let cfg = LlmConfig {
548            provider: "ollama".into(),
549            model: "qwen3:14b".into(),
550            api_key_env: None,
551            api_key_ref: None,
552            openai_url: Some("http://192.168.1.10:11434".into()),
553        };
554        let b = cfg.to_backend_config();
555        assert_eq!(b.provider, "ollama");
556        assert_eq!(b.endpoint.as_deref(), Some("http://192.168.1.10:11434"));
557    }
558
559    #[test]
560    fn llm_config_to_backend_config_unknown_with_openai_url_aliases_to_openai() {
561        // Historical LlmConfig allowed provider="custom" + openai_url to act as
562        // an OpenAI-compatible passthrough. Preserve that by re-tagging as
563        // "openai" so factory dispatches to OpenAIBackend.
564        let cfg = LlmConfig {
565            provider: "custom-name".into(),
566            model: "some-model".into(),
567            api_key_env: Some("CUSTOM_KEY".into()),
568            api_key_ref: None,
569            openai_url: Some("https://my-proxy.local/v1".into()),
570        };
571        let b = cfg.to_backend_config();
572        assert_eq!(
573            b.provider, "openai",
574            "unknown provider + openai_url should alias to openai"
575        );
576        assert_eq!(b.endpoint.as_deref(), Some("https://my-proxy.local/v1"));
577    }
578
579    #[test]
580    fn api_key_ref_roundtrips_and_defaults_none() {
581        // Old YAML without the field still parses, field defaults to None.
582        let b: BackendConfig = serde_yaml_ng::from_str("provider: anthropic\nmodel: m\n").unwrap();
583        assert_eq!(b.api_key_ref, None);
584        let l: LlmConfig = serde_yaml_ng::from_str("provider: anthropic\nmodel: m\n").unwrap();
585        assert_eq!(l.api_key_ref, None);
586        let e: EmbeddingConfig = serde_yaml_ng::from_str("provider: ollama\nmodel: m\n").unwrap();
587        assert_eq!(e.api_key_ref, None);
588
589        // Set → survives YAML round-trip and to_backend_config.
590        let l2 = LlmConfig {
591            api_key_ref: Some("keychain:mur/anthropic".into()),
592            ..Default::default()
593        };
594        let y = serde_yaml_ng::to_string(&l2).unwrap();
595        let l3: LlmConfig = serde_yaml_ng::from_str(&y).unwrap();
596        assert_eq!(l3.api_key_ref.as_deref(), Some("keychain:mur/anthropic"));
597        assert_eq!(
598            l3.to_backend_config().api_key_ref.as_deref(),
599            Some("keychain:mur/anthropic")
600        );
601    }
602
603    #[test]
604    fn open_items_muted_parses_and_defaults_empty() {
605        let c: Config = serde_yaml::from_str("open_items:\n  muted:\n    - inbox\n").unwrap();
606        assert_eq!(c.open_items.muted, vec!["inbox".to_string()]);
607
608        let d: Config = serde_yaml::from_str("llm:\n  model: x\n").unwrap();
609        assert!(d.open_items.muted.is_empty(), "must default to no mutes");
610    }
611
612    /// Fail toward showing. A config that will not parse must yield an empty
613    /// mute set, never a quiet, confident, incomplete list.
614    #[test]
615    fn unreadable_config_yields_no_mutes() {
616        let tmp = tempfile::tempdir().unwrap();
617        let path = tmp.path().join("config.yaml");
618        std::fs::write(&path, "this: is: not: valid: yaml: [[[\n").unwrap();
619        let cfg = Config::load_or_default(&path);
620        assert!(
621            cfg.open_items.muted.is_empty(),
622            "a broken config must hide nothing"
623        );
624
625        // Same for a config that is simply absent.
626        let missing = Config::load_or_default(&tmp.path().join("nope.yaml"));
627        assert!(missing.open_items.muted.is_empty());
628    }
629
630    #[test]
631    fn rollup_config_accepts_backend_overrides() {
632        let yaml = r#"
633enabled: true
634extractive_backend:
635  provider: openai
636  model: Qwen3.5-4B-MLX-4bit
637  endpoint: http://127.0.0.1:8000/v1
638"#;
639        let c: RollupConfig = serde_yaml_ng::from_str(yaml).expect("parses");
640        let b = c.extractive_backend.expect("override present");
641        assert_eq!(b.provider, "openai");
642        assert_eq!(b.model, "Qwen3.5-4B-MLX-4bit");
643        assert_eq!(b.endpoint.as_deref(), Some("http://127.0.0.1:8000/v1"));
644        assert!(c.abstractive_backend.is_none());
645    }
646
647    #[test]
648    fn legacy_conversation_fields_are_gone_from_serialized_output() {
649        let cfg = Config::default();
650        // Scoped to the conversations block intentionally: `embedding` still
651        // carries its own `ollama_endpoint`, and asserting over the whole
652        // document here would require that field to be omitted, which is not
653        // the case. The Config type will never serialize without it, so this
654        // scoping to conversations is permanent.
655        let yaml = serde_yaml_ng::to_string(&cfg.conversations).expect("serializes");
656        for key in ["extractive_model", "abstractive_model", "ollama_endpoint"] {
657            assert!(
658                !yaml.contains(key),
659                "legacy key {key} still serialized:\n{yaml}"
660            );
661        }
662    }
663
664    #[test]
665    fn embedding_ollama_endpoint_is_omitted_when_unset() {
666        let mut cfg = Config::default();
667        cfg.embedding.provider = "omlx".into();
668        cfg.embedding.openai_url = Some("http://127.0.0.1:8000/v1".into());
669        cfg.embedding.ollama_endpoint = None;
670        let yaml = serde_yaml_ng::to_string(&cfg).expect("serializes");
671        assert!(
672            !yaml.contains("ollama_endpoint"),
673            "dead field re-emitted:\n{yaml}"
674        );
675    }
676
677    #[test]
678    fn embedding_ollama_endpoint_still_round_trips_when_set() {
679        let yaml =
680            "provider: ollama\nmodel: nomic-embed-text\nollama_endpoint: http://box.local:11434\n";
681        let e: EmbeddingConfig = serde_yaml_ng::from_str(yaml).expect("parses");
682        assert_eq!(e.ollama_endpoint.as_deref(), Some("http://box.local:11434"));
683    }
684}
685
686#[cfg(test)]
687mod model_switch_config_tests {
688    use super::*;
689
690    #[test]
691    fn model_switch_config_defaults_and_omitted_block() {
692        // Omitted `models:` block deserializes to defaults.
693        let cfg: Config = serde_yaml::from_str("{}").unwrap();
694        assert_eq!(cfg.models.default, None);
695        assert!(cfg.models.fallback_chain.is_empty());
696        assert_eq!(cfg.models.retry.max_retries, DEFAULT_MAX_RETRIES);
697        assert_eq!(cfg.models.retry.backoff_base_ms, DEFAULT_BACKOFF_BASE_MS);
698        assert_eq!(cfg.models.retry.cooldown_secs, DEFAULT_COOLDOWN_SECS);
699        assert!(!cfg.models.routing.enabled);
700
701        // A populated block round-trips.
702        let yaml = "models:\n  default: claude_sonnet\n  fallback_chain: [claude_sonnet, deepseek_v4_pro]\n  routing:\n    enabled: true\n    cheap: deepseek_v4_flash\n    frontier: claude_opus\n    threshold_input_tokens: 1500\n";
703        let cfg: Config = serde_yaml::from_str(yaml).unwrap();
704        assert_eq!(cfg.models.default.as_deref(), Some("claude_sonnet"));
705        assert_eq!(
706            cfg.models.fallback_chain,
707            vec!["claude_sonnet", "deepseek_v4_pro"]
708        );
709        assert!(cfg.models.routing.enabled);
710        assert_eq!(cfg.models.routing.threshold_input_tokens, Some(1500));
711    }
712
713    #[test]
714    fn smart_config_defaults_off_with_autopick() {
715        let cfg: Config = serde_yaml::from_str("{}").unwrap();
716        assert!(
717            !cfg.models.smart.enabled,
718            "Smart background routing is opt-in (capability-gate spec §2)"
719        );
720        assert_eq!(cfg.models.smart.cheap, None); // auto-pick
721        assert_eq!(
722            cfg.models.smart.max_escalations,
723            DEFAULT_SMART_MAX_ESCALATIONS
724        );
725    }
726
727    #[test]
728    fn smart_override_inherits_field_by_field() {
729        let global = SmartConfig {
730            enabled: true,
731            cheap: Some("g".into()),
732            max_escalations: 3,
733        };
734        assert_eq!(global.merged(None), global);
735        assert_eq!(global.merged(Some(&SmartOverride::default())), global);
736        // Overriding one field must not reset the others — the whole point.
737        let only_cheap = SmartOverride {
738            cheap: Some("a".into()),
739            ..Default::default()
740        };
741        let m = global.merged(Some(&only_cheap));
742        assert!(m.enabled, "overriding cheap must not disable Smart");
743        assert_eq!(m.cheap.as_deref(), Some("a"));
744        assert_eq!(m.max_escalations, 3);
745        // An explicit false still beats a global true.
746        let off = SmartOverride {
747            enabled: Some(false),
748            ..Default::default()
749        };
750        assert!(!global.merged(Some(&off)).enabled);
751    }
752
753    #[test]
754    fn routing_override_inherits_field_by_field() {
755        let global = RoutingConfig {
756            enabled: true,
757            cheap: Some("c".into()),
758            frontier: Some("f".into()),
759            threshold_input_tokens: Some(9),
760        };
761        let only_cheap = RoutingOverride {
762            cheap: Some("a".into()),
763            ..Default::default()
764        };
765        let m = global.merged(Some(&only_cheap));
766        assert!(m.enabled, "overriding cheap must not disable routing");
767        assert_eq!(m.cheap.as_deref(), Some("a"));
768        assert_eq!(m.frontier.as_deref(), Some("f"));
769        assert_eq!(m.threshold_input_tokens, Some(9));
770    }
771}