recall-echo 3.13.0

Persistent memory system with knowledge graph — for any LLM tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use std::fmt;
use std::fs;
use std::path::Path;

use serde::{Deserialize, Serialize};

/// Evidence weights per provenance class, re-exported from the confidence
/// model that owns them: `[graph.provenance]` is only their config surface.
pub use crate::graph::confidence::ProvenanceWeights;

const DEFAULT_MAX_ENTRIES: usize = 5;
const DEFAULT_IDLE_TIMEOUT_SECS: u64 = 3600;
const CONFIG_FILE: &str = ".recall-echo.toml";

// ── Provider enum ────────────────────────────────────────────────────────

/// LLM provider for entity extraction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Provider {
    Anthropic,
    Openai,
    ClaudeCode,
}

impl Provider {
    #[must_use]
    pub fn default_model(&self) -> &'static str {
        match self {
            Provider::Anthropic => "claude-haiku-4-5-20251001",
            Provider::Openai => "llama3.2",
            Provider::ClaudeCode => "",
        }
    }

    #[must_use]
    pub fn default_api_base(&self) -> &'static str {
        match self {
            Provider::Anthropic => "https://api.anthropic.com/v1/messages",
            Provider::Openai => "http://localhost:11434/v1",
            Provider::ClaudeCode => "",
        }
    }

    pub fn from_str_loose(s: &str) -> Result<Self, crate::error::RecallError> {
        match s.to_lowercase().as_str() {
            "anthropic" | "claude" => Ok(Provider::Anthropic),
            "openai" | "ollama" => Ok(Provider::Openai),
            "claude-code" | "claudecode" => Ok(Provider::ClaudeCode),
            other => Err(crate::error::RecallError::Config(format!(
                "unknown provider: {other} (use 'anthropic', 'ollama', or 'claude-code')"
            ))),
        }
    }
}

impl fmt::Display for Provider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Provider::Anthropic => write!(f, "anthropic"),
            Provider::Openai => write!(f, "openai"),
            Provider::ClaudeCode => write!(f, "claude-code"),
        }
    }
}

// ── Config structs ───────────────────────────────────────────────────────

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub ephemeral: EphemeralConfig,
    #[serde(default)]
    pub llm: LlmSection,
    #[serde(default)]
    pub pipeline: Option<PipelineSection>,
    #[serde(default)]
    pub graph: Option<GraphSection>,
    #[serde(default)]
    pub serve: ServeSection,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct EphemeralConfig {
    #[serde(default = "default_max_entries")]
    pub max_entries: usize,
}

impl Default for EphemeralConfig {
    fn default() -> Self {
        Self {
            max_entries: DEFAULT_MAX_ENTRIES,
        }
    }
}

fn default_max_entries() -> usize {
    DEFAULT_MAX_ENTRIES
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LlmSection {
    #[serde(default = "default_provider")]
    pub provider: Provider,
    #[serde(default)]
    pub model: String,
    #[serde(default)]
    pub api_base: String,
}

impl Default for LlmSection {
    fn default() -> Self {
        Self {
            provider: Provider::Anthropic,
            model: String::new(),
            api_base: String::new(),
        }
    }
}

impl LlmSection {
    /// Resolved model — uses configured value or provider default.
    #[must_use]
    pub fn resolved_model(&self) -> &str {
        if self.model.is_empty() {
            self.provider.default_model()
        } else {
            &self.model
        }
    }

    /// Resolved API base — uses configured value or provider default.
    #[must_use]
    pub fn resolved_api_base(&self) -> &str {
        if self.api_base.is_empty() {
            self.provider.default_api_base()
        } else {
            &self.api_base
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineSection {
    /// Directory containing pipeline documents (LEARNING.md, THOUGHTS.md, etc.)
    #[serde(default)]
    pub docs_dir: Option<String>,
    /// Auto-sync pipeline on archive (default: false)
    #[serde(default)]
    pub auto_sync: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphSection {
    /// Connection mode: "embedded" or "server"
    #[serde(default = "default_graph_mode")]
    pub mode: String,
    /// SurrealDB server URL (server mode only)
    #[serde(default = "default_graph_url")]
    pub url: String,
    /// SurrealDB namespace
    #[serde(default = "default_graph_namespace")]
    pub namespace: String,
    /// SurrealDB database name (typically the entity name)
    #[serde(default)]
    pub database: String,
    /// SurrealDB username (typically the entity name)
    #[serde(default)]
    pub username: String,
    /// Path to file containing the database password
    #[serde(default)]
    pub password_file: String,
    /// Scoring weights for utility-weighted semantic search.
    ///
    /// Maps to the `[graph.scoring]` section of `.recall-echo.toml`. When
    /// absent, defaults preserve the original hard-coded weights
    /// (0.45 / 0.30 / 0.25). See `GraphScoringConfig` for details.
    #[serde(default)]
    pub scoring: GraphScoringConfig,
    /// Evidence weights per provenance class.
    ///
    /// Maps to the `[graph.provenance]` section of `.recall-echo.toml`. When
    /// absent, defaults are 1.0 external / 0.8 user / 0.05 self. See
    /// [`ProvenanceWeights`] for details.
    #[serde(default)]
    pub provenance: ProvenanceWeights,
}

impl Default for GraphSection {
    fn default() -> Self {
        Self {
            mode: default_graph_mode(),
            url: default_graph_url(),
            namespace: default_graph_namespace(),
            database: String::new(),
            username: String::new(),
            password_file: String::new(),
            scoring: GraphScoringConfig::default(),
            provenance: ProvenanceWeights::default(),
        }
    }
}

/// Settings for the `recall-echo serve` graph daemon.
///
/// Maps to the `[serve]` section of `.recall-echo.toml`. The daemon is started
/// transparently by graph commands and hooks when `[graph] mode = "embedded"`
/// (the default); these keys only tune where it listens and how long it lives.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ServeSection {
    /// Override the unix socket path. Defaults to
    /// `$XDG_RUNTIME_DIR/recall-echo/<hash of memory dir>.sock`.
    pub socket_path: Option<String>,
    /// Seconds of inactivity before the daemon shuts itself down.
    /// `0` disables idle shutdown. Default `3600`.
    pub idle_timeout_secs: u64,
}

impl Default for ServeSection {
    fn default() -> Self {
        Self {
            socket_path: None,
            idle_timeout_secs: DEFAULT_IDLE_TIMEOUT_SECS,
        }
    }
}

/// Scoring weights for utility-weighted semantic search.
///
/// The final score for a retrieved entity is computed as a linear combination
/// of three signals:
///
/// ```text
/// score = weight_semantic * similarity
///       + weight_hotness  * hotness
///       + weight_utility  * utility_score
/// ```
///
/// Defaults (`0.45 / 0.30 / 0.25`) match the original hard-coded values, so
/// omitting the `[graph.scoring]` section from `.recall-echo.toml` produces
/// identical behavior to pre-v3.9.0 recall-echo.
///
/// Weights are not constrained to sum to 1.0 — the scoring function does not
/// normalize. Callers that change these should calibrate against their own
/// retrieval outcomes; see `utility-feedback-loop-spec.md` in pulse-null.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GraphScoringConfig {
    /// Weight applied to cosine similarity. Default `0.45`.
    pub weight_semantic: f64,
    /// Weight applied to the recency/access hotness signal. Default `0.30`.
    pub weight_hotness: f64,
    /// Weight applied to the utility score (outcome-feedback EMA). Default `0.25`.
    pub weight_utility: f64,
}

impl Default for GraphScoringConfig {
    fn default() -> Self {
        Self {
            weight_semantic: 0.45,
            weight_hotness: 0.30,
            weight_utility: 0.25,
        }
    }
}

fn default_graph_mode() -> String {
    "embedded".to_string()
}

fn default_graph_url() -> String {
    "ws://localhost:8787".to_string()
}

fn default_graph_namespace() -> String {
    "nullarc".to_string()
}

fn default_provider() -> Provider {
    Provider::Anthropic
}

// ── Load / Save ──────────────────────────────────────────────────────────

/// Config file path for a given base directory.
#[must_use]
pub fn config_path(base: &Path) -> std::path::PathBuf {
    base.join(CONFIG_FILE)
}

/// Load config from .recall-echo.toml in the given directory.
/// Returns defaults if file doesn't exist or is malformed.
#[must_use]
pub fn load_from_dir(dir: &Path) -> Config {
    load(dir)
}

/// Load config from .recall-echo.toml in the base dir.
/// Returns defaults if file doesn't exist or is malformed.
#[must_use]
pub fn load(base: &Path) -> Config {
    let path = config_path(base);
    if !path.exists() {
        return Config::default();
    }

    let content = match fs::read_to_string(&path) {
        Ok(c) => c,
        Err(_) => return Config::default(),
    };

    match toml::from_str(&content) {
        Ok(cfg) => validate(cfg),
        Err(_) => Config::default(),
    }
}

/// Save config to .recall-echo.toml in the base dir.
pub fn save(base: &Path, config: &Config) -> Result<(), crate::error::RecallError> {
    let path = config_path(base);
    let content = toml::to_string_pretty(config)?;
    fs::write(&path, content)?;
    Ok(())
}

/// Returns true if .recall-echo.toml exists in the directory.
#[must_use]
pub fn exists(base: &Path) -> bool {
    config_path(base).exists()
}

fn validate(mut cfg: Config) -> Config {
    if !(1..=50).contains(&cfg.ephemeral.max_entries) {
        cfg.ephemeral.max_entries = DEFAULT_MAX_ENTRIES;
    }
    cfg
}

// ── Config mutation helpers ──────────────────────────────────────────────

impl Config {
    /// Set a dotted config key (e.g. "llm.provider", "ephemeral.max_entries").
    pub fn set_key(&mut self, key: &str, value: &str) -> Result<(), crate::error::RecallError> {
        use crate::error::RecallError;
        match key {
            "llm.provider" | "provider" => {
                let provider = Provider::from_str_loose(value)?;
                // When switching provider, reset model and api_base to defaults
                self.llm.model = String::new();
                self.llm.api_base = String::new();
                self.llm.provider = provider;
                Ok(())
            }
            "llm.model" | "model" => {
                self.llm.model = value.to_string();
                Ok(())
            }
            "llm.api_base" | "api_base" => {
                self.llm.api_base = value.to_string();
                Ok(())
            }
            "ephemeral.max_entries" => {
                let n: usize = value
                    .parse()
                    .map_err(|_| RecallError::Config(format!("invalid number: {value}")))?;
                if !(1..=50).contains(&n) {
                    return Err(RecallError::Config(
                        "max_entries must be between 1 and 50".into(),
                    ));
                }
                self.ephemeral.max_entries = n;
                Ok(())
            }
            "pipeline.docs_dir" => {
                let section = self.pipeline.get_or_insert(PipelineSection {
                    docs_dir: None,
                    auto_sync: None,
                });
                section.docs_dir = Some(value.to_string());
                Ok(())
            }
            "pipeline.auto_sync" => {
                let b: bool = value
                    .parse()
                    .map_err(|_| RecallError::Config(format!("invalid boolean: {value}")))?;
                let section = self.pipeline.get_or_insert(PipelineSection {
                    docs_dir: None,
                    auto_sync: None,
                });
                section.auto_sync = Some(b);
                Ok(())
            }
            "serve.idle_timeout_secs" => {
                let secs: u64 = value
                    .parse()
                    .map_err(|_| RecallError::Config(format!("invalid number: {value}")))?;
                self.serve.idle_timeout_secs = secs;
                Ok(())
            }
            "serve.socket_path" => {
                self.serve.socket_path = if value.trim().is_empty() {
                    None
                } else {
                    Some(value.to_string())
                };
                Ok(())
            }
            "graph.provenance.weight_external" => {
                self.graph_section().provenance.weight_external = parse_weight(value)?;
                Ok(())
            }
            "graph.provenance.weight_user" => {
                self.graph_section().provenance.weight_user = parse_weight(value)?;
                Ok(())
            }
            "graph.provenance.weight_self" => {
                self.graph_section().provenance.weight_self = parse_weight(value)?;
                Ok(())
            }
            other => Err(RecallError::Config(format!("unknown config key: {other}"))),
        }
    }

    /// The `[graph]` section, created at its defaults if the config has none.
    fn graph_section(&mut self) -> &mut GraphSection {
        self.graph.get_or_insert_with(GraphSection::default)
    }
}

/// Parse an evidence weight: a finite, non-negative number.
///
/// Zero is allowed — it is how a class is switched off entirely.
fn parse_weight(value: &str) -> Result<f64, crate::error::RecallError> {
    use crate::error::RecallError;
    let weight: f64 = value
        .parse()
        .map_err(|_| RecallError::Config(format!("invalid number: {value}")))?;
    if !weight.is_finite() || weight < 0.0 {
        return Err(RecallError::Config(format!(
            "evidence weight must be finite and non-negative, got {value}"
        )));
    }
    Ok(weight)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_config() {
        let cfg = Config::default();
        assert_eq!(cfg.ephemeral.max_entries, 5);
        assert_eq!(cfg.llm.provider, Provider::Anthropic);
        assert!(cfg.llm.model.is_empty());
    }

    #[test]
    fn parse_ephemeral_only() {
        let cfg: Config = toml::from_str("[ephemeral]\nmax_entries = 10\n").unwrap();
        assert_eq!(cfg.ephemeral.max_entries, 10);
        assert_eq!(cfg.llm.provider, Provider::Anthropic);
    }

    #[test]
    fn graph_mode_defaults_to_embedded() {
        let cfg: Config = toml::from_str("[graph]\n").unwrap();
        assert_eq!(cfg.graph.unwrap().mode, "embedded");
    }

    #[test]
    fn graph_mode_parses_server() {
        let cfg: Config =
            toml::from_str("[graph]\nmode = \"server\"\nurl = \"ws://db.local:8787\"\n").unwrap();
        let g = cfg.graph.unwrap();
        assert_eq!(g.mode, "server");
        assert_eq!(g.url, "ws://db.local:8787");
    }

    #[test]
    fn serve_defaults_when_section_absent() {
        let cfg: Config = toml::from_str("[ephemeral]\nmax_entries = 3\n").unwrap();
        assert_eq!(cfg.serve.idle_timeout_secs, DEFAULT_IDLE_TIMEOUT_SECS);
        assert!(cfg.serve.socket_path.is_none());
    }

    #[test]
    fn serve_section_parses_overrides() {
        let cfg: Config = toml::from_str(
            "[serve]\nsocket_path = \"/run/re/graph.sock\"\nidle_timeout_secs = 60\n",
        )
        .unwrap();
        assert_eq!(cfg.serve.idle_timeout_secs, 60);
        assert_eq!(cfg.serve.socket_path.as_deref(), Some("/run/re/graph.sock"));
    }

    #[test]
    fn set_key_serve_idle_timeout() {
        let mut cfg = Config::default();
        cfg.set_key("serve.idle_timeout_secs", "120").unwrap();
        assert_eq!(cfg.serve.idle_timeout_secs, 120);
        assert!(cfg.set_key("serve.idle_timeout_secs", "soon").is_err());
    }

    #[test]
    fn parse_llm_section() {
        let cfg: Config = toml::from_str(
            "[llm]\nprovider = \"openai\"\nmodel = \"llama3.1\"\napi_base = \"http://myhost:11434/v1\"\n",
        )
        .unwrap();
        assert_eq!(cfg.llm.provider, Provider::Openai);
        assert_eq!(cfg.llm.model, "llama3.1");
        assert_eq!(cfg.llm.api_base, "http://myhost:11434/v1");
    }

    #[test]
    fn parse_claude_code_provider() {
        let cfg: Config = toml::from_str("[llm]\nprovider = \"claude-code\"\n").unwrap();
        assert_eq!(cfg.llm.provider, Provider::ClaudeCode);
    }

    #[test]
    fn resolved_defaults() {
        let llm = LlmSection::default();
        assert_eq!(llm.resolved_model(), "claude-haiku-4-5-20251001");
        assert_eq!(
            llm.resolved_api_base(),
            "https://api.anthropic.com/v1/messages"
        );
    }

    #[test]
    fn resolved_custom_overrides_default() {
        let llm = LlmSection {
            provider: Provider::Openai,
            model: "mistral-7b".into(),
            api_base: String::new(),
        };
        assert_eq!(llm.resolved_model(), "mistral-7b");
        assert_eq!(llm.resolved_api_base(), "http://localhost:11434/v1");
    }

    #[test]
    fn round_trip_toml() {
        let cfg = Config {
            ephemeral: EphemeralConfig { max_entries: 3 },
            llm: LlmSection {
                provider: Provider::Openai,
                model: "llama3.2".into(),
                api_base: "http://localhost:11434/v1".into(),
            },
            pipeline: None,
            graph: None,
            serve: ServeSection::default(),
        };
        let s = toml::to_string_pretty(&cfg).unwrap();
        let parsed: Config = toml::from_str(&s).unwrap();
        assert_eq!(parsed.ephemeral.max_entries, 3);
        assert_eq!(parsed.llm.provider, Provider::Openai);
        assert_eq!(parsed.llm.model, "llama3.2");
    }

    #[test]
    fn set_key_provider() {
        let mut cfg = Config::default();
        cfg.set_key("llm.provider", "ollama").unwrap();
        assert_eq!(cfg.llm.provider, Provider::Openai);
        assert!(cfg.llm.model.is_empty());
    }

    #[test]
    fn set_key_model() {
        let mut cfg = Config::default();
        cfg.set_key("llm.model", "claude-sonnet-4-6").unwrap();
        assert_eq!(cfg.llm.model, "claude-sonnet-4-6");
    }

    #[test]
    fn set_key_unknown_fails() {
        let mut cfg = Config::default();
        assert!(cfg.set_key("nonexistent.key", "value").is_err());
    }

    #[test]
    fn provider_from_str_loose() {
        assert_eq!(
            Provider::from_str_loose("ollama").unwrap(),
            Provider::Openai
        );
        assert_eq!(
            Provider::from_str_loose("claude").unwrap(),
            Provider::Anthropic
        );
        assert_eq!(
            Provider::from_str_loose("claude-code").unwrap(),
            Provider::ClaudeCode
        );
        assert!(Provider::from_str_loose("unknown").is_err());
    }

    #[test]
    fn save_and_load() {
        let tmp = tempfile::tempdir().unwrap();
        let cfg = Config {
            ephemeral: EphemeralConfig { max_entries: 7 },
            llm: LlmSection {
                provider: Provider::ClaudeCode,
                model: String::new(),
                api_base: String::new(),
            },
            pipeline: None,
            graph: None,
            serve: ServeSection::default(),
        };
        save(tmp.path(), &cfg).unwrap();
        let loaded = load(tmp.path());
        assert_eq!(loaded.ephemeral.max_entries, 7);
        assert_eq!(loaded.llm.provider, Provider::ClaudeCode);
    }

    #[test]
    fn load_nonexistent_file() {
        let tmp = tempfile::tempdir().unwrap();
        let cfg = load(tmp.path());
        assert_eq!(cfg.ephemeral.max_entries, 5);
    }

    #[test]
    fn validate_out_of_range() {
        let cfg = validate(Config {
            ephemeral: EphemeralConfig { max_entries: 100 },
            llm: LlmSection::default(),
            pipeline: None,
            graph: None,
            serve: ServeSection::default(),
        });
        assert_eq!(cfg.ephemeral.max_entries, 5);
    }

    #[test]
    fn graph_scoring_defaults_match_legacy_hardcodes() {
        let scoring = GraphScoringConfig::default();
        assert!((scoring.weight_semantic - 0.45).abs() < f64::EPSILON);
        assert!((scoring.weight_hotness - 0.30).abs() < f64::EPSILON);
        assert!((scoring.weight_utility - 0.25).abs() < f64::EPSILON);
    }

    #[test]
    fn graph_scoring_partial_toml_fills_defaults() {
        let scoring: GraphScoringConfig =
            toml::from_str("weight_utility = 0.5\n").expect("parse partial scoring");
        assert!((scoring.weight_semantic - 0.45).abs() < f64::EPSILON);
        assert!((scoring.weight_hotness - 0.30).abs() < f64::EPSILON);
        assert!((scoring.weight_utility - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn graph_scoring_empty_section_yields_defaults() {
        let section: GraphSection = toml::from_str("").expect("parse empty graph section");
        let defaults = GraphScoringConfig::default();
        assert!((section.scoring.weight_semantic - defaults.weight_semantic).abs() < f64::EPSILON);
        assert!((section.scoring.weight_hotness - defaults.weight_hotness).abs() < f64::EPSILON);
        assert!((section.scoring.weight_utility - defaults.weight_utility).abs() < f64::EPSILON);
    }

    #[test]
    fn graph_provenance_defaults_when_section_absent() {
        let section: GraphSection = toml::from_str("mode = \"embedded\"\n").expect("parse section");
        let defaults = ProvenanceWeights::default();
        assert_eq!(section.provenance, defaults);
        assert!((defaults.weight_external - 1.0).abs() < f64::EPSILON);
        assert!((defaults.weight_user - 0.8).abs() < f64::EPSILON);
        assert!((defaults.weight_self - 0.05).abs() < f64::EPSILON);
    }

    #[test]
    fn graph_provenance_partial_toml_fills_defaults() {
        let cfg: Config =
            toml::from_str("[graph]\n\n[graph.provenance]\nweight_self = 0.5\n").expect("parse");
        let provenance = cfg.graph.expect("graph section present").provenance;
        assert!((provenance.weight_self - 0.5).abs() < f64::EPSILON);
        assert!((provenance.weight_external - 1.0).abs() < f64::EPSILON);
        assert!((provenance.weight_user - 0.8).abs() < f64::EPSILON);
    }

    #[test]
    fn set_key_provenance_weights() {
        let mut cfg = Config::default();
        cfg.set_key("graph.provenance.weight_self", "0.2").unwrap();
        cfg.set_key("graph.provenance.weight_user", "0").unwrap();
        cfg.set_key("graph.provenance.weight_external", "1.5")
            .unwrap();

        let provenance = cfg
            .graph
            .as_ref()
            .expect("graph section created")
            .provenance;
        assert!((provenance.weight_self - 0.2).abs() < f64::EPSILON);
        assert!(provenance.weight_user.abs() < f64::EPSILON);
        assert!((provenance.weight_external - 1.5).abs() < f64::EPSILON);

        assert!(cfg.set_key("graph.provenance.weight_self", "-1").is_err());
        assert!(cfg.set_key("graph.provenance.weight_self", "lots").is_err());
    }

    #[test]
    fn provenance_weights_round_trip_through_toml() {
        let mut cfg = Config::default();
        cfg.set_key("graph.provenance.weight_self", "0.05").unwrap();
        let rendered = toml::to_string_pretty(&cfg).expect("render");
        let parsed: Config = toml::from_str(&rendered).expect("reparse");
        assert_eq!(
            parsed.graph.expect("graph section survives").provenance,
            ProvenanceWeights::default()
        );
    }

    #[test]
    fn graph_scoring_nested_under_graph() {
        let cfg: Config = toml::from_str(
            "[graph]\nmode = \"embedded\"\n\n[graph.scoring]\nweight_utility = 0.5\n",
        )
        .expect("parse nested scoring");
        let scoring = cfg.graph.expect("graph section present").scoring;
        assert!((scoring.weight_semantic - 0.45).abs() < f64::EPSILON);
        assert!((scoring.weight_hotness - 0.30).abs() < f64::EPSILON);
        assert!((scoring.weight_utility - 0.5).abs() < f64::EPSILON);
    }
}