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 sync: SyncConfig,
232
233    // --- P1.1 additions ---
234    #[serde(default)]
235    pub storage: StorageConfig,
236
237    #[serde(default)]
238    pub sources_global: SourcesGlobalConfig,
239
240    // --- E3 additions ---
241    #[serde(default)]
242    pub sleep_cycle: SleepCycleConfig,
243
244    // --- M2 additions ---
245    #[serde(default)]
246    pub skills: SkillsConfig,
247
248    // --- M6c additions ---
249    #[serde(default)]
250    pub skill_llm: SkillLlmConfig,
251
252    // --- M7a additions ---
253    #[serde(default)]
254    pub cross_agent: CrossAgentConfig,
255
256    // --- nudge additions ---
257    #[serde(default)]
258    pub nudge: NudgeConfig,
259
260    // --- mobile P4 additions ---
261    #[serde(default)]
262    pub mobile_relay: MobileRelayConfig,
263
264    // --- Ambient capture & harvest (2026-06-11 spec) ---
265    #[serde(default)]
266    pub session: SessionCfg,
267
268    #[serde(default)]
269    pub harvest: HarvestCfg,
270
271    // --- OAuth bridge (cc-proxy) routing for subscription tokens ---
272    #[serde(default)]
273    pub cc_proxy: CcProxyConfig,
274
275    // --- Agent CLI TUI ---
276    #[serde(default)]
277    pub cli: CliConfig,
278
279    // --- parallel_jobs MCP tool ---
280    #[serde(default)]
281    pub parallel_jobs: ParallelJobsConfig,
282
283    /// Memory-federation snapshot settings (`federation_snapshot:`).
284    #[serde(default)]
285    pub federation_snapshot: SnapshotConfig,
286
287    /// Proactive memory capture (`memory:`, federation P2).
288    #[serde(default)]
289    pub memory: MemoryConfig,
290
291    // --- fleet_run runtime built-in tool ---
292    #[serde(default)]
293    pub fleet_run: FleetRunConfig,
294
295    /// Daemon-side dispatch of cross-router fleets (`fleet_dispatch:`, #2116).
296    #[serde(default)]
297    pub fleet_dispatch: FleetDispatchConfig,
298
299    // --- git push broker (agent-side tools + daemon sweeper) ---
300    #[serde(default)]
301    pub git_push: GitPushConfig,
302
303    // --- `mur open` display policy ---
304    #[serde(default)]
305    pub open_items: OpenItemsConfig,
306
307    // --- Hub Fleet Manager redesign ---
308    #[serde(default)]
309    pub fleet: FleetConfig,
310
311    /// `mur update` post-upgrade behavior (`update:`, issue #866).
312    #[serde(default)]
313    pub update: UpdateConfig,
314
315    /// Job/fleet/workflow run-status heartbeat tuning (`runs:`).
316    #[serde(default)]
317    pub runs: RunsConfig,
318
319    /// Capture-queue rotation (`capture:`).
320    #[serde(default)]
321    pub capture: CaptureConfig,
322
323    /// Global execution limits (`limits:`), the outermost scope of spec
324    /// 2026-09-12 §3.1. Written textually by `mur limits --global`, never by
325    /// load-modify-save (that drops blocks other binaries own).
326    #[serde(default)]
327    pub limits: crate::limits::Limits,
328
329    /// Durable-monitor notification channels (`notifications:`). Absent
330    /// means log-only: `desktop` is opt-in.
331    #[serde(default)]
332    pub notifications: NotificationsConfig,
333
334    /// AgentResolver (`monitor_resolver:`), spec §混合處置策略 step 3.
335    /// Absent means off — see [`MonitorResolverConfig`].
336    #[serde(default)]
337    pub monitor_resolver: MonitorResolverConfig,
338
339    /// Pre-dispatch triage (`triage:`). Absent means shadow mode: triage
340    /// runs and records, and never stops a dispatch.
341    #[serde(default)]
342    pub triage: TriageConfig,
343
344    /// MUR's credit line on work an agent publishes (`attribution:`).
345    #[serde(default)]
346    pub attribution: AttributionConfig,
347
348    /// Per-agent scratch dir retention and doctor threshold (`scratch:`).
349    #[serde(default)]
350    pub scratch: ScratchConfig,
351
352    /// Channel consult (`consult:`): how long an `Ask` stays answerable.
353    #[serde(default)]
354    pub consult: ConsultConfig,
355
356    /// Per-turn copy-on-write track tuning (`turn_track:`).
357    #[serde(default)]
358    pub turn_track: TurnTrackConfig,
359
360    /// Code-search tool bounds (`search:`), e.g. `search.ast_grep`.
361    #[serde(default)]
362    pub search: SearchConfig,
363}
364
365impl Config {
366    /// Read from disk, falling back to defaults. Legacy conversation model
367    /// fields are migrated **in memory only** — this is called from agent
368    /// runtime processes (`mur-agent-runtime`), which must never write the
369    /// user's config file.
370    pub fn load_or_default(path: &std::path::Path) -> Self {
371        let Ok(text) = std::fs::read_to_string(path) else {
372            return Self::default();
373        };
374        let text = crate::config_migrate::migrate_conversations_yaml(&text).unwrap_or(text);
375        let mut cfg: Self = serde_yaml_ng::from_str(&text).unwrap_or_default();
376        cfg.sanitize();
377        cfg
378    }
379
380    /// Like [`Config::load_or_default`], but a file that is present and does
381    /// not parse is an error rather than silently the defaults. For a reader
382    /// that already holds a good copy and must not trade it for defaults
383    /// (the agent runtime's hot reload). An absent file is still the defaults.
384    pub fn try_load(path: &std::path::Path) -> Result<Self, String> {
385        let text = match std::fs::read_to_string(path) {
386            Ok(t) => t,
387            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
388            Err(e) => return Err(format!("{}: {e}", path.display())),
389        };
390        let text = crate::config_migrate::migrate_conversations_yaml(&text).unwrap_or(text);
391        let mut cfg: Self =
392            serde_yaml_ng::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?;
393        cfg.sanitize();
394        Ok(cfg)
395    }
396
397    /// Clamp values that are legal YAML but illegal at runtime. Called once
398    /// from [`Config::load_or_default`] — never from call sites, so every
399    /// reader (CLI, executor heartbeat ticker, `status_of`'s stale
400    /// threshold) sees the sanitized value.
401    fn sanitize(&mut self) {
402        // A zero interval would make the stale threshold zero (a healthy
403        // run instantly reports STALLED) and `tokio::time::interval` panics
404        // on a zero period — both from one user-edited line.
405        if self.runs.heartbeat_interval_secs == 0 {
406            self.runs.heartbeat_interval_secs = default_heartbeat_interval_secs();
407        }
408        // A zero rotate size would rotate on every single append.
409        if self.capture.rotate_at_mb == 0 {
410            self.capture.rotate_at_mb = default_rotate_at_mb();
411        }
412        if self.runs.heartbeat_stale_after_intervals == 0 {
413            self.runs.heartbeat_stale_after_intervals = default_heartbeat_stale_after_intervals();
414        }
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    #[test]
421    fn update_defaults_apply_when_block_absent_and_fields_parse() {
422        let c: super::Config = serde_yaml_ng::from_str("{}").unwrap();
423        assert_eq!(c.update, super::UpdateConfig::default());
424        assert!(c.update.codesign_identity.is_none());
425        assert!(c.update.restart_exclude.is_empty());
426
427        let c: super::Config = serde_yaml_ng::from_str(
428            "update:\n  codesign_identity: \"Developer ID Application: X (TEAM)\"\n  restart_exclude: [dr_worker_1]\n",
429        )
430        .unwrap();
431        assert_eq!(
432            c.update.codesign_identity.as_deref(),
433            Some("Developer ID Application: X (TEAM)")
434        );
435        assert_eq!(c.update.restart_exclude, vec!["dr_worker_1".to_string()]);
436    }
437
438    #[test]
439    fn federation_snapshot_defaults_apply_when_block_absent() {
440        let c: super::Config = serde_yaml_ng::from_str("{}").unwrap();
441        assert_eq!(c.federation_snapshot.poll_secs, 30);
442        assert_eq!(c.federation_snapshot.request_max_age_secs, 600);
443        assert_eq!(
444            c.federation_snapshot.min_lifecycle,
445            crate::skill::stats::LifecycleState::Stable
446        );
447        // Memory capture (P2a): defaults to auto_announce; `off` parses.
448        assert_eq!(c.memory.capture, super::CaptureMode::AutoAnnounce);
449        let c: super::Config = serde_yaml_ng::from_str("memory:\n  capture: off\n").unwrap();
450        assert_eq!(c.memory.capture, super::CaptureMode::Off);
451    }
452
453    use super::*;
454
455    #[test]
456    fn default_bundled_model_id_is_qwen35_2b() {
457        assert_eq!(
458            crate::config::DEFAULT_BUNDLED_MODEL_ID,
459            "Qwen3.5-2B-MLX-4bit"
460        );
461    }
462
463    #[test]
464    fn nudge_config_defaults() {
465        let c = NudgeConfig::default();
466        assert!(c.enabled);
467        assert_eq!(c.daily_cap, 3);
468        assert_eq!(c.snooze_days, 7);
469        assert_eq!(c.threshold, 3);
470    }
471
472    #[test]
473    fn config_has_nudge_section_with_defaults() {
474        let c: Config = serde_yaml_ng::from_str("{}").unwrap();
475        assert_eq!(c.nudge.daily_cap, 3);
476    }
477
478    #[test]
479    fn storage_config_default_is_lancedb() {
480        let c = StorageConfig::default();
481        assert_eq!(c.vector_backend, "lancedb");
482        assert_eq!(c.qdrant_url, None);
483        assert_eq!(c.qdrant_api_key_ref, None);
484    }
485
486    #[test]
487    fn sources_global_config_has_sensible_defaults() {
488        let c = SourcesGlobalConfig::default();
489        assert_eq!(c.poll_interval_secs, 600);
490        assert_eq!(c.max_chunks_per_sync, 10_000);
491        assert_eq!(c.max_parallel_sources, 3);
492        assert_eq!(c.default_weight, 1.0);
493        assert_eq!(c.embedding_batch_size, 32);
494    }
495
496    #[test]
497    fn config_default_has_storage_and_sources_global() {
498        let c = Config::default();
499        assert_eq!(c.storage.vector_backend, "lancedb");
500        assert_eq!(c.sources_global.default_weight, 1.0);
501    }
502
503    #[test]
504    fn config_loads_yaml_without_new_fields() {
505        // Existing users' config.yaml won't mention storage or sources_global.
506        // It must still parse.
507        let yaml = r#"
508embedding:
509  provider: ollama
510  model: test-model
511  dimensions: 512
512  ollama_endpoint: http://localhost:11434
513"#;
514        let c: Config = serde_yaml::from_str(yaml).expect("parses");
515        assert_eq!(c.storage.vector_backend, "lancedb");
516        assert_eq!(c.sources_global.max_parallel_sources, 3);
517    }
518
519    #[test]
520    fn llm_config_to_backend_config_anthropic_passthrough() {
521        let cfg = LlmConfig {
522            provider: "anthropic".into(),
523            model: "claude-haiku-4-5".into(),
524            api_key_env: Some("ANTHROPIC_API_KEY".into()),
525            api_key_ref: None,
526            openai_url: None,
527        };
528        let b = cfg.to_backend_config();
529        assert_eq!(b.provider, "anthropic");
530        assert_eq!(b.model, "claude-haiku-4-5");
531        assert_eq!(b.api_key_env.as_deref(), Some("ANTHROPIC_API_KEY"));
532        assert_eq!(b.endpoint, None);
533        assert_eq!(b.timeout_secs, None);
534    }
535
536    #[test]
537    fn llm_config_to_backend_config_openai_url_maps_to_endpoint() {
538        let cfg = LlmConfig {
539            provider: "openai".into(),
540            model: "gpt-4o-mini".into(),
541            api_key_env: None,
542            api_key_ref: None,
543            openai_url: Some("https://api.together.xyz/v1".into()),
544        };
545        let b = cfg.to_backend_config();
546        assert_eq!(b.provider, "openai");
547        assert_eq!(b.endpoint.as_deref(), Some("https://api.together.xyz/v1"));
548        assert_eq!(b.api_key_env, None); // factory will fall back to OPENAI_API_KEY
549    }
550
551    #[test]
552    fn llm_config_to_backend_config_ollama_openai_url_maps_to_endpoint() {
553        let cfg = LlmConfig {
554            provider: "ollama".into(),
555            model: "qwen3:14b".into(),
556            api_key_env: None,
557            api_key_ref: None,
558            openai_url: Some("http://192.168.1.10:11434".into()),
559        };
560        let b = cfg.to_backend_config();
561        assert_eq!(b.provider, "ollama");
562        assert_eq!(b.endpoint.as_deref(), Some("http://192.168.1.10:11434"));
563    }
564
565    #[test]
566    fn llm_config_to_backend_config_unknown_with_openai_url_aliases_to_openai() {
567        // Historical LlmConfig allowed provider="custom" + openai_url to act as
568        // an OpenAI-compatible passthrough. Preserve that by re-tagging as
569        // "openai" so factory dispatches to OpenAIBackend.
570        let cfg = LlmConfig {
571            provider: "custom-name".into(),
572            model: "some-model".into(),
573            api_key_env: Some("CUSTOM_KEY".into()),
574            api_key_ref: None,
575            openai_url: Some("https://my-proxy.local/v1".into()),
576        };
577        let b = cfg.to_backend_config();
578        assert_eq!(
579            b.provider, "openai",
580            "unknown provider + openai_url should alias to openai"
581        );
582        assert_eq!(b.endpoint.as_deref(), Some("https://my-proxy.local/v1"));
583    }
584
585    #[test]
586    fn api_key_ref_roundtrips_and_defaults_none() {
587        // Old YAML without the field still parses, field defaults to None.
588        let b: BackendConfig = serde_yaml_ng::from_str("provider: anthropic\nmodel: m\n").unwrap();
589        assert_eq!(b.api_key_ref, None);
590        let l: LlmConfig = serde_yaml_ng::from_str("provider: anthropic\nmodel: m\n").unwrap();
591        assert_eq!(l.api_key_ref, None);
592        let e: EmbeddingConfig = serde_yaml_ng::from_str("provider: ollama\nmodel: m\n").unwrap();
593        assert_eq!(e.api_key_ref, None);
594
595        // Set → survives YAML round-trip and to_backend_config.
596        let l2 = LlmConfig {
597            api_key_ref: Some("keychain:mur/anthropic".into()),
598            ..Default::default()
599        };
600        let y = serde_yaml_ng::to_string(&l2).unwrap();
601        let l3: LlmConfig = serde_yaml_ng::from_str(&y).unwrap();
602        assert_eq!(l3.api_key_ref.as_deref(), Some("keychain:mur/anthropic"));
603        assert_eq!(
604            l3.to_backend_config().api_key_ref.as_deref(),
605            Some("keychain:mur/anthropic")
606        );
607    }
608
609    #[test]
610    fn open_items_muted_parses_and_defaults_empty() {
611        let c: Config = serde_yaml::from_str("open_items:\n  muted:\n    - inbox\n").unwrap();
612        assert_eq!(c.open_items.muted, vec!["inbox".to_string()]);
613
614        let d: Config = serde_yaml::from_str("llm:\n  model: x\n").unwrap();
615        assert!(d.open_items.muted.is_empty(), "must default to no mutes");
616    }
617
618    /// Fail toward showing. A config that will not parse must yield an empty
619    /// mute set, never a quiet, confident, incomplete list.
620    #[test]
621    fn unreadable_config_yields_no_mutes() {
622        let tmp = tempfile::tempdir().unwrap();
623        let path = tmp.path().join("config.yaml");
624        std::fs::write(&path, "this: is: not: valid: yaml: [[[\n").unwrap();
625        let cfg = Config::load_or_default(&path);
626        assert!(
627            cfg.open_items.muted.is_empty(),
628            "a broken config must hide nothing"
629        );
630
631        // Same for a config that is simply absent.
632        let missing = Config::load_or_default(&tmp.path().join("nope.yaml"));
633        assert!(missing.open_items.muted.is_empty());
634    }
635
636    #[test]
637    fn rollup_config_accepts_backend_overrides() {
638        let yaml = r#"
639enabled: true
640extractive_backend:
641  provider: openai
642  model: Qwen3.5-4B-MLX-4bit
643  endpoint: http://127.0.0.1:8000/v1
644"#;
645        let c: RollupConfig = serde_yaml_ng::from_str(yaml).expect("parses");
646        let b = c.extractive_backend.expect("override present");
647        assert_eq!(b.provider, "openai");
648        assert_eq!(b.model, "Qwen3.5-4B-MLX-4bit");
649        assert_eq!(b.endpoint.as_deref(), Some("http://127.0.0.1:8000/v1"));
650        assert!(c.abstractive_backend.is_none());
651    }
652
653    #[test]
654    fn legacy_conversation_fields_are_gone_from_serialized_output() {
655        let cfg = Config::default();
656        // Scoped to the conversations block intentionally: `embedding` still
657        // carries its own `ollama_endpoint`, and asserting over the whole
658        // document here would require that field to be omitted, which is not
659        // the case. The Config type will never serialize without it, so this
660        // scoping to conversations is permanent.
661        let yaml = serde_yaml_ng::to_string(&cfg.conversations).expect("serializes");
662        for key in ["extractive_model", "abstractive_model", "ollama_endpoint"] {
663            assert!(
664                !yaml.contains(key),
665                "legacy key {key} still serialized:\n{yaml}"
666            );
667        }
668    }
669
670    #[test]
671    fn embedding_ollama_endpoint_is_omitted_when_unset() {
672        let mut cfg = Config::default();
673        cfg.embedding.provider = "omlx".into();
674        cfg.embedding.openai_url = Some("http://127.0.0.1:8000/v1".into());
675        cfg.embedding.ollama_endpoint = None;
676        let yaml = serde_yaml_ng::to_string(&cfg).expect("serializes");
677        assert!(
678            !yaml.contains("ollama_endpoint"),
679            "dead field re-emitted:\n{yaml}"
680        );
681    }
682
683    #[test]
684    fn embedding_ollama_endpoint_still_round_trips_when_set() {
685        let yaml =
686            "provider: ollama\nmodel: nomic-embed-text\nollama_endpoint: http://box.local:11434\n";
687        let e: EmbeddingConfig = serde_yaml_ng::from_str(yaml).expect("parses");
688        assert_eq!(e.ollama_endpoint.as_deref(), Some("http://box.local:11434"));
689    }
690}
691
692#[cfg(test)]
693mod model_switch_config_tests {
694    use super::*;
695
696    #[test]
697    fn model_switch_config_defaults_and_omitted_block() {
698        // Omitted `models:` block deserializes to defaults.
699        let cfg: Config = serde_yaml::from_str("{}").unwrap();
700        assert_eq!(cfg.models.default, None);
701        assert!(cfg.models.fallback_chain.is_empty());
702        assert_eq!(cfg.models.retry.max_retries, DEFAULT_MAX_RETRIES);
703        assert_eq!(cfg.models.retry.backoff_base_ms, DEFAULT_BACKOFF_BASE_MS);
704        assert_eq!(cfg.models.retry.cooldown_secs, DEFAULT_COOLDOWN_SECS);
705        assert!(!cfg.models.routing.enabled);
706
707        // A populated block round-trips.
708        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";
709        let cfg: Config = serde_yaml::from_str(yaml).unwrap();
710        assert_eq!(cfg.models.default.as_deref(), Some("claude_sonnet"));
711        assert_eq!(
712            cfg.models.fallback_chain,
713            vec!["claude_sonnet", "deepseek_v4_pro"]
714        );
715        assert!(cfg.models.routing.enabled);
716        assert_eq!(cfg.models.routing.threshold_input_tokens, Some(1500));
717    }
718
719    #[test]
720    fn smart_config_defaults_off_with_autopick() {
721        let cfg: Config = serde_yaml::from_str("{}").unwrap();
722        assert!(
723            !cfg.models.smart.enabled,
724            "Smart background routing is opt-in (capability-gate spec §2)"
725        );
726        assert_eq!(cfg.models.smart.cheap, None); // auto-pick
727        assert_eq!(
728            cfg.models.smart.max_escalations,
729            DEFAULT_SMART_MAX_ESCALATIONS
730        );
731    }
732
733    #[test]
734    fn smart_override_inherits_field_by_field() {
735        let global = SmartConfig {
736            enabled: true,
737            cheap: Some("g".into()),
738            max_escalations: 3,
739        };
740        assert_eq!(global.merged(None), global);
741        assert_eq!(global.merged(Some(&SmartOverride::default())), global);
742        // Overriding one field must not reset the others — the whole point.
743        let only_cheap = SmartOverride {
744            cheap: Some("a".into()),
745            ..Default::default()
746        };
747        let m = global.merged(Some(&only_cheap));
748        assert!(m.enabled, "overriding cheap must not disable Smart");
749        assert_eq!(m.cheap.as_deref(), Some("a"));
750        assert_eq!(m.max_escalations, 3);
751        // An explicit false still beats a global true.
752        let off = SmartOverride {
753            enabled: Some(false),
754            ..Default::default()
755        };
756        assert!(!global.merged(Some(&off)).enabled);
757    }
758
759    #[test]
760    fn routing_override_inherits_field_by_field() {
761        let global = RoutingConfig {
762            enabled: true,
763            cheap: Some("c".into()),
764            frontier: Some("f".into()),
765            threshold_input_tokens: Some(9),
766        };
767        let only_cheap = RoutingOverride {
768            cheap: Some("a".into()),
769            ..Default::default()
770        };
771        let m = global.merged(Some(&only_cheap));
772        assert!(m.enabled, "overriding cheap must not disable routing");
773        assert_eq!(m.cheap.as_deref(), Some("a"));
774        assert_eq!(m.frontier.as_deref(), Some("f"));
775        assert_eq!(m.threshold_input_tokens, Some(9));
776    }
777}