Skip to main content

mur_common/config/
mod.rs

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