solo-storage 0.8.0

Solo: SQLite + SQLCipher persistence layer
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
// SPDX-License-Identifier: Apache-2.0

//! `solo.config.toml` reader/writer.
//!
//! The config file lives alongside `solo.db` and stores everything Solo needs
//! to re-open the database on startup but does NOT need to keep secret. The
//! Argon2 salt is the load-bearing field — without it, the same passphrase
//! produces a different key, so the SQLCipher database becomes unreadable.
//!
//! Layout (TOML):
//! ```toml
//! schema_version = 1
//! salt_hex       = "0123456789abcdef0123456789abcdef"   # 16 bytes -> 32 hex
//!
//! [embedder]
//! name    = "ollama:nomic-embed-text"   # or "stub" for offline dev
//! version = "v1"                        # bump on any vector-shifting change
//! dim     = 768                         # probed at `solo init` for Ollama
//! dtype   = "f32"
//! ```
//!
//! Why TOML: human-readable for debugging + recovery. The whole file is small;
//! we don't need a more compact format.

use serde::{Deserialize, Serialize};
use solo_core::{Error, Result};
use std::path::Path;

use crate::key_material::SALT_LEN;

/// Current config schema version. Bump on any incompatible field change.
pub const CONFIG_SCHEMA_VERSION: u32 = 1;

/// Auth-mode config persisted under `[auth]` in `solo.config.toml`
/// (v0.8.0 P3). Lives in `solo-storage` rather than `solo-api` because
/// `SoloConfig` is the canonical owner of all on-disk config blocks;
/// `solo-api::auth::AuthConfig` mirrors this shape and converts at the
/// transport boundary.
///
/// Two modes:
///   * `bearer` — `[auth] mode = "bearer", token = "…"`
///   * `oidc`   — `[auth] mode = "oidc", discovery_url = "…", audience = "…"`
///                 (optional `tenant_claim_name`, default `solo_tenant`)
///
/// Backward compatibility: when `[auth]` is absent, `solo http-serve`
/// continues to honor `--bearer-token-file` (v0.7.x behavior). Operators
/// migrate to config-driven auth by writing an `[auth]` block; the flag
/// stays as a runtime override for ad-hoc deployments.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "mode", rename_all = "snake_case")]
pub enum AuthSettings {
    Bearer {
        token: String,
    },
    Oidc {
        discovery_url: String,
        audience: String,
        #[serde(default = "default_tenant_claim_name")]
        tenant_claim_name: String,
    },
}

fn default_tenant_claim_name() -> String {
    "solo_tenant".to_string()
}

/// Audit log settings persisted under `[audit]` in `solo.config.toml`
/// (v0.8.0 P4).
///
/// `retention_days = None` (omitted block, or block without the field)
/// = keep audit rows forever. This is the default — compliance use cases
/// often demand unbounded retention, and Solo treats audit rows as cheap
/// (~80 bytes/row uncompressed).
///
/// `purge_interval_secs = None` = no background sweep. Operators who set
/// `retention_days` but omit `purge_interval_secs` can still purge
/// manually via `solo audit purge`. When `Some(N)`, `TenantHandle::open`
/// spawns a per-tenant tokio task that calls `purge_older_than` every
/// `N` seconds.
///
/// Backward compatible: pre-v0.8.0-P4 configs that omit the block
/// deserialize as `None` (default = keep forever, no background sweep).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct AuditSettings {
    /// Retain audit rows for this many days. `None` = forever.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retention_days: Option<u32>,
    /// Run a background sweep every `purge_interval_secs` seconds in
    /// every cached `TenantHandle`. `None` (the default) = no background
    /// sweep. Honored only when `retention_days` is also set; without
    /// a retention bound a sweep would have nothing to delete.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub purge_interval_secs: Option<u64>,
}

/// PII redaction settings persisted under `[redaction]` in `solo.config.toml`
/// (v0.8.0 P5).
///
/// Default = `enabled = false` (opt-in per the locked v0.8.0 design).
/// With `enabled = true` the writer-actor runs every built-in detector
/// (`email`, `ssn`, `us_phone`, `credit_card`, `aws_access_key`,
/// `github_pat`) over `episodes.content` and `document_chunks.content`
/// before INSERT. Operators disable specific defaults via
/// `exclude_builtin = ["email", ...]`, and add their own under
/// `[[redaction.custom]]` blocks.
///
/// Per-tenant redaction overrides are deliberately NOT supported in
/// v0.8.0 P5 — the redaction block in `solo.config.toml` is the single
/// source of truth. Per-tenant config layering is a v0.8.1+ concern.
///
/// Backward compatible: pre-v0.8.0-P5 configs that omit the block
/// deserialize with `RedactionConfig::default()` (everything off).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RedactionConfig {
    /// Master switch. Default `false` (opt-in).
    #[serde(default)]
    pub enabled: bool,
    /// Names of built-in patterns to disable. Defaults to empty (all
    /// builtins active when `enabled = true`).
    #[serde(default)]
    pub exclude_builtin: Vec<String>,
    /// Operator-supplied custom patterns. Compiled at
    /// `RedactionRegistry::from_config` time; an invalid regex here
    /// surfaces as `TenantHandle::open` error.
    #[serde(default)]
    pub custom: Vec<CustomRedactionPattern>,
}

/// One operator-supplied custom redaction pattern from a
/// `[[redaction.custom]]` block.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CustomRedactionPattern {
    /// Stable identifier — used as the sentinel suffix
    /// (`[REDACTED:<name>]`) when `replacement` is omitted, and as the
    /// audit-row count key. Must be non-empty.
    pub name: String,
    /// Rust regex syntax. Compiled at registry build time.
    pub regex: String,
    /// Optional replacement string. Defaults to `[REDACTED:<name>]`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replacement: Option<String>,
}

/// Top-level config struct, serialized as TOML to `solo.config.toml`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SoloConfig {
    /// Version of the config schema itself (NOT the database schema). Bumping
    /// this lets future Solo versions migrate old config files in-place.
    pub schema_version: u32,
    /// 32-character lowercase hex string of the 16-byte Argon2 salt.
    pub salt_hex: String,
    /// Embedder identity: name, version, dim, dtype. The database holds
    /// embeddings tied to a specific `(name, version)`; if those change, the
    /// daemon refuses to start until `solo reembed` rebuilds them.
    pub embedder: EmbedderConfig,
    /// User-identity settings for the read-path. Default empty; backward-
    /// compatible with configs that don't declare an `[identity]` block.
    /// Today this carries `user_aliases` so `facts_about` can resolve a
    /// queried alias against historical triples whose `subject_id` was
    /// normalised to the canonical `"user"`. v0.5.0 Priority 1, sub-step
    /// 1C — see `docs/dev-log/0071-v0.5.x-roadmap.md`.
    #[serde(default)]
    pub identity: IdentityConfig,
    /// Document parser + chunker settings for the v0.7.0 RAG memory path.
    /// Default values match the v0.7.0 plan (target 500 tokens, 50-token
    /// overlap, the same allow-list as `document::parse::ALLOWED`).
    /// Backward-compatible: pre-v0.7.0 configs that omit the `[documents]`
    /// block deserialize cleanly with defaults.
    #[serde(default)]
    pub documents: DocumentConfig,
    /// Auth-mode config for the HTTP transport (v0.8.0 P3). `None` =
    /// no `[auth]` block in the config file = fall through to the
    /// v0.7.x `--bearer-token-file` flag (loopback default still
    /// runs unauthenticated). Operators opt into config-driven auth
    /// by writing an `[auth]` block.
    #[serde(default)]
    pub auth: Option<AuthSettings>,
    /// Audit log settings (v0.8.0 P4). Default = `AuditSettings::default()`
    /// (retention_days=None → forever; purge_interval_secs=None → no
    /// background sweep). The audit table is always created via
    /// migration 0005 regardless of this config block; the block only
    /// controls retention behavior.
    #[serde(default)]
    pub audit: AuditSettings,
    /// PII redaction settings (v0.8.0 P5). Default = disabled. When
    /// enabled, the writer-actor runs the built-in detectors plus any
    /// `[[redaction.custom]]` patterns over text content before INSERT.
    /// Telemetry: `redaction.applied` audit rows record pattern-name
    /// match counts (never the matched substrings — strict).
    #[serde(default)]
    pub redaction: RedactionConfig,
}

/// User-identity settings persisted under `[identity]` in `solo.config.toml`.
///
/// `user_aliases` lets a user query `facts_about(subject = "alex")` and have
/// the read path also surface rows that were extracted historically with the
/// canonical `subject_id = "user"` (or vice-versa). The forward-going
/// extraction pipeline (Priority 1 sub-steps 1A + 1B) prefers named entities
/// over `"user"`, but historical triples written before 1A still use
/// `"user"` — read-side alias expansion bridges the two without rewriting
/// any data.
///
/// Default = empty — zero behaviour change for existing configs.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct IdentityConfig {
    /// Names that should be treated as equivalent to the canonical `"user"`
    /// subject when querying `facts_about`. Lets a user query "facts about
    /// alex" and get rows that were historically extracted with
    /// `subject_id = "user"`. Case-sensitive — match the casing in the
    /// triples table.
    #[serde(default)]
    pub user_aliases: Vec<String>,
}

/// Document parser + chunker settings persisted under `[documents]` in
/// `solo.config.toml`. New in v0.7.0 (RAG / document-memory).
///
/// Defaults match the v0.7.0 implementation plan:
///   * `chunk_token_target = 500` — approx 2000 chars per chunk
///   * `chunk_overlap_tokens = 50` — ~10% overlap so cross-boundary
///     sentences survive into both neighbouring chunks
///   * `allowed_extensions` — see `document::parse::ALLOWED` for the
///     canonical list (kept in sync; this field exists so operators
///     can disable specific formats without recompiling).
///
/// Backward compatible: pre-v0.7.0 configs that omit the block
/// deserialize with all defaults applied.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DocumentConfig {
    #[serde(default = "default_chunk_token_target")]
    pub chunk_token_target: u32,
    #[serde(default = "default_chunk_overlap_tokens")]
    pub chunk_overlap_tokens: u32,
    #[serde(default = "default_allowed_extensions")]
    pub allowed_extensions: Vec<String>,
}

fn default_chunk_token_target() -> u32 {
    500
}

fn default_chunk_overlap_tokens() -> u32 {
    50
}

fn default_allowed_extensions() -> Vec<String> {
    vec![
        "md", "markdown", "txt", "rs", "py", "toml", "yaml", "yml", "json", "pdf", "html", "htm",
    ]
    .into_iter()
    .map(String::from)
    .collect()
}

impl Default for DocumentConfig {
    fn default() -> Self {
        Self {
            chunk_token_target: default_chunk_token_target(),
            chunk_overlap_tokens: default_chunk_overlap_tokens(),
            allowed_extensions: default_allowed_extensions(),
        }
    }
}

/// Embedder identity persisted to disk so startup can detect drift.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EmbedderConfig {
    pub name: String,
    pub version: String,
    pub dim: u32,
    /// Serialized form of `solo_core::EmbeddingDtype`: "f32" | "f16" | "i8" | "binary".
    pub dtype: String,
}

impl SoloConfig {
    /// Build a fresh config for first-run setup. Caller supplies the salt
    /// (typically `KeyMaterial::fresh_salt()`). `identity` defaults to
    /// empty — `solo init` does not seed `user_aliases`; users opt in by
    /// editing `solo.config.toml`.
    pub fn new(salt: [u8; SALT_LEN], embedder: EmbedderConfig) -> Self {
        Self {
            schema_version: CONFIG_SCHEMA_VERSION,
            salt_hex: hex::encode(salt),
            embedder,
            identity: IdentityConfig::default(),
            documents: DocumentConfig::default(),
            auth: None,
            audit: AuditSettings::default(),
            redaction: RedactionConfig::default(),
        }
    }

    /// Decode the persisted salt back to its 16-byte form.
    pub fn salt_bytes(&self) -> Result<[u8; SALT_LEN]> {
        let bytes = hex::decode(&self.salt_hex)
            .map_err(|e| Error::storage(format!("config salt_hex is not valid hex: {e}")))?;
        if bytes.len() != SALT_LEN {
            return Err(Error::storage(format!(
                "config salt_hex must decode to {} bytes, got {}",
                SALT_LEN,
                bytes.len()
            )));
        }
        let mut out = [0u8; SALT_LEN];
        out.copy_from_slice(&bytes);
        Ok(out)
    }

    /// Serialize to `solo.config.toml` at the given path. Atomic-writes via a
    /// `<path>.tmp` file + rename so a crash mid-write can't leave a partial
    /// config. Refuses to overwrite an existing file (caller must handle the
    /// already-initialized case).
    ///
    /// Durability ordering: write tmp → fsync tmp → rename → fsync parent dir
    /// (Unix only; Windows relies on NTFS's metadata journal). The salt
    /// stored here is the only path back into the SQLCipher database — a
    /// partial-write corruption locks the user out forever, so we pay the
    /// fsync cost (~1 ms) without compromise.
    pub fn write(&self, path: &Path) -> Result<()> {
        if path.exists() {
            return Err(Error::conflict(format!(
                "config already exists: {}",
                path.display()
            )));
        }
        let tmp_path = path.with_extension("toml.tmp");
        let body = toml::to_string_pretty(self)
            .map_err(|e| Error::storage(format!("toml serialize: {e}")))?;

        // Open + write + fsync the tmp file before exposing it via rename.
        {
            let mut tmp_file = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&tmp_path)
                .map_err(|e| Error::storage(format!("open tmp {}: {e}", tmp_path.display())))?;
            std::io::Write::write_all(&mut tmp_file, body.as_bytes())
                .map_err(|e| Error::storage(format!("write {}: {e}", tmp_path.display())))?;
            tmp_file
                .sync_all()
                .map_err(|e| Error::storage(format!("fsync tmp {}: {e}", tmp_path.display())))?;
        }

        std::fs::rename(&tmp_path, path)
            .map_err(|e| Error::storage(format!("rename to {}: {e}", path.display())))?;

        // fsync the parent directory so the rename persists across a crash.
        // No-op on Windows — opening a directory for FlushFileBuffers requires
        // FILE_FLAG_BACKUP_SEMANTICS; NTFS's metadata journal handles this case.
        #[cfg(unix)]
        {
            if let Some(parent) = path.parent() {
                if let Ok(d) = std::fs::OpenOptions::new().read(true).open(parent) {
                    let _ = d.sync_all();
                }
            }
        }

        Ok(())
    }

    /// Read + parse from `solo.config.toml`. Validates schema_version.
    pub fn read(path: &Path) -> Result<Self> {
        let body = std::fs::read_to_string(path)
            .map_err(|e| Error::storage(format!("read {}: {e}", path.display())))?;
        let cfg: Self = toml::from_str(&body)
            .map_err(|e| Error::storage(format!("toml parse {}: {e}", path.display())))?;
        if cfg.schema_version != CONFIG_SCHEMA_VERSION {
            return Err(Error::storage(format!(
                "config schema_version mismatch: file is v{}, this binary expects v{}",
                cfg.schema_version, CONFIG_SCHEMA_VERSION
            )));
        }
        // Validate salt_hex shape eagerly so callers see the error here, not
        // later at key-derive time.
        let _ = cfg.salt_bytes()?;
        Ok(cfg)
    }
}

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

    fn fixture_embedder() -> EmbedderConfig {
        EmbedderConfig {
            name: "bge-m3".into(),
            version: "v1.0".into(),
            dim: 1024,
            dtype: "f32".into(),
        }
    }

    #[test]
    fn roundtrip_via_disk() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");

        let salt = [7u8; SALT_LEN];
        let cfg = SoloConfig::new(salt, fixture_embedder());
        cfg.write(&path).unwrap();

        let read_back = SoloConfig::read(&path).unwrap();
        assert_eq!(cfg, read_back);
        assert_eq!(read_back.salt_bytes().unwrap(), salt);
    }

    #[test]
    fn write_refuses_overwrite() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        let cfg = SoloConfig::new([0; SALT_LEN], fixture_embedder());
        cfg.write(&path).unwrap();
        let err = cfg.write(&path).unwrap_err();
        assert!(err.to_string().contains("already exists"), "got: {err}");
    }

    #[test]
    fn read_rejects_wrong_schema_version() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            r#"
schema_version = 99
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#,
        )
        .unwrap();
        let err = SoloConfig::read(&path).unwrap_err();
        assert!(err.to_string().contains("schema_version mismatch"), "got: {err}");
    }

    #[test]
    fn read_rejects_non_hex_salt() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#
            ),
        )
        .unwrap();
        let err = SoloConfig::read(&path).unwrap_err();
        // hex::decode fails on non-hex chars → "not valid hex".
        assert!(err.to_string().contains("salt_hex"), "got: {err}");
    }

    #[test]
    fn read_rejects_missing_embedder_block() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"
"#
            ),
        )
        .unwrap();
        let err = SoloConfig::read(&path).unwrap_err();
        // serde error for missing field
        assert!(err.to_string().to_lowercase().contains("embedder") || err.to_string().contains("missing"), "got: {err}");
    }

    #[test]
    fn read_loads_user_aliases_from_identity_block() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[identity]
user_aliases = ["alex", "alice"]
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert_eq!(cfg.identity.user_aliases, vec!["alex".to_string(), "alice".to_string()]);
    }

    #[test]
    fn read_defaults_identity_when_block_absent() {
        // Backward compat: existing configs (pre-v0.5.0) have no
        // [identity] block. They must still deserialize cleanly, with
        // `user_aliases` defaulting to empty.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert!(cfg.identity.user_aliases.is_empty());
    }

    #[test]
    fn read_defaults_user_aliases_when_identity_block_empty() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[identity]
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert!(cfg.identity.user_aliases.is_empty());
    }

    #[test]
    fn read_defaults_documents_when_block_absent() {
        // Pre-v0.7.0 configs have no [documents] block. They must still
        // deserialize cleanly, with defaults applied.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert_eq!(cfg.documents.chunk_token_target, 500);
        assert_eq!(cfg.documents.chunk_overlap_tokens, 50);
        assert!(cfg.documents.allowed_extensions.contains(&"md".to_string()));
        assert!(cfg.documents.allowed_extensions.contains(&"pdf".to_string()));
    }

    #[test]
    fn read_loads_custom_documents_block() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[documents]
chunk_token_target = 250
chunk_overlap_tokens = 25
allowed_extensions = ["md", "txt"]
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert_eq!(cfg.documents.chunk_token_target, 250);
        assert_eq!(cfg.documents.chunk_overlap_tokens, 25);
        assert_eq!(cfg.documents.allowed_extensions, vec!["md".to_string(), "txt".to_string()]);
    }

    #[test]
    fn document_config_default_matches_plan() {
        let d = DocumentConfig::default();
        assert_eq!(d.chunk_token_target, 500);
        assert_eq!(d.chunk_overlap_tokens, 50);
        // Sanity: the allow-list mirrors the parser's. If parse::ALLOWED
        // grows, this default + the test below should be kept in sync.
        for ext in &["md", "markdown", "txt", "rs", "py", "toml", "yaml", "yml", "json", "pdf", "html", "htm"] {
            assert!(
                d.allowed_extensions.iter().any(|e| e == ext),
                "default allowed_extensions missing {ext}"
            );
        }
    }

    #[test]
    fn read_defaults_auth_when_block_absent() {
        // Pre-v0.8.0 configs (or operators sticking with the
        // `--bearer-token-file` CLI flag) have no `[auth]` block.
        // They must deserialize cleanly with `auth = None`.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert!(cfg.auth.is_none());
    }

    #[test]
    fn read_loads_bearer_auth_block() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[auth]
mode = "bearer"
token = "s3cr3t"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        match cfg.auth {
            Some(AuthSettings::Bearer { token }) => assert_eq!(token, "s3cr3t"),
            other => panic!("expected bearer, got {other:?}"),
        }
    }

    #[test]
    fn read_loads_oidc_auth_block_with_default_tenant_claim() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[auth]
mode = "oidc"
discovery_url = "https://idp.example.com/.well-known/openid-configuration"
audience = "solo-prod"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        match cfg.auth {
            Some(AuthSettings::Oidc {
                discovery_url,
                audience,
                tenant_claim_name,
            }) => {
                assert_eq!(
                    discovery_url,
                    "https://idp.example.com/.well-known/openid-configuration"
                );
                assert_eq!(audience, "solo-prod");
                // default
                assert_eq!(tenant_claim_name, "solo_tenant");
            }
            other => panic!("expected oidc, got {other:?}"),
        }
    }

    #[test]
    fn read_loads_oidc_auth_block_with_custom_tenant_claim() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[auth]
mode = "oidc"
discovery_url = "https://idp.example.com/.well-known/openid-configuration"
audience = "solo-prod"
tenant_claim_name = "org_id"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        match cfg.auth {
            Some(AuthSettings::Oidc {
                tenant_claim_name, ..
            }) => assert_eq!(tenant_claim_name, "org_id"),
            other => panic!("expected oidc, got {other:?}"),
        }
    }

    #[test]
    fn read_defaults_audit_when_block_absent() {
        // Pre-v0.8.0-P4 configs (and the typical fresh init) have no
        // `[audit]` block. They must deserialize cleanly with default
        // AuditSettings (retention_days=None, purge_interval_secs=None).
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert!(cfg.audit.retention_days.is_none());
        assert!(cfg.audit.purge_interval_secs.is_none());
    }

    #[test]
    fn read_loads_audit_block_with_retention_only() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[audit]
retention_days = 30
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert_eq!(cfg.audit.retention_days, Some(30));
        assert!(cfg.audit.purge_interval_secs.is_none());
    }

    #[test]
    fn read_loads_audit_block_with_purge_interval() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "00000000000000000000000000000000"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"

[audit]
retention_days = 7
purge_interval_secs = 3600
"#
            ),
        )
        .unwrap();
        let cfg = SoloConfig::read(&path).expect("read ok");
        assert_eq!(cfg.audit.retention_days, Some(7));
        assert_eq!(cfg.audit.purge_interval_secs, Some(3600));
    }

    #[test]
    fn read_rejects_short_salt_hex() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("solo.config.toml");
        std::fs::write(
            &path,
            format!(
                r#"
schema_version = {CONFIG_SCHEMA_VERSION}
salt_hex = "deadbeef"

[embedder]
name = "bge-m3"
version = "v1.0"
dim = 1024
dtype = "f32"
"#
            ),
        )
        .unwrap();
        let err = SoloConfig::read(&path).unwrap_err();
        assert!(err.to_string().contains("salt_hex"), "got: {err}");
    }
}