Skip to main content

pond/
config.rs

1//! Configuration loading: the `[embeddings]`, `[sources]`, and `[storage]`
2//! blocks.
3//!
4//! pond ships built-in defaults, so an instance with no `config.toml` still
5//! works. `pond config --print-schema` emits [`DEFAULT_CONFIG_TOML`], the
6//! fully-annotated example.
7
8use std::{
9    collections::BTreeMap,
10    path::{Path, PathBuf},
11};
12
13use anyhow::{Context, Result, anyhow, bail};
14use lance_io::object_store::uri_to_url;
15use serde::{Deserialize, Deserializer, Serialize, de};
16use serde_json::Value;
17use url::Url;
18
19/// Parse `"128 MiB"`, `"1 GiB"`, `"500 KiB"`, or a bare byte count. Accepts
20/// SI (KB/MB/GB) and binary (KiB/MiB/GiB/TiB) suffixes; treats the bare unit
21/// `"B"` and unsuffixed numbers as raw bytes. Tolerant of whitespace and
22/// case. The result MUST fit in `usize` (Lance's cache APIs take `usize`).
23fn parse_byte_size(raw: &str) -> Result<usize, String> {
24    let trimmed = raw.trim();
25    if trimmed.is_empty() {
26        return Err("byte-size value is empty".to_owned());
27    }
28    let split = trimmed
29        .find(|c: char| c.is_ascii_alphabetic())
30        .unwrap_or(trimmed.len());
31    let (number, unit) = trimmed.split_at(split);
32    let number: f64 = number
33        .trim()
34        .parse()
35        .map_err(|_| format!("byte-size value {raw:?} is not a number"))?;
36    if !number.is_finite() || number < 0.0 {
37        return Err(format!("byte-size value {raw:?} must be non-negative"));
38    }
39    let multiplier: f64 = match unit.trim().to_ascii_lowercase().as_str() {
40        "" | "b" => 1.0,
41        "k" | "kb" => 1_000.0,
42        "kib" => 1_024.0,
43        "m" | "mb" => 1_000_000.0,
44        "mib" => 1_048_576.0,
45        "g" | "gb" => 1_000_000_000.0,
46        "gib" => 1_073_741_824.0,
47        "tib" => 1_099_511_627_776.0,
48        other => {
49            return Err(format!(
50                "byte-size unit {other:?} not recognized (try MiB / GiB)"
51            ));
52        }
53    };
54    let bytes = number * multiplier;
55    if !bytes.is_finite() || bytes > usize::MAX as f64 {
56        return Err(format!("byte-size value {raw:?} overflows usize"));
57    }
58    Ok(bytes as usize)
59}
60
61fn deserialize_byte_size_opt<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
62where
63    D: Deserializer<'de>,
64{
65    #[derive(Deserialize)]
66    #[serde(untagged)]
67    enum Repr {
68        Bytes(u64),
69        Text(String),
70    }
71    let repr: Option<Repr> = Option::deserialize(deserializer)?;
72    match repr {
73        None => Ok(None),
74        Some(Repr::Bytes(value)) => usize::try_from(value).map(Some).map_err(de::Error::custom),
75        Some(Repr::Text(value)) => parse_byte_size(&value).map(Some).map_err(de::Error::custom),
76    }
77}
78
79/// Parse a CLI / env `--data-dir` argument into a `Url`. Delegates to Lance's
80/// own `uri_to_url`, which handles every form pond cares about:
81/// - bare paths like `/srv/pond` -> `file:///srv/pond`
82/// - explicit `file://...` URIs
83/// - object-store URIs (`s3://`, `gs://`, `az://`, ...)
84/// - tilde expansion (`~/...`)
85/// - Windows drive letters (we don't ship Windows, but the parser handles it)
86///
87/// Using Lance's parser keeps pond's CLI parse path identical to what Lance
88/// uses internally - no risk of pond accepting a string Lance later rejects.
89pub fn parse_data_dir(input: &str) -> Result<Url> {
90    uri_to_url(input).with_context(|| format!("invalid --data-dir {input:?}"))
91}
92
93/// True when the URL is on the local filesystem. Mirrors Lance's
94/// `ObjectStore::is_local` (lance-io/src/object_store.rs:541): the `file` and
95/// `file+uring` schemes are local; everything else (incl. `memory://`) is not.
96pub fn is_local(url: &Url) -> bool {
97    matches!(url.scheme(), "file" | "file+uring")
98}
99
100/// Extract the filesystem `PathBuf` for local URLs. `None` for remote.
101pub fn local_path(url: &Url) -> Option<PathBuf> {
102    if is_local(url) {
103        url.to_file_path().ok()
104    } else {
105        None
106    }
107}
108
109/// URI string for a child of this location (typically one Lance dataset under
110/// the data dir). Trims a single trailing slash on the base, then concatenates
111/// with a `/` separator. This keeps `Dataset::open` / `Dataset::write` happy
112/// on both filesystem and object-store backends - they want the URI form, not
113/// a `url::Url`.
114pub fn child_uri(base: &Url, suffix: &str) -> String {
115    // For local URLs we strip the `file://` prefix so log lines and error
116    // messages render as plain paths (`/srv/pond/sessions.lance`), matching
117    // what pond used to emit before the URL migration.
118    if let Some(path) = local_path(base) {
119        return path.join(suffix).display().to_string();
120    }
121    format!("{}/{suffix}", base.as_str().trim_end_matches('/'))
122}
123
124/// Render a `Url` for human-readable log/diagnostic output: local URLs come
125/// back as plain paths (no `file://` prefix); remote URLs stay verbatim.
126pub fn display(url: &Url) -> String {
127    if let Some(path) = local_path(url) {
128        path.display().to_string()
129    } else {
130        url.to_string()
131    }
132}
133
134/// Build a `Url` from a filesystem path. Convenience for tests and for
135/// `resolve_data_dir` callers that hold a `PathBuf` already. The path must be
136/// absolute (`url::Url::from_file_path` is a hard requirement on Unix); a
137/// relative path gets canonicalized via `std::path::absolute` first.
138pub fn url_for_path(path: impl AsRef<Path>) -> Result<Url> {
139    let path = path.as_ref();
140    let absolute = if path.is_absolute() {
141        path.to_path_buf()
142    } else {
143        std::path::absolute(path)
144            .with_context(|| format!("failed to absolutize {}", path.display()))?
145    };
146    Url::from_file_path(&absolute).map_err(|()| {
147        anyhow!(
148            "failed to convert path {} into a file:// URL",
149            absolute.display()
150        )
151    })
152}
153
154/// Default `config.toml` body emitted by `pond config --print-schema`. Every
155/// line is commented: pond ships built-in defaults, so the file is purely a
156/// discoverable template and pond still works with no `config.toml` on disk.
157pub const DEFAULT_CONFIG_TOML: &str = "\
158# pond configuration.
159#
160# pond ships built-in defaults, so every setting here is optional - delete this
161# file and pond still works. Uncomment and edit to override.
162
163# Where pond looks for source data to import. One entry per adapter type
164# (`claude-code`, `codex-cli`, ...). `pond sync` with no arguments syncs every
165# entry; `pond sync <adapter>` syncs just one. With an empty `[sources]`,
166# `pond sync` runs an interactive discovery against the known default paths
167# and writes the picks back here.
168#
169# Future wrap: pond is single-namespace in v1 (spec.md#wire-namespace-resolution); `[sources]` is
170# flat here. When multi-namespace pond lands, source registration becomes
171# per-tenant under `[namespaces.<ns>.sources.<adapter>]`. Pre-v1 the schema
172# is breakable; the rename is operationally free until a real second tenant
173# exists.
174#
175# [sources.claude-code]
176# enabled = true
177# path = \"~/.claude/projects\"
178#
179# [sources.codex-cli]
180# enabled = true
181# path = \"~/.codex/sessions\"
182#
183# Set `enabled = false` to keep the section but skip it on `pond sync`;
184# re-enable via `pond sync <adapter>`.
185
186# Embeddings. Search runs hybrid (vector + FTS) whenever the store has any
187# vectors, and FTS-only otherwise - the model loads lazily on the first hybrid
188# query, so there's no cost on FTS-only corpora. `model` selects the
189# HuggingFace XLM-RoBERTa model; `dim` declares its output width and is baked
190# into the messages.vector schema on table creation - it must equal the
191# model's hidden_size and be a multiple of 8 (IVF_PQ subspace stride).
192#
193# Common pairings:
194#   model = \"intfloat/multilingual-e5-small\"   dim = 384   (default)
195#   model = \"intfloat/multilingual-e5-base\"    dim = 768
196#   model = \"intfloat/multilingual-e5-large\"   dim = 1024
197#
198# A different-dim model needs a fresh data dir; pond enforces this at the
199# schema boundary.
200#
201# [embeddings]
202# model = \"intfloat/multilingual-e5-small\"
203# dim = 384
204
205# Search tuning. Leave unset for Lance defaults; set when tuning IVF_PQ recall
206# against a corpus.
207#
208# [search]
209# nprobes = 16
210# refine_factor = 2
211
212# Storage maintenance. Tunes the compaction + cleanup pass that runs inside
213# `pond sync` and `pond index optimize`.
214#
215# - `compaction_fragment_cap` is the sub-target fragment count past which the
216#   compaction phase runs (it also runs once those fragments hold a whole target
217#   fragment's worth of rows). Default 64 stops the automated sync re-compacting
218#   the trailing fragment every pass; 0 compacts every pass.
219# - `cleanup_older_than` is the manifest-retention window for the safe cleanup
220#   pass. Accepts `Ns` / `Nm` / `Nh` / `Nd` (default `1d`). Versions older than
221#   this are reclaimed by Lance's OCC-coordinated GC.
222# - `index_lag_threshold` is the minimum unindexed-fragment count before a
223#   per-intent append/rebuild runs in `pond index optimize`; the brute-force
224#   fallback keeps queries correct while fragments accumulate. Default 4.
225#
226# [maintenance]
227# compaction_fragment_cap = 64
228# cleanup_older_than = \"1d\"
229# index_lag_threshold = 4
230
231# Long-running process caps. Both accept either a plain byte count or a
232# humansize-style suffix (\"128 MiB\", \"1 GiB\"). Both are optional - leave
233# unset to let pond pick the backend-aware default:
234#   local FS  : index_cache = 256 MiB, metadata_cache = 128 MiB
235#   remote    : index_cache = 2 GiB,   metadata_cache = 512 MiB
236# Lance's library defaults (6 GiB / 1 GiB) are too generous for a per-session
237# `pond mcp` process; tightening them is what keeps RSS under the 500 MiB target
238# without measurable latency regressions on typical agent-history corpora.
239#
240# [runtime]
241# index_cache_bytes    = \"256 MiB\"
242# metadata_cache_bytes = \"128 MiB\"
243
244# Object-store credentials and tuning, passed verbatim to Lance's
245# `DatasetBuilder::with_storage_options`. Required only when `--data-dir` is
246# an `s3://` / `gs://` / `az://` URI that needs auth or a non-default region.
247# Keys follow the `object_store` crate's standard names. Environment
248# variables of the same name are read by `object_store` automatically;
249# values in this block override them. pond does not parse these.
250#
251# Future wrap: pond is single-namespace in v1 (spec.md#wire-namespace-resolution); `[storage]` is
252# flat here on the assumption of one bucket per pond. When multi-namespace
253# pond lands and tenants need separate buckets/regions, this becomes
254# `[namespaces.<ns>.storage]`. Pre-v1 the schema is breakable; the rename is
255# operationally free until a real second tenant exists.
256#
257# [storage]
258# AWS_ACCESS_KEY_ID = \"...\"
259# AWS_SECRET_ACCESS_KEY = \"...\"
260# AWS_REGION = \"us-east-1\"
261# AWS_ENDPOINT = \"https://minio.example.com\"  # for self-hosted MinIO
262# allow_http = \"true\"                          # only for non-TLS endpoints
263";
264
265/// Top-level `config.toml` shape.
266#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
267#[serde(deny_unknown_fields)]
268pub struct Config {
269    #[serde(default)]
270    pub embeddings: EmbeddingsConfig,
271    #[serde(default)]
272    pub search: SearchConfig,
273    #[serde(default)]
274    pub maintenance: MaintenanceConfig,
275    #[serde(default)]
276    pub runtime: RuntimeConfig,
277    /// `[sources.<adapter>]` map: per-adapter config blobs the matching
278    /// factory deserializes inside its `open()`. The shape is adapter-defined
279    /// (filesystem adapters expect `{ path = "..." }`; API-backed adapters
280    /// expect endpoint + auth keys), so this layer stays opaque. Empty by
281    /// default; `pond sync` runs discovery into this map on first use.
282    #[serde(default)]
283    pub sources: BTreeMap<String, Value>,
284    /// `[storage]` key=value pairs handed verbatim to Lance's
285    /// `DatasetBuilder::with_storage_options` and `WriteParams.store_params`.
286    /// Keys are the standard `object_store` config names
287    /// (`AWS_ACCESS_KEY_ID`, `AWS_REGION`, `AWS_ENDPOINT`, etc.); see Lance's
288    /// `DatasetBuilder::with_storage_options` doc for the per-scheme variants
289    /// (S3 / GCS / Azure). pond does not parse or validate these; Lance does.
290    /// Empty by default; required only when `--data-dir` is an object-store
291    /// URI that needs credentials or a non-default region/endpoint. Values
292    /// here override any matching environment variables.
293    #[serde(default)]
294    pub storage: BTreeMap<String, String>,
295}
296
297/// `[runtime]`: long-running process caps. Both knobs accept either a plain
298/// byte count or a `humansize`-style suffix (`"128 MiB"`, `"1 GiB"`). Both are
299/// optional - `None` lets `pond::substrate` pick the backend-aware default
300/// (local FS gets a tight cap; object stores stay near Lance's defaults).
301#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
302#[serde(deny_unknown_fields, default)]
303pub struct RuntimeConfig {
304    #[serde(default, deserialize_with = "deserialize_byte_size_opt")]
305    pub index_cache_bytes: Option<usize>,
306    #[serde(default, deserialize_with = "deserialize_byte_size_opt")]
307    pub metadata_cache_bytes: Option<usize>,
308}
309
310/// `[search]`: optional Lance vector-query tuning knobs.
311#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct SearchConfig {
314    #[serde(default)]
315    pub nprobes: Option<usize>,
316    #[serde(default)]
317    pub refine_factor: Option<u32>,
318}
319
320/// `[maintenance]`: storage-maintenance knobs shared by `pond sync` and
321/// `pond index optimize`. All optional - omit and pond falls back to the
322/// in-process defaults in `pond::substrate` (`DEFAULT_COMPACTION_FRAGMENT_CAP`,
323/// `default_cleanup_older_than`, and the `index_lag_threshold` initializer).
324#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
325#[serde(deny_unknown_fields)]
326pub struct MaintenanceConfig {
327    /// Sub-target fragment count past which the compaction phase runs (it also
328    /// runs once those fragments hold a whole target fragment's worth of rows).
329    /// Default 64 stops the automated sync re-compacting the trailing fragment
330    /// every pass; 0 compacts every pass.
331    #[serde(default)]
332    pub compaction_fragment_cap: Option<usize>,
333    /// Manifest-retention window for the safe cleanup pass. Accepts
334    /// `Ns`/`Nm`/`Nh`/`Nd` (default `1d`). Versions older than this are
335    /// reclaimed by Lance's OCC-coordinated GC (`delete_unverified=false`),
336    /// which never races a concurrent writer on any backend.
337    #[serde(default)]
338    pub cleanup_older_than: Option<String>,
339    /// Minimum unindexed-fragment count below which `optimize_table_indices`
340    /// skips the per-intent append/rebuild path; the brute-force fallback
341    /// keeps queries correct while fragments accumulate. Default 4 trades a
342    /// little query latency on cold fragments for far fewer remote index
343    /// commits during high-rate ingest.
344    #[serde(default)]
345    pub index_lag_threshold: Option<usize>,
346}
347
348/// `[embeddings]`: model selector and vector dimension. There is no master
349/// switch - the search path always runs hybrid when vectors exist in the
350/// store and FTS-only when they don't (`has_embeddings()` is the only gate);
351/// the candle/Metal model is `LazyEmbedder`-loaded on the first query that
352/// actually needs it. `model` and `dim` are installed into the process at
353/// startup via `embed::init_model_id` / `sessions::init_embedding_dim`, so
354/// swapping models for a one-off experiment is a temporary config file - no
355/// CLI flag and no per-call-site plumbing.
356#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
357#[serde(deny_unknown_fields, default)]
358pub struct EmbeddingsConfig {
359    /// The embedding model id (spec.md#search): any XLM-RoBERTa model loadable
360    /// by `candle-transformers`. Defaults to `intfloat/multilingual-e5-base`.
361    pub model: String,
362    /// Output dimension of `model`. Must equal the model's `hidden_size` and
363    /// be divisible by 8 (the IVF_PQ subspace stride; see `embed::index_params`).
364    /// Defaults to 768 (e5-base). Set to 384 for e5-small, 1024 for e5-large.
365    pub dim: usize,
366}
367
368impl Default for EmbeddingsConfig {
369    fn default() -> Self {
370        Self {
371            model: crate::embed::DEFAULT_MODEL_ID.to_owned(),
372            dim: crate::sessions::DEFAULT_EMBEDDING_DIM,
373        }
374    }
375}
376
377/// Resolve pond's data directory. An explicit `--data-dir` / `POND_DATA_DIR`
378/// wins (and may carry an `s3://` / `gs://` / `az://` URI); otherwise the
379/// XDG-local fallback (`$XDG_DATA_HOME/pond`, then `$HOME/.local/share/pond`,
380/// then `.pond`). `xdg_data_home` is honored only if absolute, per the XDG
381/// base-directory spec.
382pub fn resolve_data_dir(
383    explicit: Option<Url>,
384    xdg_data_home: Option<PathBuf>,
385    home: Option<PathBuf>,
386) -> Result<Url> {
387    if let Some(location) = explicit {
388        return Ok(location);
389    }
390    if let Some(xdg) = xdg_data_home.filter(|path| path.is_absolute()) {
391        return url_for_path(xdg.join("pond"));
392    }
393    if let Some(home) = home {
394        return url_for_path(home.join(".local").join("share").join("pond"));
395    }
396    // No HOME and no usable XDG var - stay usable rather than panic.
397    url_for_path(PathBuf::from(".pond"))
398}
399
400/// Local default path for `config.toml`. URI-backed data dirs always land
401/// here because the config file has to be local (it names the bucket and
402/// any creds). XDG hierarchy: `$XDG_CONFIG_HOME/pond/config.toml`, then
403/// `$HOME/.config/pond/config.toml`, then `.pond.toml` in cwd.
404pub fn default_config_path(xdg_config_home: Option<PathBuf>, home: Option<PathBuf>) -> PathBuf {
405    if let Some(xdg) = xdg_config_home.filter(|path| path.is_absolute()) {
406        return xdg.join("pond").join("config.toml");
407    }
408    if let Some(home) = home {
409        return home.join(".config").join("pond").join("config.toml");
410    }
411    PathBuf::from(".pond.toml")
412}
413
414impl Config {
415    /// Load `config.toml` from `path` if it exists and validate it. A missing
416    /// file yields the built-in defaults. On success the resolved embedding
417    /// model id + dim are installed into the process (`OnceLock`-backed; only
418    /// the first call per process sticks), so all downstream code paths see a
419    /// consistent pair without per-handler plumbing.
420    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
421        let path = path.as_ref();
422        let config = if path.exists() {
423            let text = std::fs::read_to_string(path)
424                .with_context(|| format!("failed to read config {}", path.display()))?;
425            toml::from_str::<Self>(&text)
426                .with_context(|| format!("failed to parse config {}", path.display()))?
427        } else {
428            Self::default()
429        };
430        config.embeddings.validate()?;
431        config.embeddings.install_runtime();
432        if let Some(threshold) = config.maintenance.index_lag_threshold {
433            crate::substrate::init_index_lag_threshold(threshold);
434        }
435        // Tilde expansion is per-adapter (inside each factory's `open()`):
436        // an API-backed adapter has no path to expand, and only the
437        // filesystem-shaped adapters need the helper. See `expand_home_under`.
438        Ok(config)
439    }
440
441    /// Resolve the `[sources.<adapter>]` entries to drive `pond sync`. Only
442    /// sections with `enabled = true` flow through; sections with
443    /// `enabled = false` (or absent) are treated as opt-out and the
444    /// per-adapter blob (minus `enabled`) is handed to the factory's
445    /// `open()`. With `adapter = None` returns every enabled entry; with
446    /// `Some(name)` returns just that one - and errors if it's not in
447    /// config OR if it's currently disabled (the caller should then
448    /// re-prompt or report).
449    pub fn resolve_sources(&self, adapter: Option<&str>) -> Result<Vec<(String, Value)>> {
450        match adapter {
451            None => Ok(self
452                .sources
453                .iter()
454                .filter_map(|(name, blob)| take_enabled(name, blob))
455                .collect()),
456            Some(name) => {
457                let blob = self
458                    .sources
459                    .get(name)
460                    .ok_or_else(|| anyhow!("no [sources.{name}] entry in config"))?;
461                take_enabled(name, blob).map(|entry| vec![entry]).ok_or_else(|| {
462                    anyhow!(
463                        "source [{name}] is disabled (enabled = false); run `pond sync {name}` to re-enable"
464                    )
465                })
466            }
467        }
468    }
469
470    /// Names that are configured but currently `enabled = false`. Used by
471    /// `pond sync` post-import to know not to re-probe an adapter the user
472    /// already declined (the decline persists; re-prompt only via the
473    /// positional override `pond sync <name>`).
474    pub fn disabled_source_names(&self) -> Vec<&str> {
475        self.sources
476            .iter()
477            .filter_map(|(name, blob)| {
478                let enabled = blob
479                    .get("enabled")
480                    .and_then(Value::as_bool)
481                    .unwrap_or(false);
482                if enabled { None } else { Some(name.as_str()) }
483            })
484            .collect()
485    }
486}
487
488/// Inner helper: return `Some((name, blob))` when the source section is
489/// enabled, stripping the discriminator from the blob before handing it on;
490/// `None` when the section is missing `enabled` or has `enabled = false`.
491fn take_enabled(name: &str, blob: &Value) -> Option<(String, Value)> {
492    let enabled = blob
493        .get("enabled")
494        .and_then(Value::as_bool)
495        .unwrap_or(false);
496    if !enabled {
497        return None;
498    }
499    let mut clean = blob.clone();
500    if let Some(obj) = clean.as_object_mut() {
501        obj.remove("enabled");
502    }
503    Some((name.to_owned(), clean))
504}
505
506/// Tilde-expand `path` against an explicit `home`. Filesystem-shaped adapters
507/// call this from inside their factory's `open()`. Tests use it directly to
508/// exercise the rule without mutating the process-wide `HOME` env var
509/// (`std::env::set_var` is `unsafe` under edition 2024 and pond forbids
510/// unsafe code).
511pub fn expand_home_under(path: &Path, home: &Path) -> PathBuf {
512    let Some(text) = path.to_str() else {
513        return path.to_path_buf();
514    };
515    if text == "~" {
516        return home.to_path_buf();
517    }
518    if let Some(rest) = text.strip_prefix("~/") {
519        return home.join(rest);
520    }
521    path.to_path_buf()
522}
523
524impl EmbeddingsConfig {
525    /// Surface-level validation: model id non-empty and dim divisible by 8.
526    /// The dim/model mismatch is the load-time check inside `CandleEmbedder::load`,
527    /// which knows the model's `hidden_size`; what we can catch up front is the
528    /// IVF_PQ subspace stride (`dim / 8` in `embed::index_params`).
529    pub fn validate(&self) -> Result<()> {
530        if self.model.trim().is_empty() {
531            bail!("embeddings.model must be a non-empty HuggingFace model id");
532        }
533        if self.dim == 0 || !self.dim.is_multiple_of(8) {
534            bail!(
535                "embeddings.dim = {} must be a positive multiple of 8 (IVF_PQ subspace stride)",
536                self.dim,
537            );
538        }
539        Ok(())
540    }
541
542    /// Install model id + dim into the process. Idempotent: only the first
543    /// call sticks (matches `OnceLock` semantics in `embed::init_model_id` and
544    /// `sessions::init_embedding_dim`).
545    pub fn install_runtime(&self) {
546        crate::embed::init_model_id(self.model.clone());
547        crate::sessions::init_embedding_dim(self.dim);
548    }
549}
550
551#[cfg(test)]
552mod tests {
553    #![allow(clippy::expect_used, clippy::unwrap_used)]
554
555    use super::*;
556    use serde_json::Value;
557    use tempfile::TempDir;
558
559    #[test]
560    fn validate_catches_empty_model_and_bad_dim() {
561        assert!(EmbeddingsConfig::default().validate().is_ok());
562        // Empty / whitespace-only model id is rejected: HuggingFace fetch
563        // would fail far away from the config error.
564        let bad_model = EmbeddingsConfig {
565            model: "   ".to_owned(),
566            dim: 768,
567        };
568        assert!(bad_model.validate().is_err());
569        // Dim must divide 8 (PQ subspace stride in `embed::index_params`).
570        let bad_dim = EmbeddingsConfig {
571            model: "intfloat/multilingual-e5-base".to_owned(),
572            dim: 100,
573        };
574        assert!(bad_dim.validate().is_err());
575        // Zero is rejected too (would divide-by-zero inside index_params).
576        let zero_dim = EmbeddingsConfig {
577            model: "intfloat/multilingual-e5-base".to_owned(),
578            dim: 0,
579        };
580        assert!(zero_dim.validate().is_err());
581    }
582
583    #[test]
584    fn config_load_missing_file_falls_back_to_builtin() {
585        let config = Config::load("/nonexistent/pond-config-xyz.toml").unwrap();
586        assert_eq!(config.embeddings, EmbeddingsConfig::default());
587    }
588
589    #[test]
590    fn default_config_toml_loads_to_the_builtin_defaults() {
591        let dir = TempDir::new().unwrap();
592        let path = dir.path().join("config.toml");
593        std::fs::write(&path, DEFAULT_CONFIG_TOML).unwrap();
594        // The shipped template is all comments, so it must load and validate as
595        // the built-in defaults - a malformed template fails right here.
596        let config = Config::load(&path).unwrap();
597        assert_eq!(config.embeddings, EmbeddingsConfig::default());
598        assert_eq!(config.embeddings.model, crate::embed::DEFAULT_MODEL_ID);
599        assert_eq!(
600            config.embeddings.dim,
601            crate::sessions::DEFAULT_EMBEDDING_DIM
602        );
603    }
604
605    #[test]
606    fn resolve_data_dir_follows_explicit_then_xdg_then_home() {
607        // An explicit `--data-dir` / `POND_DATA_DIR` wins over everything. The
608        // explicit value can carry any URI form Lance accepts; here we test the
609        // local-path form (parsing is delegated to Lance's `uri_to_url`).
610        let explicit = parse_data_dir("/explicit").unwrap();
611        let resolved = resolve_data_dir(
612            Some(explicit.clone()),
613            Some(PathBuf::from("/xdg")),
614            Some(PathBuf::from("/home")),
615        )
616        .unwrap();
617        assert_eq!(resolved, explicit);
618
619        // An absolute XDG_DATA_HOME is used next.
620        let resolved = resolve_data_dir(
621            None,
622            Some(PathBuf::from("/xdg")),
623            Some(PathBuf::from("/home")),
624        )
625        .unwrap();
626        assert!(is_local(&resolved));
627        assert_eq!(local_path(&resolved).unwrap(), PathBuf::from("/xdg/pond"));
628
629        // A relative XDG_DATA_HOME is ignored per the XDG spec; HOME is the fallback.
630        let resolved = resolve_data_dir(
631            None,
632            Some(PathBuf::from("relative")),
633            Some(PathBuf::from("/home")),
634        )
635        .unwrap();
636        assert_eq!(
637            local_path(&resolved).unwrap(),
638            PathBuf::from("/home/.local/share/pond"),
639        );
640
641        // No XDG and no HOME - stays usable: returns the cwd-anchored `.pond`.
642        // The result is absolute (Lance's URL conversion requires it), so we
643        // just check that the URL ends with the relative path's components.
644        let resolved = resolve_data_dir(None, None, None).unwrap();
645        assert!(is_local(&resolved));
646        assert!(
647            local_path(&resolved).unwrap().ends_with(".pond"),
648            "fallback path should end with .pond: {resolved}",
649        );
650    }
651
652    #[test]
653    fn expand_home_under_handles_tilde_forms() {
654        let home = Path::new("/srv/me");
655        assert_eq!(
656            expand_home_under(Path::new("~"), home),
657            PathBuf::from("/srv/me")
658        );
659        assert_eq!(
660            expand_home_under(Path::new("~/.codex/sessions"), home),
661            PathBuf::from("/srv/me/.codex/sessions"),
662        );
663        // Absolute paths pass through unchanged.
664        assert_eq!(
665            expand_home_under(Path::new("/etc/passwd"), home),
666            PathBuf::from("/etc/passwd"),
667        );
668        // A leading `~something` (no slash) is not the home form - leave it.
669        assert_eq!(
670            expand_home_under(Path::new("~user/elsewhere"), home),
671            PathBuf::from("~user/elsewhere"),
672        );
673    }
674
675    #[test]
676    fn resolve_sources_returns_one_or_all_or_errors() {
677        let temp = TempDir::new().unwrap();
678        let body = "\
679[sources.claude-code]
680enabled = true
681path = \"/srv/claude\"
682
683[sources.codex-cli]
684enabled = true
685path = \"/srv/codex\"
686
687[sources.opencode]
688enabled = false
689";
690        let path = temp.path().join("config.toml");
691        std::fs::write(&path, body).expect("write config");
692        let config = Config::load(&path).unwrap();
693
694        // None -> only enabled entries
695        let all = config.resolve_sources(None).unwrap();
696        assert_eq!(all.len(), 2);
697        let names: Vec<_> = all.iter().map(|(n, _)| n.as_str()).collect();
698        assert!(names.contains(&"claude-code"));
699        assert!(names.contains(&"codex-cli"));
700        // The `enabled` discriminator never reaches the adapter blob.
701        for (_, blob) in &all {
702            assert!(blob.get("enabled").is_none(), "enabled should be stripped");
703        }
704
705        // Some(name) -> one entry, opaque JSON blob
706        let one = config.resolve_sources(Some("codex-cli")).unwrap();
707        assert_eq!(one.len(), 1);
708        assert_eq!(one[0].0, "codex-cli");
709        assert_eq!(
710            one[0].1.get("path").and_then(Value::as_str),
711            Some("/srv/codex"),
712        );
713
714        // Disabled positional -> errors with the recovery hint baked in.
715        let disabled = config.resolve_sources(Some("opencode"));
716        let err = disabled
717            .expect_err("disabled adapter must error")
718            .to_string();
719        assert!(err.contains("enabled = false"), "got: {err}");
720        assert!(err.contains("pond sync opencode"), "got: {err}");
721
722        // Unknown -> error
723        assert!(config.resolve_sources(Some("nope")).is_err());
724
725        // disabled_source_names lists exactly the off ones.
726        assert_eq!(config.disabled_source_names(), vec!["opencode"]);
727    }
728
729    #[test]
730    fn memory_uri_is_classified_as_remote() {
731        let url = parse_data_dir("memory:///pond-remote-test").expect("memory uri parses");
732        assert!(
733            !is_local(&url),
734            "memory:// is not a local-filesystem URL: {url}",
735        );
736        assert!(
737            local_path(&url).is_none(),
738            "local_path must return None for non-file schemes",
739        );
740    }
741}