Skip to main content

mur_common/config/
conversations.rs

1use super::*;
2
3// ── Ask config (Phase 2B, Task 18) ───────────────────────────────────────────
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct AskConfig {
7    #[serde(default = "ask_default_k_summary")]
8    pub k_summary: u32,
9    #[serde(default = "ask_default_k_raw")]
10    pub k_raw: u32,
11    #[serde(default = "ask_default_esc")]
12    pub escalation_threshold: f64,
13    #[serde(default = "ask_default_mmr")]
14    pub mmr_threshold: f64,
15    #[serde(default = "ask_default_max_ctx")]
16    pub max_context_tokens: u32,
17    #[serde(default = "ask_default_resp_tok")]
18    pub response_tokens: u32,
19    #[serde(default = "ask_default_timeout")]
20    pub timeout_secs: u32,
21    #[serde(default = "ask_default_min_score")]
22    pub min_score: f64,
23    #[serde(default = "ask_default_continue_history_turns")]
24    pub continue_history_turns: u32,
25    /// Separate, shorter timeout for the rewriter LLM call (Phase 3.3).
26    /// Rewriter output is small (~80 tokens) and falling back to the raw
27    /// question on failure is non-fatal, so we don't want to burn the full
28    /// `timeout_secs` budget waiting on a slow/unreachable Ollama before
29    /// the user sees any response.
30    #[serde(default = "ask_default_rewriter_timeout")]
31    pub rewriter_timeout_secs: u32,
32    #[serde(default = "ask_default_compress_hits_enabled")]
33    pub compress_hits_enabled: bool,
34    #[serde(default = "ask_default_summarize_hits_enabled")]
35    pub summarize_hits_enabled: bool,
36    #[serde(default)]
37    pub summarize_model: Option<String>,
38    /// Per-stage backend override for the answer-generation model.
39    /// None = inherit the smart slot (`config.llm`).
40    #[serde(default)]
41    pub backend: Option<BackendConfig>,
42    /// Per-stage backend override for the query rewriter.
43    /// None = inherit the answer stage's backend (`self.backend`), falling
44    /// through to the smart slot (`config.llm`) only if that is also unset.
45    #[serde(default)]
46    pub rewriter_backend: Option<BackendConfig>,
47}
48
49impl AskConfig {
50    /// Effective backend for answer generation. An explicit per-stage
51    /// override wins; otherwise the stage inherits the smart slot
52    /// (`config.llm`) with this stage's own timeout baked in, so a slow
53    /// backend cannot silently fall back to the factory's 120s default.
54    pub fn effective_backend(&self, llm: &LlmConfig) -> BackendConfig {
55        self.backend.clone().unwrap_or_else(|| BackendConfig {
56            timeout_secs: Some(self.timeout_secs as u64),
57            ..llm.to_backend_config()
58        })
59    }
60
61    /// Effective backend for the query rewriter. An explicit
62    /// `rewriter_backend` override wins outright. Otherwise the rewriter
63    /// follows the answer stage's backend (`self.backend`), and only falls
64    /// through to the smart slot (`llm`) when the answer stage has no
65    /// override either — the rewriter is not an independent pinning point,
66    /// only an independent timeout. Whichever source it resolves from, it
67    /// always keeps its own much tighter `rewriter_timeout_secs` budget:
68    /// the rewriter's output is small and falling back to the raw question
69    /// on timeout is non-fatal.
70    pub fn effective_rewriter_backend(&self, llm: &LlmConfig) -> BackendConfig {
71        self.rewriter_backend
72            .clone()
73            .unwrap_or_else(|| BackendConfig {
74                timeout_secs: Some(self.rewriter_timeout_secs as u64),
75                ..self
76                    .backend
77                    .clone()
78                    .unwrap_or_else(|| llm.to_backend_config())
79            })
80    }
81}
82
83impl Default for AskConfig {
84    fn default() -> Self {
85        Self {
86            k_summary: ask_default_k_summary(),
87            k_raw: ask_default_k_raw(),
88            escalation_threshold: ask_default_esc(),
89            mmr_threshold: ask_default_mmr(),
90            max_context_tokens: ask_default_max_ctx(),
91            response_tokens: ask_default_resp_tok(),
92            timeout_secs: ask_default_timeout(),
93            min_score: ask_default_min_score(),
94            continue_history_turns: ask_default_continue_history_turns(),
95            rewriter_timeout_secs: ask_default_rewriter_timeout(),
96            compress_hits_enabled: ask_default_compress_hits_enabled(),
97            summarize_hits_enabled: ask_default_summarize_hits_enabled(),
98            summarize_model: None,
99            backend: None,
100            rewriter_backend: None,
101        }
102    }
103}
104
105fn ask_default_k_summary() -> u32 {
106    5
107}
108fn ask_default_k_raw() -> u32 {
109    10
110}
111fn ask_default_esc() -> f64 {
112    0.5
113}
114fn ask_default_mmr() -> f64 {
115    0.88
116}
117fn ask_default_max_ctx() -> u32 {
118    6000
119}
120fn ask_default_resp_tok() -> u32 {
121    1024
122}
123fn ask_default_timeout() -> u32 {
124    120
125}
126fn ask_default_min_score() -> f64 {
127    0.35
128}
129fn ask_default_rewriter_timeout() -> u32 {
130    8
131}
132fn ask_default_continue_history_turns() -> u32 {
133    3
134}
135fn ask_default_compress_hits_enabled() -> bool {
136    true
137}
138fn ask_default_summarize_hits_enabled() -> bool {
139    true
140}
141
142// ── Conversations archive config (Task 23) ────────────────────────────────────
143
144/// Phase 1 conversations archive config (Task 23).
145///
146/// Hard defaults: off-by-default (`enabled: false`), 30-day retention,
147/// 5-minute poll interval, all sources enabled, Mem0-style REJECT filters on,
148/// dedup threshold 0.85. Every sub-field is serde-default so a config.yaml
149/// without a `conversations:` section still parses.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct ConversationsConfig {
152    #[serde(default)]
153    pub enabled: bool,
154    #[serde(default = "conv_default_retention_days")]
155    pub retention_days: u32,
156    #[serde(default = "conv_default_poll_interval")]
157    pub poll_interval_secs: u64,
158    #[serde(default)]
159    pub sources: ConversationsSources,
160    #[serde(default)]
161    pub filter: ConversationsFilter,
162    #[serde(default)]
163    pub compact: CompactConfig,
164    #[serde(default)]
165    pub ask: AskConfig,
166    #[serde(default)]
167    pub rollup: RollupConfig,
168}
169
170impl Default for ConversationsConfig {
171    fn default() -> Self {
172        Self {
173            enabled: false,
174            retention_days: conv_default_retention_days(),
175            poll_interval_secs: conv_default_poll_interval(),
176            sources: ConversationsSources::default(),
177            filter: ConversationsFilter::default(),
178            compact: CompactConfig::default(),
179            ask: AskConfig::default(),
180            rollup: RollupConfig::default(),
181        }
182    }
183}
184
185/// Waiting turns per channel conversation before the runtime answers
186/// `CONVERSATION_BUSY` (at-mention design §4).
187pub const DEFAULT_CONVERSATION_MAX_WAITING: usize = 4;
188
189/// `mention:` section of `~/.mur/config.yaml` — `@` mention routing. Read by
190/// the agent runtime at boot; `mur-channel` never reads config.
191#[derive(Debug, Clone, Serialize, Deserialize)]
192#[serde(default)]
193pub struct MentionConfig {
194    /// Waiting turns per conversation before CONVERSATION_BUSY (§4).
195    pub conversation_max_waiting: usize,
196}
197
198impl Default for MentionConfig {
199    fn default() -> Self {
200        Self {
201            conversation_max_waiting: DEFAULT_CONVERSATION_MAX_WAITING,
202        }
203    }
204}
205
206fn conv_default_retention_days() -> u32 {
207    30
208}
209fn conv_default_poll_interval() -> u64 {
210    300
211}
212fn conv_truthy() -> bool {
213    true
214}
215fn conv_default_dedup() -> f64 {
216    0.85
217}
218
219#[derive(Debug, Clone, Serialize, Deserialize)]
220pub struct CompactConfig {
221    #[serde(default = "conv_truthy")]
222    pub enabled_in_daemon: bool,
223    #[serde(default = "compact_default_max_days")]
224    pub max_days_per_run: u32,
225    #[serde(default = "compact_default_max_spans")]
226    pub max_extractive_spans: u32,
227    #[serde(default = "compact_default_max_words")]
228    pub max_abstractive_words: u32,
229    #[serde(default = "compact_default_chunk_tokens")]
230    pub chunk_tokens: u32,
231    #[serde(default = "compact_default_history_retain")]
232    pub history_retain: u32,
233    #[serde(default = "compact_default_cron")]
234    pub daemon_cron: String,
235    /// Per-stage backend override for extractive summarization.
236    /// None = inherit the smart slot (`config.llm`).
237    #[serde(default)]
238    pub extractive_backend: Option<BackendConfig>,
239    /// Per-stage backend override for abstractive summarization.
240    /// None = inherit the smart slot (`config.llm`).
241    #[serde(default)]
242    pub abstractive_backend: Option<BackendConfig>,
243}
244
245impl CompactConfig {
246    /// Effective backend for the extractive stage. Override wins; otherwise
247    /// inherit the smart slot. CompactConfig has no per-stage timeout field,
248    /// so inheritance bakes the same conservative 120s the fabricated Ollama
249    /// config used.
250    pub fn effective_extractive_backend(&self, llm: &LlmConfig) -> BackendConfig {
251        self.extractive_backend
252            .clone()
253            .unwrap_or_else(|| BackendConfig {
254                timeout_secs: Some(120),
255                ..llm.to_backend_config()
256            })
257    }
258
259    /// Effective backend for the abstractive stage. See
260    /// `effective_extractive_backend` for the timeout rationale.
261    pub fn effective_abstractive_backend(&self, llm: &LlmConfig) -> BackendConfig {
262        self.abstractive_backend
263            .clone()
264            .unwrap_or_else(|| BackendConfig {
265                timeout_secs: Some(120),
266                ..llm.to_backend_config()
267            })
268    }
269}
270
271impl Default for CompactConfig {
272    fn default() -> Self {
273        Self {
274            enabled_in_daemon: true,
275            max_days_per_run: compact_default_max_days(),
276            max_extractive_spans: compact_default_max_spans(),
277            max_abstractive_words: compact_default_max_words(),
278            chunk_tokens: compact_default_chunk_tokens(),
279            history_retain: compact_default_history_retain(),
280            daemon_cron: compact_default_cron(),
281            extractive_backend: None,
282            abstractive_backend: None,
283        }
284    }
285}
286
287fn compact_default_max_days() -> u32 {
288    7
289}
290fn compact_default_max_spans() -> u32 {
291    20
292}
293fn compact_default_max_words() -> u32 {
294    400
295}
296fn compact_default_chunk_tokens() -> u32 {
297    6000
298}
299fn compact_default_history_retain() -> u32 {
300    5
301}
302fn compact_default_cron() -> String {
303    "0 0 3 * * * *".into()
304}
305
306// ── Rollup config (Phase 3.2, Task 1) ─────────────────────────────────────────
307
308#[derive(Debug, Clone, Serialize, Deserialize)]
309pub struct RollupConfig {
310    #[serde(default = "rollup_default_enabled")]
311    pub enabled: bool,
312    #[serde(default = "rollup_default_max_weeks")]
313    pub max_weeks_per_run: u32,
314    #[serde(default = "rollup_default_max_months")]
315    pub max_months_per_run: u32,
316    #[serde(default = "rollup_default_max_spans_week")]
317    pub max_extractive_spans_per_week: u32,
318    #[serde(default = "rollup_default_max_words_week")]
319    pub max_abstractive_words_per_week: u32,
320    #[serde(default = "rollup_default_max_spans_month")]
321    pub max_extractive_spans_per_month: u32,
322    #[serde(default = "rollup_default_max_words_month")]
323    pub max_abstractive_words_per_month: u32,
324    #[serde(default = "rollup_default_week_mmr")]
325    pub week_mmr_threshold: f64,
326    #[serde(default = "rollup_default_month_mmr")]
327    pub month_mmr_threshold: f64,
328    /// Per-stage backend override for the extractive stage.
329    /// None = inherit the smart slot (`config.llm`).
330    #[serde(default)]
331    pub extractive_backend: Option<BackendConfig>,
332    /// Per-stage backend override for the abstractive stage.
333    /// None = inherit the smart slot (`config.llm`).
334    #[serde(default)]
335    pub abstractive_backend: Option<BackendConfig>,
336}
337
338impl Default for RollupConfig {
339    fn default() -> Self {
340        Self {
341            enabled: rollup_default_enabled(),
342            max_weeks_per_run: rollup_default_max_weeks(),
343            max_months_per_run: rollup_default_max_months(),
344            max_extractive_spans_per_week: rollup_default_max_spans_week(),
345            max_abstractive_words_per_week: rollup_default_max_words_week(),
346            max_extractive_spans_per_month: rollup_default_max_spans_month(),
347            max_abstractive_words_per_month: rollup_default_max_words_month(),
348            week_mmr_threshold: rollup_default_week_mmr(),
349            month_mmr_threshold: rollup_default_month_mmr(),
350            extractive_backend: None,
351            abstractive_backend: None,
352        }
353    }
354}
355
356impl RollupConfig {
357    /// Effective backend for the extractive stage. Override wins; otherwise
358    /// inherit the smart slot with the same 120s budget the previously
359    /// hardcoded inline config used (`summarize/rollup.rs`).
360    pub fn effective_extractive_backend(&self, llm: &LlmConfig) -> BackendConfig {
361        self.extractive_backend
362            .clone()
363            .unwrap_or_else(|| BackendConfig {
364                timeout_secs: Some(120),
365                ..llm.to_backend_config()
366            })
367    }
368
369    /// Effective backend for the abstractive stage.
370    pub fn effective_abstractive_backend(&self, llm: &LlmConfig) -> BackendConfig {
371        self.abstractive_backend
372            .clone()
373            .unwrap_or_else(|| BackendConfig {
374                timeout_secs: Some(120),
375                ..llm.to_backend_config()
376            })
377    }
378}
379
380fn rollup_default_enabled() -> bool {
381    true
382}
383fn rollup_default_max_weeks() -> u32 {
384    4
385}
386fn rollup_default_max_months() -> u32 {
387    2
388}
389fn rollup_default_max_spans_week() -> u32 {
390    20
391}
392fn rollup_default_max_words_week() -> u32 {
393    500
394}
395fn rollup_default_max_spans_month() -> u32 {
396    20
397}
398fn rollup_default_max_words_month() -> u32 {
399    700
400}
401fn rollup_default_week_mmr() -> f64 {
402    0.85
403}
404fn rollup_default_month_mmr() -> f64 {
405    0.82
406}
407
408#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct ConversationsSources {
410    #[serde(default = "conv_truthy")]
411    pub claude_code: bool,
412    #[serde(default = "conv_truthy")]
413    pub cursor: bool,
414    #[serde(default = "conv_truthy")]
415    pub gemini: bool,
416    #[serde(default)]
417    pub aider: AiderSourceConfig,
418}
419
420impl Default for ConversationsSources {
421    fn default() -> Self {
422        Self {
423            claude_code: true,
424            cursor: true,
425            gemini: true,
426            aider: AiderSourceConfig::default(),
427        }
428    }
429}
430
431#[derive(Debug, Clone, Serialize, Deserialize)]
432pub struct AiderSourceConfig {
433    #[serde(default = "conv_truthy")]
434    pub enabled: bool,
435    #[serde(default)]
436    pub watched_dirs: Vec<String>,
437}
438
439impl Default for AiderSourceConfig {
440    fn default() -> Self {
441        Self {
442            enabled: true,
443            watched_dirs: Vec::new(),
444        }
445    }
446}
447
448#[derive(Debug, Clone, Serialize, Deserialize)]
449pub struct ConversationsFilter {
450    #[serde(default = "conv_default_dedup")]
451    pub dedup_threshold: f64,
452    #[serde(default = "conv_truthy")]
453    pub reject_heartbeat: bool,
454    #[serde(default = "conv_truthy")]
455    pub reject_system_restatement: bool,
456}
457
458impl Default for ConversationsFilter {
459    fn default() -> Self {
460        Self {
461            dedup_threshold: conv_default_dedup(),
462            reject_heartbeat: true,
463            reject_system_restatement: true,
464        }
465    }
466}
467
468#[cfg(test)]
469mod conversations_tests {
470    use super::*;
471
472    #[test]
473    fn conversations_section_defaults() {
474        let c = ConversationsConfig::default();
475        assert!(!c.enabled);
476        assert_eq!(c.retention_days, 30);
477        assert_eq!(c.poll_interval_secs, 300);
478        assert!(c.sources.claude_code);
479        assert!(c.sources.cursor);
480        assert!(c.sources.gemini);
481        assert!(c.sources.aider.enabled);
482        assert!(c.sources.aider.watched_dirs.is_empty());
483        assert_eq!(c.filter.dedup_threshold, 0.85);
484        assert!(c.filter.reject_heartbeat);
485        assert!(c.filter.reject_system_restatement);
486    }
487
488    #[test]
489    fn parse_from_yaml_with_overrides() {
490        let y = r#"
491conversations:
492  enabled: true
493  retention_days: 45
494  poll_interval_secs: 120
495  sources:
496    cursor: false
497    aider:
498      watched_dirs: ["~/Projects/a", "~/Projects/b"]
499  filter:
500    dedup_threshold: 0.9
501"#;
502        let v: serde_yaml::Value = serde_yaml::from_str(y).unwrap();
503        let conv: ConversationsConfig = serde_yaml::from_value(v["conversations"].clone()).unwrap();
504        assert!(conv.enabled);
505        assert_eq!(conv.retention_days, 45);
506        assert_eq!(conv.poll_interval_secs, 120);
507        assert!(conv.sources.claude_code); // defaulted true
508        assert!(!conv.sources.cursor); // override
509        assert!(conv.sources.gemini); // defaulted true
510        assert_eq!(conv.sources.aider.watched_dirs.len(), 2);
511        assert_eq!(conv.filter.dedup_threshold, 0.9);
512        assert!(conv.filter.reject_heartbeat); // defaulted true
513    }
514
515    #[test]
516    fn missing_conversations_section_is_fine() {
517        let y = r#"
518# No conversations section at all
519foo: bar
520"#;
521        let v: serde_yaml::Value = serde_yaml::from_str(y).unwrap();
522        // Default when absent
523        let conv: ConversationsConfig = v
524            .get("conversations")
525            .cloned()
526            .map(|x| serde_yaml::from_value(x).unwrap_or_default())
527            .unwrap_or_default();
528        assert_eq!(conv.retention_days, 30);
529    }
530
531    #[test]
532    fn compact_config_defaults() {
533        let c = CompactConfig::default();
534        assert!(c.enabled_in_daemon);
535        assert_eq!(c.max_days_per_run, 7);
536        assert_eq!(c.max_extractive_spans, 20);
537        assert_eq!(c.chunk_tokens, 6000);
538        assert_eq!(c.history_retain, 5);
539        assert_eq!(c.daemon_cron, "0 0 3 * * * *");
540    }
541
542    #[test]
543    fn compact_parses_partial_overrides() {
544        let y = r#"
545conversations:
546  compact:
547    max_days_per_run: 3
548    extractive_backend:
549      provider: anthropic
550      model: claude-haiku-4-5
551"#;
552        let v: serde_yaml::Value = serde_yaml::from_str(y).unwrap();
553        let conv: ConversationsConfig = serde_yaml::from_value(v["conversations"].clone()).unwrap();
554        assert_eq!(conv.compact.max_days_per_run, 3);
555        assert_eq!(
556            conv.compact.extractive_backend.as_ref().unwrap().model,
557            "claude-haiku-4-5"
558        );
559        assert!(conv.compact.enabled_in_daemon); // default preserved
560        assert!(conv.compact.abstractive_backend.is_none()); // default preserved
561    }
562
563    #[test]
564    fn ask_config_defaults() {
565        let c = AskConfig::default();
566        assert_eq!(c.k_raw, 10);
567        assert_eq!(c.escalation_threshold, 0.5);
568        assert_eq!(c.mmr_threshold, 0.88);
569        assert_eq!(c.max_context_tokens, 6000);
570        assert_eq!(c.response_tokens, 1024);
571        assert_eq!(c.timeout_secs, 120);
572        assert_eq!(c.min_score, 0.35);
573    }
574
575    #[test]
576    fn ask_config_mmr_threshold_default_is_cosine_scaled() {
577        // Phase 3.1: default shifts from 0.85 (word-Jaccard) to 0.88 (cosine).
578        let c = AskConfig::default();
579        assert!(
580            (c.mmr_threshold - 0.88).abs() < 1e-9,
581            "expected 0.88, got {}",
582            c.mmr_threshold
583        );
584    }
585
586    #[test]
587    fn rollup_config_defaults() {
588        let c = RollupConfig::default();
589        assert!(c.enabled);
590        assert_eq!(c.max_weeks_per_run, 4);
591        assert_eq!(c.max_months_per_run, 2);
592        assert_eq!(c.max_extractive_spans_per_week, 20);
593        assert_eq!(c.max_abstractive_words_per_week, 500);
594        assert_eq!(c.max_extractive_spans_per_month, 20);
595        assert_eq!(c.max_abstractive_words_per_month, 700);
596        assert!((c.week_mmr_threshold - 0.85).abs() < 1e-9);
597        assert!((c.month_mmr_threshold - 0.82).abs() < 1e-9);
598    }
599
600    #[test]
601    fn rollup_config_plumbed_into_conversations_config() {
602        let c = ConversationsConfig::default();
603        assert!(c.rollup.enabled);
604    }
605
606    #[test]
607    fn ask_config_default_continue_history_turns_is_3() {
608        let c = AskConfig::default();
609        assert_eq!(c.continue_history_turns, 3);
610    }
611
612    #[test]
613    fn ask_config_default_compress_hits_enabled_is_true() {
614        let c = AskConfig::default();
615        assert!(c.compress_hits_enabled);
616    }
617
618    #[test]
619    fn ask_config_default_summarize_hits_enabled_is_true() {
620        let c = AskConfig::default();
621        assert!(c.summarize_hits_enabled);
622    }
623
624    #[test]
625    fn ask_config_default_summarize_model_is_none() {
626        let c = AskConfig::default();
627        assert!(c.summarize_model.is_none());
628    }
629
630    #[test]
631    fn ask_config_yaml_roundtrip_preserves_summarize_fields() {
632        let y = r#"
633conversations:
634  ask:
635    summarize_hits_enabled: false
636    summarize_model: qwen3:4b
637"#;
638        let v: serde_yaml::Value = serde_yaml::from_str(y).unwrap();
639        let conv: ConversationsConfig = serde_yaml::from_value(v["conversations"].clone()).unwrap();
640        assert!(!conv.ask.summarize_hits_enabled);
641        assert_eq!(conv.ask.summarize_model.as_deref(), Some("qwen3:4b"));
642    }
643
644    #[test]
645    fn ask_config_yaml_without_summarize_fields_uses_defaults() {
646        // Phase 3.5 must be additive: an existing config.yaml with NO
647        // summarize_* keys must still parse and default to enabled=true,
648        // model=None.
649        let y = r#"
650conversations:
651  ask:
652    min_score: 0.4
653"#;
654        let v: serde_yaml::Value = serde_yaml::from_str(y).unwrap();
655        let conv: ConversationsConfig = serde_yaml::from_value(v["conversations"].clone()).unwrap();
656        assert!(conv.ask.summarize_hits_enabled);
657        assert!(conv.ask.summarize_model.is_none());
658    }
659}