Skip to main content

pond/
config.rs

1//! Configuration loading: the `[embeddings]`, `[adapters]`, `[storage]`, and
2//! `[creds.*]` blocks.
3//!
4//! pond ships built-in defaults, so an instance with no `config.toml` still
5//! works. `pond config schema` emits [`DEFAULT_CONFIG_TOML`], the
6//! fully-annotated example. Loading layers `config.toml` under the `POND_*`
7//! env mirror via figment, so every command also works with no config file
8//! at all (spec.md#storage-configless) - URLs + env vars are sufficient.
9
10use 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
24/// Parse `"128 MiB"`, `"1 GiB"`, `"500 KiB"`, or a bare byte count. Accepts
25/// SI (KB/MB/GB) and binary (KiB/MiB/GiB/TiB) suffixes; treats the bare unit
26/// `"B"` and unsuffixed numbers as raw bytes. Tolerant of whitespace and
27/// case. The result MUST fit in `usize` (Lance's cache APIs take `usize`).
28fn 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
66/// Accept string / integer / float / bool and stringify. The env mirror
67/// parses values TOML-ishly, so `POND_CREDS_X_SECRET_ACCESS_KEY=12345`
68/// arrives as a number; these fields are strings no matter how they scan.
69fn 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
109/// True when the URL is on the local filesystem. Mirrors Lance's
110/// `ObjectStore::is_local` (lance-io/src/object_store.rs:541): the `file` and
111/// `file+uring` schemes are local; everything else (incl. `memory://`) is not.
112pub fn is_local(url: &Url) -> bool {
113    matches!(url.scheme(), "file" | "file+uring")
114}
115
116/// Extract the filesystem `PathBuf` for local URLs. `None` for remote.
117pub fn local_path(url: &Url) -> Option<PathBuf> {
118    if !is_local(url) {
119        return None;
120    }
121    // `Url::to_file_path` only accepts the `file` scheme, and `set_scheme`
122    // can't cross the special/non-special boundary - rebuild `file+uring`
123    // URLs as `file` textually.
124    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
133/// URI string for a child of this location (typically one Lance dataset under
134/// the data dir). Trims a single trailing slash on the base, then concatenates
135/// with a `/` separator. This keeps `Dataset::open` / `Dataset::write` happy
136/// on both filesystem and object-store backends - they want the URI form, not
137/// a `url::Url`.
138pub fn child_uri(base: &Url, suffix: &str) -> String {
139    // For local URLs we strip the `file://` prefix so log lines and error
140    // messages render as plain paths (`/srv/pond/sessions.lance`), matching
141    // what pond used to emit before the URL migration.
142    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
148/// Render a `Url` for human-readable log/diagnostic output: local URLs come
149/// back as plain paths (no `file://` prefix, `$HOME` contracted to `~`);
150/// remote URLs stay verbatim.
151pub 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
159/// Build a `Url` from a filesystem path. Convenience for tests and for
160/// callers that hold a `PathBuf` already. The path must be
161/// absolute (`url::Url::from_file_path` is a hard requirement on Unix); a
162/// relative path gets canonicalized via `std::path::absolute` first.
163pub 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
179/// Default `config.toml` body emitted by `pond config schema`. Every
180/// line is commented: pond ships built-in defaults, so the file is purely a
181/// discoverable template and pond still works with no `config.toml` on disk.
182pub 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/// Top-level `config.toml` shape.
305#[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    /// `[adapters.<adapter>]` map: per-adapter config blobs the matching
317    /// factory deserializes inside its `open()`. The shape is adapter-defined
318    /// (filesystem adapters expect `{ path = "..." }`; API-backed adapters
319    /// expect endpoint + auth keys), so this layer stays opaque. Empty by
320    /// default; `pond sync` runs discovery into this map on first use.
321    #[serde(default)]
322    pub adapters: BTreeMap<String, Value>,
323    /// `[storage]`: the default destination URL (spec.md#storage-url-grammar).
324    /// `None` = the platform-local data dir.
325    #[serde(default)]
326    pub storage: StorageConfig,
327    /// `[creds.<name>]`: URL-scoped credential sets. Every storage URL
328    /// resolves its own set by longest-prefix `scope` match
329    /// (spec.md#creds-scope-match); the resolver lives in `pond::substrate`.
330    #[serde(default)]
331    pub creds: BTreeMap<String, CredsSet>,
332}
333
334/// `[storage]`: the single default destination. Typed so the legacy
335/// passthrough map (ENV-style `object_store` keys) fails loudly with the
336/// rewrite recipe instead of silently changing meaning.
337#[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/// One `[creds.<name>]` set. All fields optional; validation enforces at most
345/// one variant per logical secret. `extra` carries verbatim `object_store`
346/// options pond has not typed (redaction in `pond config show` still applies
347/// to its keys by name).
348#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
349#[serde(deny_unknown_fields)]
350pub struct CredsSet {
351    /// URL prefix this set binds to. `None` = the catch-all set (at most one).
352    #[serde(default)]
353    pub scope: Option<String>,
354    // Key / region fields are `lenient_string`: the env mirror parses values
355    // TOML-ishly, so an all-digit key or region arrives as a number and must
356    // still land in these String fields.
357    #[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
375/// `[creds.<name>]` name charset `[a-z][a-z0-9]{0,15}` (spec.md#storage-env-mirror):
376/// lowercase-alphanumeric keeps `POND_CREDS_<NAME>_<FIELD>` splittable at the
377/// first `_` after the name. Shared by config validation and `pond creds`.
378pub 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
385/// The rejection message for a name that fails [`valid_creds_set_name`], shared
386/// by config validation and `pond creds` so the rule and its wording never drift.
387pub 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/// `[runtime]`: long-running process caps. Both knobs accept either a plain
394/// byte count or a `humansize`-style suffix (`"128 MiB"`, `"1 GiB"`). Both are
395/// optional - `None` lets `pond::substrate` pick the backend-aware default
396/// (local FS gets a tight cap; object stores stay near Lance's defaults).
397#[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/// `[search]`: optional Lance vector-query tuning knobs.
407#[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/// `[maintenance]`: storage-maintenance knobs shared by `pond sync` and
415/// `pond optimize`. All optional - omit and pond falls back to the
416/// in-process defaults in `pond::substrate` (`DEFAULT_COMPACTION_FRAGMENT_CAP`,
417/// `default_cleanup_older_than`).
418#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
419#[serde(deny_unknown_fields)]
420pub struct MaintenanceConfig {
421    /// Sub-target fragment count past which the compaction phase runs (it also
422    /// runs once those fragments hold a whole target fragment's worth of rows).
423    /// Default 64 stops the automated sync re-compacting the trailing fragment
424    /// every pass; 0 compacts every pass.
425    #[serde(default)]
426    pub compaction_fragment_cap: Option<usize>,
427    /// Manifest-retention window for the safe cleanup pass. Accepts
428    /// `Ns`/`Nm`/`Nh`/`Nd` (default `1d`). Versions older than this are
429    /// reclaimed by Lance's OCC-coordinated GC (`delete_unverified=false`),
430    /// which never races a concurrent writer on any backend.
431    #[serde(default)]
432    pub cleanup_older_than: Option<String>,
433}
434
435/// `[embeddings]`: model selector and vector dimension. There is no master
436/// switch - a `vector` search degrades to FTS when no vectors exist in the
437/// store (`has_embeddings()` is the only gate); the candle/Metal model is
438/// `LazyEmbedder`-loaded on the first query that
439/// actually needs it. `model` and `dim` are installed into the process at
440/// startup via `embed::init_model_id` / `sessions::init_embedding_dim`, so
441/// swapping models for a one-off experiment is a temporary config file - no
442/// CLI flag and no per-call-site plumbing.
443#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
444#[serde(deny_unknown_fields, default)]
445pub struct EmbeddingsConfig {
446    /// The embedding model id (spec.md#search): any XLM-RoBERTa model loadable
447    /// by `candle-transformers`. Defaults to `intfloat/multilingual-e5-small`.
448    pub model: String,
449    /// Output dimension of `model`. Must equal the model's `hidden_size`.
450    /// Defaults to 384 (e5-small). Set to 768 for e5-base, 1024 for e5-large.
451    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
463/// The platform-local default storage path, used when neither
464/// `--storage-path` / `POND_STORAGE_PATH` nor `[storage].path` is set:
465/// `$XDG_DATA_HOME/pond`, then `$HOME/.local/share/pond`, then `.pond`.
466/// `xdg_data_home` is honored only if absolute, per the XDG base-directory
467/// spec.
468pub 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    // No HOME and no usable XDG var - stay usable rather than panic.
476    url_for_path(PathBuf::from(".pond"))
477}
478
479/// Cache dir for rebuildable artifacts (the search row meta map): the XDG-cache
480/// analog of [`default_storage_path`]. Separate root because the contents are
481/// regenerated from the store, not durable data.
482pub 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
492/// Local default path for `config.toml`. URI-backed data dirs always land
493/// here because the config file has to be local (it names the bucket and
494/// any creds). XDG hierarchy: `$XDG_CONFIG_HOME/pond/config.toml`, then
495/// `$HOME/.config/pond/config.toml`, then `.pond.toml` in cwd.
496pub 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    /// Load `config.toml` from `path` (if it exists) layered under the
508    /// `POND_*` env mirror, and validate. A missing file yields the built-in
509    /// defaults - env vars alone are a complete config
510    /// (spec.md#storage-configless). On success the resolved embedding model
511    /// id + dim are installed into the process (`OnceLock`-backed; only the
512    /// first call per process sticks), so all downstream code paths see a
513    /// consistent pair without per-handler plumbing.
514    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
515        Ok(Self::load_with_provenance(path)?.0)
516    }
517
518    /// [`Config::load`] over an in-memory TOML body (still layered under the
519    /// `POND_*` env mirror). `pond init` uses this to validate and resolve
520    /// the config it is composing BEFORE anything touches disk - the wizard
521    /// writes exactly once, at the end.
522    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    /// [`Config::load`] that also returns the figment, so `pond config show`
533    /// can attribute each value to its source layer (file / env / default).
534    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        // `extract_lossy`, not `extract`: env values parse TOML-ishly, so an
538        // all-digit secret would arrive as a number and fail the String field;
539        // lossy stringifies scalars instead.
540        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            // Inline figment's message (it already names the failing key and
548            // source layer) so single-line error surfaces keep the detail.
549            anyhow!("failed to load config {}: {error}", path.display())
550        })?;
551        config.embeddings.validate()?;
552        config.validate_creds()?;
553        config.embeddings.install_runtime();
554        // Tilde expansion is per-adapter (inside each factory's `open()`):
555        // an API-backed adapter has no path to expand, and only the
556        // filesystem-shaped adapters need the helper. See `expand_home_under`.
557        Ok((config, figment))
558    }
559
560    /// `[creds.*]` structural rules (spec.md#creds-scope-match): set-name
561    /// charset, at most one variant per logical secret, at most one
562    /// scope-less set, no duplicate scopes. All parse-time so a misbinding
563    /// dies before any URL resolves against it.
564    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                    // Duplicates are checked on the canonical form (incl.
598                    // trailing-slash trim, matching scope-match semantics),
599                    // so two spellings of one prefix can never tie at
600                    // resolve time.
601                    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    /// Resolve the `[adapters.<adapter>]` entries to drive `pond sync`. Only
618    /// sections with `enabled = true` flow through; sections with
619    /// `enabled = false` (or absent) are treated as opt-out and the
620    /// per-adapter blob (minus `enabled`) is handed to the factory's
621    /// `open()`. With `adapter = None` returns every enabled entry; with
622    /// `Some(name)` returns just that one - and errors if it's not in
623    /// config OR if it's currently disabled (the caller should then
624    /// re-prompt or report).
625    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    /// Names that are configured but currently `enabled = false`. Used by
647    /// `pond sync` post-import to know not to re-probe an adapter the user
648    /// already declined (the decline persists; re-prompt only via the
649    /// positional override `pond sync <name>`).
650    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
664/// The `POND_*` env mirror (spec.md#storage-env-mirror): `POND_STORAGE_PATH`
665/// -> `storage.path`, `POND_CREDS_<NAME>_<FIELD>` -> `creds.<name>.<field>`.
666/// Filtered to exactly those two shapes - clap owns its own `POND_*` vars
667/// (`POND_CONFIG_FILE`, `POND_HOST`, ...) and an unfiltered prefix would turn each
668/// of them into an unknown-field error here.
669fn env_mirror() -> Env {
670    // Keys reach these closures pre-lowercasing (`CREDS_...`), so compare on
671    // an ascii-lowered copy; `str::starts_with` is case-sensitive.
672    Env::prefixed("POND_")
673        .filter(|key| {
674            let key = key.as_str().to_ascii_lowercase();
675            // `extra` has no env form (spec.md#storage-env-mirror): the env
676            // grammar stays flat strings; structured options belong in the
677            // file (or URL query params).
678            key == "storage_path" || (key.starts_with("creds_") && !key.ends_with("_extra"))
679        })
680        .map(|key| {
681            // Set names are lowercase alphanumeric (validate_creds), so the
682            // first `_` after `creds` and the one after the name are the only
683            // separators; field names keep their underscores.
684            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
690/// The pre-redesign `[storage]` passthrough keys, by role (ENV-style
691/// `object_store` aliases). Both the load-time error recipe
692/// (`detect_legacy_storage`) and the `pond init` rewrite read these, so the
693/// legacy vocabulary lives in one place - a new alias must not require
694/// editing two detectors in lockstep.
695pub 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
703/// Recognize the pre-redesign `[storage]` passthrough map (ENV-style
704/// `object_store` keys) and return the exact rewrite onto `[storage].path` +
705/// `[creds.default]`. An error with a recipe, not a shim: old configs do not
706/// keep working.
707fn 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    // Under the declared virtual-hosted style the endpoint host leads with
728    // the bucket; de-fold it, or following the recipe verbatim folds the
729    // bucket in twice (the new grammar re-applies virtual hosting).
730    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    // spec.md#storage-redaction: never echo credential values, even back to
746    // their owner - stderr lands in logs, scrollback, and pasted bug reports.
747    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
759/// Recognize a pre-rename `[sources.<name>]` config block (the adapter map was
760/// renamed `sources` -> `adapters`) and return a one-line recipe pointing at
761/// `pond init`. An error with a recipe, not a shim: old configs do not silently
762/// keep working. Transitional - delete once live configs have migrated.
763fn 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
773/// Inner helper: return `Some((name, blob))` when the adapter section is
774/// enabled, stripping the discriminator from the blob before handing it on;
775/// `None` when the section is missing `enabled` or has `enabled = false`.
776fn 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
791/// Expand `~` and `$VAR`/`${VAR}` in `path` against an explicit `home`.
792/// Filesystem-shaped adapters call this from inside their factory's `open()`.
793/// Tests use it directly to exercise the rule without mutating the
794/// process-wide `HOME` env var (`std::env::set_var` is `unsafe` under
795/// edition 2024 and pond forbids unsafe code). Unset vars and `~user` forms
796/// pass through unchanged - never guess.
797pub 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
810/// The inverse of [`expand_home_under`] for display and config writes:
811/// contract a `home` prefix back to `~` so user-facing surfaces (and the
812/// paths `pond init` persists) stay portable and readable. Non-home paths
813/// pass through unchanged.
814pub 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
822/// [`contract_home_under`] against the process `HOME`. Returns the input
823/// rendered for humans; machine surfaces (JSON output, the wire) keep
824/// absolute paths.
825pub 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    /// Surface-level validation: model id non-empty and dim positive. The
834    /// dim/model mismatch is the load-time check inside `CandleEmbedder::load`,
835    /// which knows the model's `hidden_size`.
836    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    /// Install model id + dim into the process. Idempotent: only the first
847    /// call sticks (matches `OnceLock` semantics in `embed::init_model_id` and
848    /// `sessions::init_embedding_dim`).
849    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
855/// Write `config.toml` with owner-only perms (0600). The file can carry a
856/// plaintext `secret_access_key` (inline `[creds.*]`), so it must never be
857/// group/world-readable - matching the AWS CLI's 0600 on its credentials file.
858/// Unix only; Windows is out of v1 scope. Order is truncate -> chmod -> write,
859/// so the secret is only ever written once perms are already 0600, even when
860/// repairing a pre-existing 0644 file.
861pub 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        // `.mode()` applies only on creation; chmod also repairs a pre-existing file.
874        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    // `result_large_err`: `figment::Jail` closures return `figment::Error`
890    // by contract; the size is figment's, not ours.
891    #![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        // A pre-existing world-readable file must be repaired, not left at 0644.
913        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        // Empty / whitespace-only model id is rejected: HuggingFace fetch
929        // would fail far away from the config error.
930        let bad_model = EmbeddingsConfig {
931            model: "   ".to_owned(),
932            dim: 768,
933        };
934        assert!(bad_model.validate().is_err());
935        // Non-multiple-of-8 dims are accepted now: IVF_SQ has no subspace
936        // stride, so the old `dim % 8` requirement is gone.
937        let odd_dim = EmbeddingsConfig {
938            model: "intfloat/multilingual-e5-base".to_owned(),
939            dim: 100,
940        };
941        assert!(odd_dim.validate().is_ok());
942        // Zero is still rejected.
943        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    // Every `Config::load` reads the process-global POND_* env mirror, so any
951    // test that calls it must hold the Jail lock - otherwise `env_mirror_layers_
952    // over_file`'s POND_CREDS_* vars leak in mid-load from a parallel thread and
953    // the load fails validation (two scope-less creds sets). Jail is the lock.
954    #[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            // The shipped template is all comments, so it must load and validate as
968            // the built-in defaults - a malformed template fails right here.
969            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        // An absolute XDG_DATA_HOME wins.
983        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        // A relative XDG_DATA_HOME is ignored per the XDG spec; HOME is the fallback.
990        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        // No XDG and no HOME - stays usable: returns the cwd-anchored `.pond`.
1001        // The result is absolute (Lance's URL conversion requires it), so we
1002        // just check that the URL ends with the relative path's components.
1003        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        // Absolute paths pass through unchanged.
1023        assert_eq!(
1024            expand_home_under(Path::new("/etc/passwd"), home),
1025            PathBuf::from("/etc/passwd"),
1026        );
1027        // A leading `~something` (no slash) is not the home form - leave it.
1028        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        // Jail serializes env mutation against the other env-touching tests.
1037        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            // Unset vars pass through unchanged - never guess.
1049            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        // Non-home paths pass through unchanged.
1069        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            // None -> only enabled entries
1096            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            // The `enabled` discriminator never reaches the adapter blob.
1102            for (_, blob) in &all {
1103                assert!(blob.get("enabled").is_none(), "enabled should be stripped");
1104            }
1105
1106            // Some(name) -> one entry, opaque JSON blob
1107            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            // Disabled positional -> errors with the recovery hint baked in.
1116            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            // Unknown -> error
1124            assert!(config.resolve_adapters(Some("nope")).is_err());
1125
1126            // disabled_adapter_names lists exactly the off ones.
1127            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    // The storage/creds tests run inside `figment::Jail` even when they set
1146    // no env vars: the Jail-based env-mirror test mutates process-global env
1147    // mid-flight, and the Jail lock is what serializes them against it.
1148
1149    #[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            // Unknown key dies loudly (typos must not silently no-op).
1192            ("[creds.a]\nacces_key_id = \"x\"\n", "acces_key_id"),
1193            // Name charset: separators break the env-mirror grammar.
1194            ("[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            // One variant per logical secret.
1197            (
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            // At most one scope-less set.
1206            (
1207                "[creds.a]\naccess_key_id = \"x\"\n[creds.b]\naccess_key_id = \"y\"\n",
1208                "scope-less",
1209            ),
1210            // Duplicate scopes can never tie-break - checked canonicalized,
1211            // so two spellings of one prefix still collide.
1212            (
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            // The error IS the migration: old keys mapped onto the new shape.
1258            assert!(err.contains("old [storage] passthrough map"), "got: {err}");
1259            // The declared virtual-hosted style pins the bucket as the leading
1260            // host label; the recipe must de-fold it, not repeat the folded
1261            // host (which the new grammar would fold again).
1262            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            // spec.md#storage-redaction: the recipe must NOT echo the real
1267            // key values - placeholders plus a "copy from" pointer only.
1268            assert!(!err.contains("AKIA123"), "got: {err}");
1269            assert!(!err.contains("\"shh\""), "got: {err}");
1270            assert!(err.contains("access_key_id     = \"...\""), "got: {err}");
1271            // Region is autodetected (AWS) or defaulted (S3-compatible
1272            // endpoints ignore it): the recipe must not carry AWS_REGION
1273            // forward, only name the ?region= override.
1274            assert!(!err.contains("region            ="), "got: {err}");
1275            assert!(err.contains("?region="), "got: {err}");
1276            assert!(err.contains("pond storage check"), "got: {err}");
1277            // Without the addressing-style key the split is unknowable; the
1278            // recipe keeps the host verbatim with a <bucket> placeholder.
1279            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            // Env beats file per field; untouched fields survive the merge.
1330            jail.set_env("POND_STORAGE_PATH", "/from-env");
1331            jail.set_env("POND_CREDS_WORK_ACCESS_KEY_ID", "from-env");
1332            // A purely-numeric env secret must stay a string (extract_lossy).
1333            jail.set_env("POND_CREDS_WORK_SECRET_ACCESS_KEY", "12345");
1334            // A set defined only in env is discovered by the prefix scan.
1335            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}