pond-db 0.9.0

Lossless storage and hybrid search for sessions from any AI agent client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Source discovery and the interactive registration picker: probe the
//! environment for configurable sources, prompt the operator, and persist the
//! picks to `config.toml`. Config-time and interactive - kept off the
//! sync-time seam in `mod.rs`.

use std::path::Path;

use anyhow::{Context, bail};
use serde_json::Value;
use toml_edit::{DocumentMut, Item, Table};

use super::{Env, by_name, known_names, probe_all};

/// One discovered adapter: its name, a hint to show the operator (typically
/// the probed path or endpoint), and the JSON config blob that will be
/// persisted under `[sources.<name>]` if the operator confirms.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
    pub name: String,
    pub hint: String,
    pub config: Value,
}

/// Probe every registered factory whose name is NOT already a key in
/// `configured`. Used by `pond sync` to spot freshly-detectable adapters
/// without re-prompting the operator about ones they already opted in or
/// out of. Returns `Candidate`s in registry order.
pub fn probe_unconfigured(
    configured: &std::collections::BTreeMap<String, Value>,
) -> Vec<Candidate> {
    let Some(env) = Env::from_env() else {
        return Vec::new();
    };
    super::registry()
        .iter()
        .filter(|factory| !configured.contains_key(factory.name()))
        .filter_map(|factory| {
            factory.probe_default(&env).map(|config| Candidate {
                name: factory.name().to_owned(),
                hint: hint_for(&config),
                config,
            })
        })
        .collect()
}

/// Probe every registered factory (or just the one named in `focus`) under
/// the current environment and shape results into [`Candidate`]s for the
/// picker. Returns an empty list when no factory's `probe_default` returned
/// anything - the caller surfaces a "configure manually" error in that case.
pub fn discover(focus: Option<&str>) -> Vec<Candidate> {
    let Some(env) = Env::from_env() else {
        return Vec::new();
    };
    let candidates: Vec<Candidate> = match focus {
        None => probe_all(&env)
            .into_iter()
            .map(|(name, config)| Candidate {
                name: name.to_owned(),
                hint: hint_for(&config),
                config,
            })
            .collect(),
        Some(name) => by_name(name)
            .and_then(|factory| factory.probe_default(&env))
            .map(|config| Candidate {
                name: name.to_owned(),
                hint: hint_for(&config),
                config,
            })
            .into_iter()
            .collect(),
    };
    candidates
}

/// Best-effort label for the picker. For filesystem configs that's the
/// `path` (with `$HOME` contracted to `~` for readability); for richer
/// configs we fall back to a compact JSON dump so the operator at least sees
/// what they're confirming.
fn hint_for(config: &Value) -> String {
    if let Some(path) = config.get("path").and_then(Value::as_str) {
        return crate::config::contract_home(Path::new(path))
            .display()
            .to_string();
    }
    if let Some(endpoint) = config.get("endpoint").and_then(Value::as_str) {
        return endpoint.to_owned();
    }
    serde_json::to_string(config).unwrap_or_default()
}

/// Prompt the operator to pick which `candidates` to register, then persist
/// the chosen entries to `config.toml` and return them. Pre-checks every
/// candidate (the operator already opted in by running `pond sync`). When
/// `stdin_is_tty` is false we never prompt - we bail with a clear "configure
/// manually" message so CI and post-install scripts get a predictable error
/// instead of a hang. The caller injects TTY-ness so tests can drive the
/// non-tty branch deterministically regardless of how `cargo test` is invoked.
pub fn prompt_and_persist(
    config_path: &Path,
    candidates: &[Candidate],
    stdin_is_tty: bool,
) -> anyhow::Result<Vec<Candidate>> {
    if candidates.is_empty() {
        bail!(
            "no adapter sources detected in this environment; known adapters: {}",
            known_names().join(", "),
        );
    }
    if !stdin_is_tty {
        bail!(
            "[sources] is empty and stdin is not a terminal; run `pond init --yes` to enable \
             detected sources, or add a [sources.<adapter>] entry to {} (known adapters: {})",
            config_path.display(),
            known_names().join(", "),
        );
    }
    let mut picker = cliclack::multiselect("Select sources to register")
        .initial_values(candidates.iter().map(|c| c.name.clone()).collect());
    for candidate in candidates {
        picker = picker.item(candidate.name.clone(), &candidate.name, &candidate.hint);
    }
    let selected: Vec<String> = match picker.interact() {
        Ok(picks) => picks,
        // Esc / Ctrl-C in the picker means "register nothing", same outcome
        // as an empty selection - not a failure.
        Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
            bail!("no sources selected; nothing to sync");
        }
        Err(error) => return Err(error).context("source picker prompt failed"),
    };
    if selected.is_empty() {
        bail!("no sources selected; nothing to sync");
    }
    let picks: Vec<Candidate> = candidates
        .iter()
        .filter(|candidate| selected.contains(&candidate.name))
        .cloned()
        .collect();
    persist_accept(config_path, &picks)?;
    Ok(picks)
}

/// Shape accepted and declined sources into a `toml_edit` document:
/// `[sources.<name>]` with `enabled` as the first key, the accept's config
/// blob unpacked into TOML pairs (home-prefixed `path` values contracted to
/// `~/...` so the file stays portable), declines as `enabled = false` stubs.
/// The one table-shaping routine shared by the sync picker writes and the
/// `pond init` wizard's single end-of-run write.
pub fn apply_to_doc(
    doc: &mut DocumentMut,
    accepts: &[Candidate],
    declines: &[&str],
) -> anyhow::Result<()> {
    if accepts.is_empty() && declines.is_empty() {
        return Ok(());
    }
    if !doc.contains_key("sources") {
        let mut table = Table::new();
        table.set_implicit(true);
        doc.insert("sources", Item::Table(table));
    }
    let sources = sources_table_mut(doc)?;
    for pick in accepts {
        let mut entry = json_to_toml_table(&pick.config).with_context(|| {
            format!(
                "pick for {:?} did not produce a TOML-shaped table",
                pick.name
            )
        })?;
        contract_path_key(&mut entry);
        prepend_enabled(&mut entry, true);
        sources.insert(&pick.name, Item::Table(entry));
    }
    for name in declines {
        let mut entry = Table::new();
        prepend_enabled(&mut entry, false);
        sources.insert(name, Item::Table(entry));
    }
    Ok(())
}

/// Contract a home-prefixed `path` value to `~/...` before it lands in
/// config.toml. Reads (`expand_home_under` inside each factory's `open()`)
/// expand the same prefix back, so the round-trip is lossless.
fn contract_path_key(table: &mut Table) {
    if let Some(path) = table.get("path").and_then(Item::as_str) {
        let contracted = crate::config::contract_home(Path::new(path))
            .display()
            .to_string();
        if contracted != path {
            table["path"] = toml_edit::value(contracted);
        }
    }
}

/// Write the picked sources back to `config.toml` under `[sources.<name>]`,
/// preserving any existing user comments/formatting via `toml_edit`.
pub fn persist_accept(config_path: &Path, picks: &[Candidate]) -> anyhow::Result<()> {
    let mut doc = open_or_init(config_path)?;
    apply_to_doc(&mut doc, picks, &[])?;
    std::fs::write(config_path, doc.to_string())
        .with_context(|| format!("failed to write {}", config_path.display()))?;
    Ok(())
}

/// Outcome of a per-adapter `Confirm` prompt during `pond sync`. `enable`
/// is the answer to "should this adapter be enabled?"; `sync_now` is the
/// follow-up "should we sync it this run?" (only meaningful when
/// `enable == true`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromptOutcome {
    pub candidate: Candidate,
    pub enable: bool,
    pub sync_now: bool,
}

/// Prompt the operator about each freshly-detected unconfigured adapter:
/// "Enable X?" and, on accept, "Sync X now?". When `auto_accept` is true
/// (the operator passed `--yes`) every prompt is skipped and answered
/// yes/yes. Returns the per-adapter outcomes.
pub fn prompt_each(
    candidates: &[Candidate],
    auto_accept: bool,
) -> anyhow::Result<Vec<PromptOutcome>> {
    let mut out = Vec::with_capacity(candidates.len());
    for candidate in candidates {
        let label = if candidate.hint.is_empty() {
            candidate.name.clone()
        } else {
            format!("{} ({})", candidate.name, candidate.hint)
        };
        let (enable, sync_now) = if auto_accept {
            (true, true)
        } else {
            let enable = cliclack::confirm(format!("Enable {label}?"))
                .initial_value(true)
                .interact()
                .context("enable prompt failed")?;
            let sync_now = if enable {
                cliclack::confirm(format!("Sync {} now?", candidate.name))
                    .initial_value(true)
                    .interact()
                    .context("sync-now prompt failed")?
            } else {
                false
            };
            (enable, sync_now)
        };
        out.push(PromptOutcome {
            candidate: candidate.clone(),
            enable,
            sync_now,
        });
    }
    Ok(out)
}

/// Persist `[sources.<name>] enabled = false` for adapters the operator
/// declined during a probe prompt. Keeps the decline sticky across runs.
pub fn persist_decline(config_path: &Path, names: &[&str]) -> anyhow::Result<()> {
    if names.is_empty() {
        return Ok(());
    }
    let mut doc = open_or_init(config_path)?;
    apply_to_doc(&mut doc, &[], names)?;
    std::fs::write(config_path, doc.to_string())
        .with_context(|| format!("failed to write {}", config_path.display()))?;
    Ok(())
}

fn open_or_init(config_path: &Path) -> anyhow::Result<DocumentMut> {
    if let Some(parent) = config_path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create config dir {}", parent.display()))?;
    }
    let existing = if config_path.exists() {
        std::fs::read_to_string(config_path)
            .with_context(|| format!("failed to read {}", config_path.display()))?
    } else {
        String::new()
    };
    let mut doc: DocumentMut = existing
        .parse()
        .with_context(|| format!("failed to parse {} as TOML", config_path.display()))?;
    if !doc.contains_key("sources") {
        let mut table = Table::new();
        table.set_implicit(true);
        doc.insert("sources", Item::Table(table));
    }
    Ok(doc)
}

fn sources_table_mut(doc: &mut DocumentMut) -> anyhow::Result<&mut Table> {
    doc["sources"]
        .as_table_mut()
        .ok_or_else(|| anyhow::anyhow!("config.toml has a `sources` value that is not a table"))
}

fn prepend_enabled(table: &mut Table, value: bool) {
    use toml_edit::value as tv;
    let implicit = table.is_implicit();
    let keys: Vec<String> = table.iter().map(|(k, _)| k.to_owned()).collect();
    let mut existing: Vec<(String, Item)> = Vec::with_capacity(keys.len());
    for key in keys {
        if key == "enabled" {
            continue;
        }
        if let Some(item) = table.remove(&key) {
            existing.push((key, item));
        }
    }
    table.remove("enabled");
    let mut fresh = Table::new();
    fresh.set_implicit(implicit);
    fresh.insert("enabled", tv(value));
    for (key, item) in existing {
        fresh.insert(&key, item);
    }
    *table = fresh;
}

/// Convert a JSON object into a `toml_edit::Table`. Factories produce JSON
/// blobs (the seam contract); the picker persists them as TOML tables. Non-
/// object roots are rejected with an error rather than silently dropped.
fn json_to_toml_table(value: &Value) -> anyhow::Result<Table> {
    let Value::Object(map) = value else {
        bail!("config blob must be a JSON object, got {value}");
    };
    let mut table = Table::new();
    for (key, val) in map {
        table[key] = json_to_toml_item(val)?;
    }
    Ok(table)
}

fn json_to_toml_item(value: &Value) -> anyhow::Result<Item> {
    use toml_edit::{Array, InlineTable, Value as TomlValue, value as tv};
    Ok(match value {
        Value::Null => bail!("null is not representable in TOML"),
        Value::Bool(b) => tv(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                tv(i)
            } else if let Some(f) = n.as_f64() {
                tv(f)
            } else {
                bail!("number {n} is not representable in TOML");
            }
        }
        Value::String(s) => tv(s.clone()),
        Value::Array(values) => {
            let mut array = Array::new();
            for v in values {
                let item = json_to_toml_item(v)?;
                let toml_value: TomlValue = item.into_value().map_err(|_| {
                    anyhow::anyhow!("array element {v} is not a scalar; nested tables in arrays")
                })?;
                array.push(toml_value);
            }
            Item::Value(TomlValue::Array(array))
        }
        Value::Object(_) => {
            let table = json_to_toml_table(value)?;
            let mut inline = InlineTable::new();
            for (key, item) in table.iter() {
                if let Some(v) = item.as_value() {
                    inline.insert(key, v.clone());
                }
            }
            Item::Value(TomlValue::InlineTable(inline))
        }
    })
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::unwrap_used)]

    use super::*;
    use serde_json::json;
    use tempfile::TempDir;

    #[test]
    fn prompt_and_persist_errors_on_non_tty_stdin() {
        // Drive the non-tty branch explicitly. This is the path CI and
        // package-install scripts hit; the picker must surface a clear
        // "configure manually" error instead of hanging on a prompt.
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("config.toml");
        let candidates = vec![Candidate {
            name: "claude-code".to_owned(),
            hint: "/tmp/dummy".to_owned(),
            config: json!({ "path": "/tmp/dummy" }),
        }];
        let err = prompt_and_persist(&config_path, &candidates, false)
            .expect_err("non-tty stdin must error rather than hang");
        let msg = err.to_string();
        assert!(
            msg.contains("not a terminal"),
            "error should mention the non-tty branch: {msg}",
        );
    }

    #[test]
    fn persist_accept_and_decline_write_enabled_first() {
        let temp = TempDir::new().unwrap();
        let config_path = temp.path().join("config.toml");
        let accept = Candidate {
            name: "claude-code".to_owned(),
            hint: "/tmp/cc".to_owned(),
            config: json!({ "path": "/tmp/cc" }),
        };
        persist_accept(&config_path, &[accept]).unwrap();
        persist_decline(&config_path, &["opencode"]).unwrap();
        let body = std::fs::read_to_string(&config_path).unwrap();
        // Accepted entry: discriminator on top, then the blob.
        assert!(
            body.contains("[sources.claude-code]")
                && body.contains("enabled = true")
                && body.contains("path = \"/tmp/cc\""),
            "expected accepted entry; got: {body}",
        );
        // Declined entry: discriminator only, no path leak.
        assert!(
            body.contains("[sources.opencode]") && body.contains("enabled = false"),
            "expected declined entry; got: {body}",
        );
    }
}