Skip to main content

mur_common/config/
mod.rs

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