1use std::{
11 collections::BTreeMap,
12 path::{Path, PathBuf},
13};
14
15use anyhow::{Context, Result, anyhow, bail};
16use figment::{
17 Figment,
18 providers::{Env, Format, Toml},
19};
20use serde::{Deserialize, Deserializer, Serialize, de};
21use serde_json::Value;
22use url::Url;
23
24fn parse_byte_size(raw: &str) -> Result<usize, String> {
29 let trimmed = raw.trim();
30 if trimmed.is_empty() {
31 return Err("byte-size value is empty".to_owned());
32 }
33 let split = trimmed
34 .find(|c: char| c.is_ascii_alphabetic())
35 .unwrap_or(trimmed.len());
36 let (number, unit) = trimmed.split_at(split);
37 let number: f64 = number
38 .trim()
39 .parse()
40 .map_err(|_| format!("byte-size value {raw:?} is not a number"))?;
41 if !number.is_finite() || number < 0.0 {
42 return Err(format!("byte-size value {raw:?} must be non-negative"));
43 }
44 let multiplier: f64 = match unit.trim().to_ascii_lowercase().as_str() {
45 "" | "b" => 1.0,
46 "k" | "kb" => 1_000.0,
47 "kib" => 1_024.0,
48 "m" | "mb" => 1_000_000.0,
49 "mib" => 1_048_576.0,
50 "g" | "gb" => 1_000_000_000.0,
51 "gib" => 1_073_741_824.0,
52 "tib" => 1_099_511_627_776.0,
53 other => {
54 return Err(format!(
55 "byte-size unit {other:?} not recognized (try MiB / GiB)"
56 ));
57 }
58 };
59 let bytes = number * multiplier;
60 if !bytes.is_finite() || bytes > usize::MAX as f64 {
61 return Err(format!("byte-size value {raw:?} overflows usize"));
62 }
63 Ok(bytes as usize)
64}
65
66fn lenient_string<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
70where
71 D: Deserializer<'de>,
72{
73 #[derive(Deserialize)]
74 #[serde(untagged)]
75 enum Repr {
76 Text(String),
77 Int(i64),
78 Float(f64),
79 Bool(bool),
80 }
81 Ok(
82 Option::<Repr>::deserialize(deserializer)?.map(|repr| match repr {
83 Repr::Text(value) => value,
84 Repr::Int(value) => value.to_string(),
85 Repr::Float(value) => value.to_string(),
86 Repr::Bool(value) => value.to_string(),
87 }),
88 )
89}
90
91fn deserialize_byte_size_opt<'de, D>(deserializer: D) -> Result<Option<usize>, D::Error>
92where
93 D: Deserializer<'de>,
94{
95 #[derive(Deserialize)]
96 #[serde(untagged)]
97 enum Repr {
98 Bytes(u64),
99 Text(String),
100 }
101 let repr: Option<Repr> = Option::deserialize(deserializer)?;
102 match repr {
103 None => Ok(None),
104 Some(Repr::Bytes(value)) => usize::try_from(value).map(Some).map_err(de::Error::custom),
105 Some(Repr::Text(value)) => parse_byte_size(&value).map(Some).map_err(de::Error::custom),
106 }
107}
108
109pub fn is_local(url: &Url) -> bool {
113 matches!(url.scheme(), "file" | "file+uring")
114}
115
116pub fn local_path(url: &Url) -> Option<PathBuf> {
118 if !is_local(url) {
119 return None;
120 }
121 match url.as_str().strip_prefix("file+uring:") {
125 Some(rest) => Url::parse(&format!("file:{rest}"))
126 .ok()?
127 .to_file_path()
128 .ok(),
129 None => url.to_file_path().ok(),
130 }
131}
132
133pub fn child_uri(base: &Url, suffix: &str) -> String {
139 if let Some(path) = local_path(base) {
143 return path.join(suffix).display().to_string();
144 }
145 format!("{}/{suffix}", base.as_str().trim_end_matches('/'))
146}
147
148pub fn display(url: &Url) -> String {
152 if let Some(path) = local_path(url) {
153 contract_home(&path).display().to_string()
154 } else {
155 url.to_string()
156 }
157}
158
159pub fn url_for_path(path: impl AsRef<Path>) -> Result<Url> {
164 let path = path.as_ref();
165 let absolute = if path.is_absolute() {
166 path.to_path_buf()
167 } else {
168 std::path::absolute(path)
169 .with_context(|| format!("failed to absolutize {}", path.display()))?
170 };
171 Url::from_file_path(&absolute).map_err(|()| {
172 anyhow!(
173 "failed to convert path {} into a file:// URL",
174 absolute.display()
175 )
176 })
177}
178
179pub const DEFAULT_CONFIG_TOML: &str = "\
183# pond configuration.
184#
185# pond ships built-in defaults, so every setting here is optional - delete this
186# file and pond still works. Uncomment and edit to override.
187
188# Where pond looks for adapter data to import. One entry per adapter type
189# (`claude-code`, `codex-cli`, ...). `pond sync` with no arguments syncs every
190# entry; `pond sync <adapter>` syncs just one. With an empty `[adapters]`,
191# `pond sync` runs an interactive discovery against the known default paths
192# and writes the picks back here.
193#
194# Future wrap: pond is single-namespace in v1 (spec.md#wire-namespace-resolution); `[adapters]` is
195# flat here. When multi-namespace pond lands, adapter registration becomes
196# per-tenant under `[namespaces.<ns>.adapters.<adapter>]`. Pre-v1 the schema
197# is breakable; the rename is operationally free until a real second tenant
198# exists.
199#
200# [adapters.claude-code]
201# enabled = true
202# path = \"~/.claude/projects\"
203#
204# [adapters.codex-cli]
205# enabled = true
206# path = \"~/.codex/sessions\"
207#
208# Set `enabled = false` to keep the section but skip it on `pond sync`;
209# re-enable via `pond adapters enable <adapter>`.
210
211# Embeddings. Search defaults to the vector arm (matching on meaning) when the
212# store has any vectors, falling back to FTS otherwise - the model loads lazily
213# on the first vector query, so there's no cost on FTS-only corpora. `model`
214# selects the HuggingFace XLM-RoBERTa model; `dim` declares its output width and
215# is baked into the messages.vector schema on table creation - it must equal the
216# model's hidden_size.
217#
218# Common pairings:
219# model = \"intfloat/multilingual-e5-small\" dim = 384 (default)
220# model = \"intfloat/multilingual-e5-base\" dim = 768
221# model = \"intfloat/multilingual-e5-large\" dim = 1024
222#
223# A different-dim model needs a fresh data dir; pond enforces this at the
224# schema boundary.
225#
226# [embeddings]
227# model = \"intfloat/multilingual-e5-small\"
228# dim = 384
229
230# Search tuning. Leave unset for Lance defaults; set when tuning vector recall
231# against a corpus.
232#
233# [search]
234# nprobes = 16
235
236# Storage maintenance. Tunes the compaction + cleanup pass that runs inside
237# `pond sync` and `pond optimize`.
238#
239# - `compaction_fragment_cap` is the per-task fragment-count backstop: a
240# planned compaction task touching at least this many fragments always runs
241# even when the write-amplification veto would skip it. Default 64; 0
242# disables the veto and runs every task Lance plans.
243# - `cleanup_older_than` is the manifest-retention window for the safe cleanup
244# pass. Accepts `Ns` / `Nm` / `Nh` / `Nd` (default `1d`, floor `1h` - it is
245# what protects in-flight readers). Versions older than this are reclaimed
246# by Lance's OCC-coordinated GC.
247#
248# [maintenance]
249# compaction_fragment_cap = 64
250# cleanup_older_than = \"1d\"
251
252# Long-running process caps. Both accept either a plain byte count or a
253# humansize-style suffix (\"128 MiB\", \"1 GiB\"). Both are optional - leave
254# unset to let pond pick the backend-aware default:
255# local FS : index_cache = 256 MiB, metadata_cache = 128 MiB
256# remote : index_cache = 2 GiB, metadata_cache = 512 MiB
257# Lance's library defaults (6 GiB / 1 GiB) are too generous for a per-session
258# `pond mcp` process; tightening them is what keeps RSS under the 500 MiB target
259# without measurable latency regressions on typical agent-history corpora.
260#
261# [runtime]
262# index_cache_bytes = \"256 MiB\"
263# metadata_cache_bytes = \"128 MiB\"
264
265# Storage address and credentials (spec.md#storage-url-grammar).
266#
267# `path` is the default destination used when `--storage-path` (env
268# `POND_STORAGE_PATH`) is not passed. Absent = the platform-local data dir.
269# Addresses are URLs; the `s3+https` form carries the endpoint, bucket, and
270# prefix in one token:
271#
272# /abs/path or ~/path local filesystem
273# s3://bucket/prefix AWS S3 (ambient credential chain)
274# s3+https://host/bucket/prefix S3-compatible endpoint (Hetzner, R2, B2, MinIO)
275# gs://bucket/prefix Google Cloud Storage
276# az://account/container/prefix Azure Blob
277#
278# Credentials live in `[creds.<name>]` sets and bind to URLs by `scope`
279# prefix - longest match wins (spec.md#creds-scope-match); a set without
280# `scope` matches any URL. With no matching set, the standard cloud SDK
281# chain applies (AWS_* env, shared credentials file, instance metadata).
282# Secrets never go in URLs or CLI flags; besides inline values,
283# `access_key_id_file` / `secret_access_key_file` read a file and
284# `secret_access_key_command` runs a command (e.g. `op read ...`). `extra`
285# holds verbatim `object_store` options pond has not typed.
286#
287# Every field mirrors to env: `POND_STORAGE_PATH`, `POND_CREDS_<NAME>_<FIELD>`
288# (set names are lowercase alphanumeric, so the env grammar is unambiguous).
289# Precedence: CLI flag > POND_* env > this file > ambient cloud chain.
290# Probe a destination end-to-end with `pond storage check`.
291#
292# Future wrap: pond is single-namespace in v1 (spec.md#wire-namespace-resolution);
293# `[storage]` is flat here on the assumption of one bucket per pond. When
294# multi-namespace pond lands this becomes `[namespaces.<ns>.storage]`.
295#
296# [storage]
297# path = \"s3+https://nbg1.your-objectstorage.com/my-pond\"
298#
299# [creds.default]
300# access_key_id = \"...\"
301# secret_access_key = \"...\"
302";
303
304#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
306#[serde(deny_unknown_fields)]
307pub struct Config {
308 #[serde(default)]
309 pub embeddings: EmbeddingsConfig,
310 #[serde(default)]
311 pub search: SearchConfig,
312 #[serde(default)]
313 pub maintenance: MaintenanceConfig,
314 #[serde(default)]
315 pub runtime: RuntimeConfig,
316 #[serde(default)]
322 pub adapters: BTreeMap<String, Value>,
323 #[serde(default)]
326 pub storage: StorageConfig,
327 #[serde(default)]
331 pub creds: BTreeMap<String, CredsSet>,
332}
333
334#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
338#[serde(deny_unknown_fields)]
339pub struct StorageConfig {
340 #[serde(default)]
341 pub path: Option<String>,
342}
343
344#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
349#[serde(deny_unknown_fields)]
350pub struct CredsSet {
351 #[serde(default)]
353 pub scope: Option<String>,
354 #[serde(default, deserialize_with = "lenient_string")]
358 pub access_key_id: Option<String>,
359 #[serde(default)]
360 pub access_key_id_file: Option<PathBuf>,
361 #[serde(default, deserialize_with = "lenient_string")]
362 pub secret_access_key: Option<String>,
363 #[serde(default)]
364 pub secret_access_key_file: Option<PathBuf>,
365 #[serde(default)]
366 pub secret_access_key_command: Option<String>,
367 #[serde(default, deserialize_with = "lenient_string")]
368 pub region: Option<String>,
369 #[serde(default)]
370 pub virtual_hosted_style_request: Option<bool>,
371 #[serde(default)]
372 pub extra: BTreeMap<String, String>,
373}
374
375pub fn valid_creds_set_name(name: &str) -> bool {
379 let mut chars = name.chars();
380 chars.next().is_some_and(|c| c.is_ascii_lowercase())
381 && name.len() <= 16
382 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
383}
384
385pub fn creds_set_name_error(name: &str) -> String {
388 format!(
389 "creds set name {name:?} must match [a-z][a-z0-9]{{0,15}} (lowercase alphanumeric, no separators)"
390 )
391}
392
393#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
398#[serde(deny_unknown_fields, default)]
399pub struct RuntimeConfig {
400 #[serde(default, deserialize_with = "deserialize_byte_size_opt")]
401 pub index_cache_bytes: Option<usize>,
402 #[serde(default, deserialize_with = "deserialize_byte_size_opt")]
403 pub metadata_cache_bytes: Option<usize>,
404}
405
406#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
408#[serde(deny_unknown_fields)]
409pub struct SearchConfig {
410 #[serde(default)]
411 pub nprobes: Option<usize>,
412}
413
414#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
419#[serde(deny_unknown_fields)]
420pub struct MaintenanceConfig {
421 #[serde(default)]
426 pub compaction_fragment_cap: Option<usize>,
427 #[serde(default)]
432 pub cleanup_older_than: Option<String>,
433}
434
435#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
444#[serde(deny_unknown_fields, default)]
445pub struct EmbeddingsConfig {
446 pub model: String,
449 pub dim: usize,
452}
453
454impl Default for EmbeddingsConfig {
455 fn default() -> Self {
456 Self {
457 model: crate::embed::DEFAULT_MODEL_ID.to_owned(),
458 dim: crate::sessions::DEFAULT_EMBEDDING_DIM,
459 }
460 }
461}
462
463pub fn default_storage_path(xdg_data_home: Option<PathBuf>, home: Option<PathBuf>) -> Result<Url> {
469 if let Some(xdg) = xdg_data_home.filter(|path| path.is_absolute()) {
470 return url_for_path(xdg.join("pond"));
471 }
472 if let Some(home) = home {
473 return url_for_path(home.join(".local").join("share").join("pond"));
474 }
475 url_for_path(PathBuf::from(".pond"))
477}
478
479pub fn default_cache_path(xdg_cache_home: Option<PathBuf>, home: Option<PathBuf>) -> PathBuf {
483 if let Some(xdg) = xdg_cache_home.filter(|path| path.is_absolute()) {
484 return xdg.join("pond");
485 }
486 if let Some(home) = home {
487 return home.join(".cache").join("pond");
488 }
489 PathBuf::from(".pond-cache")
490}
491
492pub fn default_config_path(xdg_config_home: Option<PathBuf>, home: Option<PathBuf>) -> PathBuf {
497 if let Some(xdg) = xdg_config_home.filter(|path| path.is_absolute()) {
498 return xdg.join("pond").join("config.toml");
499 }
500 if let Some(home) = home {
501 return home.join(".config").join("pond").join("config.toml");
502 }
503 PathBuf::from(".pond.toml")
504}
505
506impl Config {
507 pub fn load(path: impl AsRef<Path>) -> Result<Self> {
515 Ok(Self::load_with_provenance(path)?.0)
516 }
517
518 pub fn load_str(body: &str) -> Result<Self> {
523 let figment = Figment::new().merge(Toml::string(body)).merge(env_mirror());
524 let config: Self = figment
525 .extract_lossy()
526 .map_err(|error| anyhow!("failed to load config: {error}"))?;
527 config.embeddings.validate()?;
528 config.validate_creds()?;
529 Ok(config)
530 }
531
532 pub fn load_with_provenance(path: impl AsRef<Path>) -> Result<(Self, Figment)> {
535 let path = path.as_ref();
536 let figment = Figment::new().merge(Toml::file(path)).merge(env_mirror());
537 let config: Self = figment.extract_lossy().map_err(|error| {
541 if let Some(recipe) = detect_legacy_storage(path) {
542 return anyhow!("{recipe}");
543 }
544 if let Some(recipe) = detect_legacy_sources(path) {
545 return anyhow!("{recipe}");
546 }
547 anyhow!("failed to load config {}: {error}", path.display())
550 })?;
551 config.embeddings.validate()?;
552 config.validate_creds()?;
553 config.embeddings.install_runtime();
554 Ok((config, figment))
558 }
559
560 fn validate_creds(&self) -> Result<()> {
565 let mut scopeless: Option<&str> = None;
566 let mut scopes: BTreeMap<String, &str> = BTreeMap::new();
567 for (name, set) in &self.creds {
568 if !valid_creds_set_name(name) {
569 bail!(creds_set_name_error(name));
570 }
571 if set.access_key_id.is_some() && set.access_key_id_file.is_some() {
572 bail!("[creds.{name}] sets both access_key_id and access_key_id_file; pick one");
573 }
574 let secret_variants = [
575 set.secret_access_key.is_some(),
576 set.secret_access_key_file.is_some(),
577 set.secret_access_key_command.is_some(),
578 ]
579 .iter()
580 .filter(|present| **present)
581 .count();
582 if secret_variants > 1 {
583 bail!(
584 "[creds.{name}] sets more than one of secret_access_key / secret_access_key_file / secret_access_key_command; pick one"
585 );
586 }
587 match set.scope.as_deref() {
588 None => {
589 if let Some(other) = scopeless {
590 bail!(
591 "[creds.{other}] and [creds.{name}] are both scope-less; at most one catch-all set is allowed - add a `scope` to one"
592 );
593 }
594 scopeless = Some(name);
595 }
596 Some(scope) => {
597 let canonical = crate::substrate::parse_scope(scope)
602 .map(|url| url.as_str().trim_end_matches('/').to_owned())
603 .with_context(|| {
604 format!("[creds.{name}] scope {scope:?} is not a valid URL prefix")
605 })?;
606 if let Some(other) = scopes.insert(canonical, name) {
607 bail!(
608 "[creds.{other}] and [creds.{name}] declare the same scope {scope:?}; merge them or narrow one"
609 );
610 }
611 }
612 }
613 }
614 Ok(())
615 }
616
617 pub fn resolve_adapters(&self, adapter: Option<&str>) -> Result<Vec<(String, Value)>> {
626 match adapter {
627 None => Ok(self
628 .adapters
629 .iter()
630 .filter_map(|(name, blob)| take_enabled(name, blob))
631 .collect()),
632 Some(name) => {
633 let blob = self
634 .adapters
635 .get(name)
636 .ok_or_else(|| anyhow!("no [adapters.{name}] entry in config"))?;
637 take_enabled(name, blob).map(|entry| vec![entry]).ok_or_else(|| {
638 anyhow!(
639 "adapter [{name}] is disabled (enabled = false); run `pond adapters enable {name}` to re-enable, then `pond sync {name}`"
640 )
641 })
642 }
643 }
644 }
645
646 pub fn disabled_adapter_names(&self) -> Vec<&str> {
651 self.adapters
652 .iter()
653 .filter_map(|(name, blob)| {
654 let enabled = blob
655 .get("enabled")
656 .and_then(Value::as_bool)
657 .unwrap_or(false);
658 if enabled { None } else { Some(name.as_str()) }
659 })
660 .collect()
661 }
662}
663
664fn env_mirror() -> Env {
670 Env::prefixed("POND_")
673 .filter(|key| {
674 let key = key.as_str().to_ascii_lowercase();
675 key == "storage_path" || (key.starts_with("creds_") && !key.ends_with("_extra"))
679 })
680 .map(|key| {
681 let key = key.as_str().to_ascii_lowercase();
685 let dots = if key.starts_with("creds_") { 2 } else { 1 };
686 key.replacen('_', ".", dots).into()
687 })
688}
689
690pub const LEGACY_ENDPOINT_KEYS: &[&str] = &["aws_endpoint", "endpoint"];
696pub const LEGACY_ACCESS_KEY_KEYS: &[&str] = &["aws_access_key_id", "access_key_id"];
697pub const LEGACY_SECRET_KEY_KEYS: &[&str] = &["aws_secret_access_key", "secret_access_key"];
698pub const LEGACY_VIRTUAL_HOSTED_KEYS: &[&str] = &[
699 "aws_virtual_hosted_style_request",
700 "virtual_hosted_style_request",
701];
702
703fn detect_legacy_storage(path: &Path) -> Option<String> {
708 let text = std::fs::read_to_string(path).ok()?;
709 let value: toml::Value = toml::from_str(&text).ok()?;
710 let storage = value.get("storage")?.as_table()?;
711 if storage.is_empty() || storage.keys().all(|key| key == "path") {
712 return None;
713 }
714 let get = |names: &[&str]| {
715 storage.iter().find_map(|(key, value)| {
716 names
717 .iter()
718 .any(|name| key.eq_ignore_ascii_case(name))
719 .then(|| value.as_str().unwrap_or_default().to_owned())
720 })
721 };
722 let endpoint = get(LEGACY_ENDPOINT_KEYS);
723 let host = endpoint
724 .as_deref()
725 .and_then(|e| e.split("://").nth(1))
726 .unwrap_or("<endpoint-host>");
727 let virtual_hosted = storage.iter().any(|(key, value)| {
731 LEGACY_VIRTUAL_HOSTED_KEYS
732 .iter()
733 .any(|name| key.eq_ignore_ascii_case(name))
734 && (value.as_bool().unwrap_or(false)
735 || value
736 .as_str()
737 .is_some_and(|text| text.eq_ignore_ascii_case("true") || text == "1"))
738 });
739 let path_recipe = match host.split_once('.') {
740 Some((bucket, rest)) if virtual_hosted && rest.contains('.') => {
741 format!("s3+https://{rest}/{bucket}/<prefix>")
742 }
743 _ => format!("s3+https://{host}/<bucket>/<prefix>"),
744 };
745 let mut recipe = format!(
748 "config {} uses the old [storage] passthrough map; rewrite it as:\n\n[storage]\npath = \"{path_recipe}\"\n\n[creds.default]\n",
749 path.display(),
750 );
751 recipe.push_str("access_key_id = \"...\" # copy from the old [storage] section\n");
752 recipe.push_str("secret_access_key = \"...\" # copy from the old [storage] section\n");
753 recipe.push_str(
754 "\n(the endpoint and bucket fold into the URL; allow_http is scheme-derived; virtual-hosted addressing defaults on; the region is autodetected - append ?region=<x> to the URL only if your store insists. `pond storage check` verifies the result end-to-end, and `pond init` can apply this rewrite for you)",
755 );
756 Some(recipe)
757}
758
759fn detect_legacy_sources(path: &Path) -> Option<String> {
764 let text = std::fs::read_to_string(path).ok()?;
765 let value: toml::Value = toml::from_str(&text).ok()?;
766 value.get("sources")?.as_table()?;
767 Some(format!(
768 "config {} uses a [sources.*] block; the adapter map was renamed to [adapters.*]. Run `pond init` to migrate it, or rename each `[sources.<name>]` header to `[adapters.<name>]` by hand.",
769 path.display(),
770 ))
771}
772
773fn take_enabled(name: &str, blob: &Value) -> Option<(String, Value)> {
777 let enabled = blob
778 .get("enabled")
779 .and_then(Value::as_bool)
780 .unwrap_or(false);
781 if !enabled {
782 return None;
783 }
784 let mut clean = blob.clone();
785 if let Some(obj) = clean.as_object_mut() {
786 obj.remove("enabled");
787 }
788 Some((name.to_owned(), clean))
789}
790
791pub fn expand_home_under(path: &Path, home: &Path) -> PathBuf {
798 let Some(text) = path.to_str() else {
799 return path.to_path_buf();
800 };
801 let home_text = home.to_string_lossy();
802 let expanded = shellexpand::full_with_context_no_errors(
803 text,
804 || Some(home_text.clone()),
805 |var| std::env::var(var).ok(),
806 );
807 PathBuf::from(expanded.as_ref())
808}
809
810pub fn contract_home_under(path: &Path, home: &Path) -> PathBuf {
815 match path.strip_prefix(home) {
816 Ok(rest) if rest.as_os_str().is_empty() => PathBuf::from("~"),
817 Ok(rest) => Path::new("~").join(rest),
818 Err(_) => path.to_path_buf(),
819 }
820}
821
822pub fn contract_home(path: &Path) -> PathBuf {
826 match std::env::var_os("HOME") {
827 Some(home) => contract_home_under(path, Path::new(&home)),
828 None => path.to_path_buf(),
829 }
830}
831
832impl EmbeddingsConfig {
833 pub fn validate(&self) -> Result<()> {
837 if self.model.trim().is_empty() {
838 bail!("embeddings.model must be a non-empty HuggingFace model id");
839 }
840 if self.dim == 0 {
841 bail!("embeddings.dim must be positive; got {}", self.dim);
842 }
843 Ok(())
844 }
845
846 pub fn install_runtime(&self) {
850 crate::embed::init_model_id(self.model.clone());
851 crate::sessions::init_embedding_dim(self.dim);
852 }
853}
854
855pub fn write_config_file(path: &Path, contents: &str) -> Result<()> {
862 #[cfg(unix)]
863 {
864 use std::io::Write as _;
865 use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
866 let mut file = std::fs::OpenOptions::new()
867 .write(true)
868 .create(true)
869 .truncate(true)
870 .mode(0o600)
871 .open(path)
872 .with_context(|| format!("failed to write {}", path.display()))?;
873 file.set_permissions(std::fs::Permissions::from_mode(0o600))
875 .with_context(|| format!("failed to chmod 0600 {}", path.display()))?;
876 file.write_all(contents.as_bytes())
877 .with_context(|| format!("failed to write {}", path.display()))?;
878 }
879 #[cfg(not(unix))]
880 {
881 std::fs::write(path, contents)
882 .with_context(|| format!("failed to write {}", path.display()))?;
883 }
884 Ok(())
885}
886
887#[cfg(test)]
888mod tests {
889 #![allow(clippy::expect_used, clippy::unwrap_used, clippy::result_large_err)]
892
893 use super::*;
894 use serde_json::Value;
895 use tempfile::TempDir;
896
897 #[test]
898 fn local_path_resolves_both_local_schemes() {
899 let plain = Url::parse("file:///tmp/pond-store").unwrap();
900 assert_eq!(local_path(&plain), Some(PathBuf::from("/tmp/pond-store")));
901 let uring = Url::parse("file+uring:///tmp/pond-store").unwrap();
902 assert_eq!(local_path(&uring), Some(PathBuf::from("/tmp/pond-store")));
903 assert_eq!(local_path(&Url::parse("s3://bucket/prefix").unwrap()), None);
904 }
905
906 #[cfg(unix)]
907 #[test]
908 fn write_config_file_is_owner_only_0600() {
909 use std::os::unix::fs::PermissionsExt;
910 let dir = TempDir::new().unwrap();
911 let path = dir.path().join("config.toml");
912 std::fs::write(&path, "old").unwrap();
914 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
915 write_config_file(&path, "[creds.default]\nsecret_access_key = \"x\"\n").unwrap();
916 let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
917 assert_eq!(mode, 0o600, "config with secrets must be owner-only");
918 assert!(
919 std::fs::read_to_string(&path)
920 .unwrap()
921 .contains("secret_access_key")
922 );
923 }
924
925 #[test]
926 fn validate_catches_empty_model_and_bad_dim() {
927 assert!(EmbeddingsConfig::default().validate().is_ok());
928 let bad_model = EmbeddingsConfig {
931 model: " ".to_owned(),
932 dim: 768,
933 };
934 assert!(bad_model.validate().is_err());
935 let odd_dim = EmbeddingsConfig {
938 model: "intfloat/multilingual-e5-base".to_owned(),
939 dim: 100,
940 };
941 assert!(odd_dim.validate().is_ok());
942 let zero_dim = EmbeddingsConfig {
944 model: "intfloat/multilingual-e5-base".to_owned(),
945 dim: 0,
946 };
947 assert!(zero_dim.validate().is_err());
948 }
949
950 #[test]
955 fn config_load_missing_file_falls_back_to_builtin() {
956 figment::Jail::expect_with(|_jail| {
957 let config = Config::load("/nonexistent/pond-config-xyz.toml").unwrap();
958 assert_eq!(config.embeddings, EmbeddingsConfig::default());
959 Ok(())
960 });
961 }
962
963 #[test]
964 fn default_config_toml_loads_to_the_builtin_defaults() {
965 figment::Jail::expect_with(|jail| {
966 jail.create_file("config.toml", DEFAULT_CONFIG_TOML)?;
967 let config = Config::load("config.toml").unwrap();
970 assert_eq!(config.embeddings, EmbeddingsConfig::default());
971 assert_eq!(config.embeddings.model, crate::embed::DEFAULT_MODEL_ID);
972 assert_eq!(
973 config.embeddings.dim,
974 crate::sessions::DEFAULT_EMBEDDING_DIM
975 );
976 Ok(())
977 });
978 }
979
980 #[test]
981 fn default_storage_path_follows_xdg_then_home() {
982 let resolved =
984 default_storage_path(Some(PathBuf::from("/xdg")), Some(PathBuf::from("/home")))
985 .unwrap();
986 assert!(is_local(&resolved));
987 assert_eq!(local_path(&resolved).unwrap(), PathBuf::from("/xdg/pond"));
988
989 let resolved = default_storage_path(
991 Some(PathBuf::from("relative")),
992 Some(PathBuf::from("/home")),
993 )
994 .unwrap();
995 assert_eq!(
996 local_path(&resolved).unwrap(),
997 PathBuf::from("/home/.local/share/pond"),
998 );
999
1000 let resolved = default_storage_path(None, None).unwrap();
1004 assert!(is_local(&resolved));
1005 assert!(
1006 local_path(&resolved).unwrap().ends_with(".pond"),
1007 "fallback path should end with .pond: {resolved}",
1008 );
1009 }
1010
1011 #[test]
1012 fn expand_home_under_handles_tilde_forms() {
1013 let home = Path::new("/srv/me");
1014 assert_eq!(
1015 expand_home_under(Path::new("~"), home),
1016 PathBuf::from("/srv/me")
1017 );
1018 assert_eq!(
1019 expand_home_under(Path::new("~/.codex/sessions"), home),
1020 PathBuf::from("/srv/me/.codex/sessions"),
1021 );
1022 assert_eq!(
1024 expand_home_under(Path::new("/etc/passwd"), home),
1025 PathBuf::from("/etc/passwd"),
1026 );
1027 assert_eq!(
1029 expand_home_under(Path::new("~user/elsewhere"), home),
1030 PathBuf::from("~user/elsewhere"),
1031 );
1032 }
1033
1034 #[test]
1035 fn expand_home_under_handles_env_vars() {
1036 figment::Jail::expect_with(|jail| {
1038 jail.set_env("POND_TEST_EXPAND_DIR", "/srv/data");
1039 let home = Path::new("/srv/me");
1040 assert_eq!(
1041 expand_home_under(Path::new("$POND_TEST_EXPAND_DIR/pond"), home),
1042 PathBuf::from("/srv/data/pond"),
1043 );
1044 assert_eq!(
1045 expand_home_under(Path::new("${POND_TEST_EXPAND_DIR}/pond"), home),
1046 PathBuf::from("/srv/data/pond"),
1047 );
1048 assert_eq!(
1050 expand_home_under(Path::new("$POND_TEST_UNSET_VAR/x"), home),
1051 PathBuf::from("$POND_TEST_UNSET_VAR/x"),
1052 );
1053 Ok(())
1054 });
1055 }
1056
1057 #[test]
1058 fn contract_home_under_inverts_expansion() {
1059 let home = Path::new("/srv/me");
1060 assert_eq!(
1061 contract_home_under(Path::new("/srv/me/.local/share/pond"), home),
1062 PathBuf::from("~/.local/share/pond"),
1063 );
1064 assert_eq!(
1065 contract_home_under(Path::new("/srv/me"), home),
1066 PathBuf::from("~")
1067 );
1068 assert_eq!(
1070 contract_home_under(Path::new("/etc/passwd"), home),
1071 PathBuf::from("/etc/passwd"),
1072 );
1073 }
1074
1075 #[test]
1076 fn resolve_adapters_returns_one_or_all_or_errors() {
1077 figment::Jail::expect_with(|jail| {
1078 jail.create_file(
1079 "config.toml",
1080 "\
1081[adapters.claude-code]
1082enabled = true
1083path = \"/srv/claude\"
1084
1085[adapters.codex-cli]
1086enabled = true
1087path = \"/srv/codex\"
1088
1089[adapters.opencode]
1090enabled = false
1091",
1092 )?;
1093 let config = Config::load("config.toml").unwrap();
1094
1095 let all = config.resolve_adapters(None).unwrap();
1097 assert_eq!(all.len(), 2);
1098 let names: Vec<_> = all.iter().map(|(n, _)| n.as_str()).collect();
1099 assert!(names.contains(&"claude-code"));
1100 assert!(names.contains(&"codex-cli"));
1101 for (_, blob) in &all {
1103 assert!(blob.get("enabled").is_none(), "enabled should be stripped");
1104 }
1105
1106 let one = config.resolve_adapters(Some("codex-cli")).unwrap();
1108 assert_eq!(one.len(), 1);
1109 assert_eq!(one[0].0, "codex-cli");
1110 assert_eq!(
1111 one[0].1.get("path").and_then(Value::as_str),
1112 Some("/srv/codex"),
1113 );
1114
1115 let disabled = config.resolve_adapters(Some("opencode"));
1117 let err = disabled
1118 .expect_err("disabled adapter must error")
1119 .to_string();
1120 assert!(err.contains("enabled = false"), "got: {err}");
1121 assert!(err.contains("pond sync opencode"), "got: {err}");
1122
1123 assert!(config.resolve_adapters(Some("nope")).is_err());
1125
1126 assert_eq!(config.disabled_adapter_names(), vec!["opencode"]);
1128 Ok(())
1129 });
1130 }
1131
1132 #[test]
1133 fn memory_uri_is_classified_as_remote() {
1134 let url = Url::parse("memory:///pond-remote-test").expect("memory uri parses");
1135 assert!(
1136 !is_local(&url),
1137 "memory:// is not a local-filesystem URL: {url}",
1138 );
1139 assert!(
1140 local_path(&url).is_none(),
1141 "local_path must return None for non-file schemes",
1142 );
1143 }
1144
1145 #[test]
1150 fn storage_and_creds_round_trip() {
1151 figment::Jail::expect_with(|jail| {
1152 jail.create_file(
1153 "config.toml",
1154 r#"
1155[storage]
1156path = "s3+https://nbg1.example.com/my-pond"
1157
1158[creds.default]
1159access_key_id = "AKIA123"
1160secret_access_key = "shh"
1161
1162[creds.work]
1163scope = "s3+https://fsn1.example.com/work-pond/"
1164access_key_id = "AKIA456"
1165secret_access_key_command = "op read op://vault/pond/secret"
1166region = "fsn1"
1167virtual_hosted_style_request = false
1168extra = { request_timeout = "60 seconds" }
1169"#,
1170 )?;
1171 let config = Config::load("config.toml").expect("config loads");
1172 assert_eq!(
1173 config.storage.path.as_deref(),
1174 Some("s3+https://nbg1.example.com/my-pond"),
1175 );
1176 assert_eq!(config.creds.len(), 2);
1177 let work = &config.creds["work"];
1178 assert_eq!(
1179 work.secret_access_key_command.as_deref(),
1180 Some("op read op://vault/pond/secret"),
1181 );
1182 assert_eq!(work.virtual_hosted_style_request, Some(false));
1183 assert_eq!(work.extra["request_timeout"], "60 seconds");
1184 Ok(())
1185 });
1186 }
1187
1188 #[test]
1189 fn creds_validators_reject_bad_shapes() {
1190 let cases: &[(&str, &str)] = &[
1191 ("[creds.a]\nacces_key_id = \"x\"\n", "acces_key_id"),
1193 ("[creds.my_set]\naccess_key_id = \"x\"\n", "[a-z][a-z0-9]"),
1195 ("[creds.A1]\naccess_key_id = \"x\"\n", "[a-z][a-z0-9]"),
1196 (
1198 "[creds.a]\nsecret_access_key = \"x\"\nsecret_access_key_command = \"cat\"\n",
1199 "more than one",
1200 ),
1201 (
1202 "[creds.a]\naccess_key_id = \"x\"\naccess_key_id_file = \"/k\"\n",
1203 "pick one",
1204 ),
1205 (
1207 "[creds.a]\naccess_key_id = \"x\"\n[creds.b]\naccess_key_id = \"y\"\n",
1208 "scope-less",
1209 ),
1210 (
1213 "[creds.a]\nscope = \"s3+https://h:443/b/\"\naccess_key_id = \"x\"\n[creds.b]\nscope = \"s3+https://h/b\"\naccess_key_id = \"y\"\n",
1214 "same scope",
1215 ),
1216 ];
1217 figment::Jail::expect_with(|jail| {
1218 for (body, needle) in cases {
1219 jail.create_file("config.toml", body)?;
1220 let err = Config::load("config.toml").expect_err(body).to_string();
1221 assert!(
1222 err.contains(needle),
1223 "want {needle:?} in error for {body:?}, got: {err}",
1224 );
1225 }
1226 Ok(())
1227 });
1228 }
1229
1230 #[test]
1231 fn valid_creds_set_name_matches_env_mirror_charset() {
1232 for ok in ["default", "work", "work2", "a", "abcdefghij123456"] {
1233 assert!(valid_creds_set_name(ok), "{ok:?} should be valid");
1234 }
1235 for bad in ["", "Work", "my_set", "2fast", "abcdefghij1234567", "set-1"] {
1236 assert!(!valid_creds_set_name(bad), "{bad:?} should be invalid");
1237 }
1238 }
1239
1240 #[test]
1241 fn legacy_storage_map_errors_with_the_rewrite_recipe() {
1242 figment::Jail::expect_with(|jail| {
1243 jail.create_file(
1244 "config.toml",
1245 r#"
1246[storage]
1247AWS_ACCESS_KEY_ID = "AKIA123"
1248AWS_SECRET_ACCESS_KEY = "shh"
1249AWS_REGION = "nbg1"
1250AWS_ENDPOINT = "https://ttq.nbg1.your-objectstorage.com"
1251aws_virtual_hosted_style_request = "true"
1252"#,
1253 )?;
1254 let err = Config::load("config.toml")
1255 .expect_err("legacy map must error")
1256 .to_string();
1257 assert!(err.contains("old [storage] passthrough map"), "got: {err}");
1259 assert!(
1263 err.contains("s3+https://nbg1.your-objectstorage.com/ttq/<prefix>"),
1264 "recipe must de-fold the virtual-hosted endpoint, got: {err}",
1265 );
1266 assert!(!err.contains("AKIA123"), "got: {err}");
1269 assert!(!err.contains("\"shh\""), "got: {err}");
1270 assert!(err.contains("access_key_id = \"...\""), "got: {err}");
1271 assert!(!err.contains("region ="), "got: {err}");
1275 assert!(err.contains("?region="), "got: {err}");
1276 assert!(err.contains("pond storage check"), "got: {err}");
1277 jail.create_file(
1280 "config.toml",
1281 r#"
1282[storage]
1283AWS_ACCESS_KEY_ID = "AKIA123"
1284AWS_ENDPOINT = "https://ttq.nbg1.your-objectstorage.com"
1285"#,
1286 )?;
1287 let err = Config::load("config.toml")
1288 .expect_err("legacy map must error")
1289 .to_string();
1290 assert!(
1291 err.contains("s3+https://ttq.nbg1.your-objectstorage.com/<bucket>/<prefix>"),
1292 "got: {err}",
1293 );
1294 Ok(())
1295 });
1296 }
1297
1298 #[test]
1299 fn legacy_sources_block_errors_with_the_adapters_recipe() {
1300 figment::Jail::expect_with(|jail| {
1301 jail.create_file(
1302 "config.toml",
1303 "[sources.claude-code]\nenabled = true\npath = \"/srv/claude\"\n",
1304 )?;
1305 let err = Config::load("config.toml")
1306 .expect_err("legacy [sources.*] must error")
1307 .to_string();
1308 assert!(err.contains("[adapters.*]"), "names the new key: {err}");
1309 assert!(err.contains("pond init"), "points at the fix: {err}");
1310 Ok(())
1311 });
1312 }
1313
1314 #[test]
1315 fn env_mirror_layers_over_file() {
1316 figment::Jail::expect_with(|jail| {
1317 jail.create_file(
1318 "config.toml",
1319 r#"
1320[storage]
1321path = "/from-file"
1322
1323[creds.work]
1324scope = "s3://file-bucket/"
1325access_key_id = "from-file"
1326region = "file-region"
1327"#,
1328 )?;
1329 jail.set_env("POND_STORAGE_PATH", "/from-env");
1331 jail.set_env("POND_CREDS_WORK_ACCESS_KEY_ID", "from-env");
1332 jail.set_env("POND_CREDS_WORK_SECRET_ACCESS_KEY", "12345");
1334 jail.set_env("POND_CREDS_CI_ACCESS_KEY_ID", "ci-key");
1336 let config = Config::load("config.toml").expect("env+file config loads");
1337 assert_eq!(config.storage.path.as_deref(), Some("/from-env"));
1338 let work = &config.creds["work"];
1339 assert_eq!(work.access_key_id.as_deref(), Some("from-env"));
1340 assert_eq!(work.secret_access_key.as_deref(), Some("12345"));
1341 assert_eq!(work.region.as_deref(), Some("file-region"));
1342 assert_eq!(work.scope.as_deref(), Some("s3://file-bucket/"));
1343 assert_eq!(config.creds["ci"].access_key_id.as_deref(), Some("ci-key"));
1344 Ok(())
1345 });
1346 }
1347}