bcode_config 0.0.1-alpha.0

Configuration loading for bcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Explicit, reviewed configuration edits preserving unrelated TOML and comments.

use crate::{BcodeConfig, ConfigError};
use std::io::Write as _;
use std::path::{Path, PathBuf};

/// An exact-file edit preview. The original contents fence concurrent changes.
///
/// This type intentionally has no Debug or serialization implementation: existing
/// configuration may contain secrets and must not become public preview data.
pub struct ConfigEdit {
    path: PathBuf,
    original: Option<String>,
    updated: String,
}

impl ConfigEdit {
    /// Destination selected for this explicit edit.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Apply only if the reviewed source is unchanged. Writes use atomic replacement.
    ///
    /// # Errors
    /// Returns an error on concurrent modification, lock failure, or I/O failure.
    pub fn apply(self) -> Result<PathBuf, ConfigError> {
        let parent = self
            .path
            .parent()
            .ok_or_else(|| invalid("Configuration parent is unavailable"))?;
        std::fs::create_dir_all(parent).map_err(|source| io_error(&self.path, source))?;
        let lock_path = self.path.with_extension("toml.lock");
        let lock = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&lock_path)
            .map_err(|source| io_error(&lock_path, source))?;
        lock.lock().map_err(|source| io_error(&lock_path, source))?;
        if read_optional(&self.path)? != self.original {
            return Err(invalid(
                "Configuration changed since review; review the changes again",
            ));
        }
        atomic_replace(&self.path, self.updated.as_bytes())
            .map_err(|source| io_error(&self.path, source))?;
        Ok(self.path)
    }
}

/// Replace a file with synced contents on the same filesystem. Caller owns locking.
pub(crate) fn atomic_replace(path: &Path, contents: &[u8]) -> std::io::Result<()> {
    let parent = path.parent().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "file parent is unavailable",
        )
    })?;
    let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
    temporary.write_all(contents)?;
    temporary.as_file().sync_all()?;
    temporary.persist(path).map_err(|error| error.error)?;
    std::fs::File::open(parent)?.sync_all()?;
    Ok(())
}

/// Plan one explicit non-secret TOML field edit or override removal.
///
/// Paths are key segments, not a dot-separated expression (plugin IDs may contain dots).
/// Interactive presentation and authentication storage have dedicated APIs and are rejected.
///
/// # Errors
/// Returns an error for an unsupported field, malformed TOML, or invalid configuration.
pub fn plan_field_edit(
    path: PathBuf,
    keys: &[String],
    value: Option<toml::Value>,
) -> Result<ConfigEdit, ConfigError> {
    if keys.first().is_some_and(|key| key == "contexts") {
        let selection = keys.len() == 2 && keys[1] == "active";
        let valid = selection
            || (keys.len() == 5
                && keys[1] == "entries"
                && keys[3] == "model"
                && keys[4] == "profile");
        if !valid {
            return Err(invalid(
                "Only context-local model profile selection is supported by this editor",
            ));
        }
        if selection {
            let Some(toml::Value::String(context)) = &value else {
                return Err(invalid("Select a context ID explicitly"));
            };
            crate::contexts::qualify(context, "validation")?;
        } else {
            crate::contexts::qualify(&keys[2], "validation")?;
        }
        if !matches!(&value, Some(toml::Value::String(name)) if !name.trim().is_empty()) {
            return Err(invalid("Select a non-empty context-local model profile"));
        }
        return plan_validated_field_edit(path, keys, value);
    }
    if keys.is_empty()
        || keys.iter().any(String::is_empty)
        || matches!(
            keys[0].as_str(),
            "tui" | "presentation" | "auth" | "composition"
        )
    {
        return Err(invalid(
            "Use the dedicated presentation or authentication editor for this field",
        ));
    }
    let root: toml::Value = toml::Value::try_from(BcodeConfig::default())
        .map_err(|_| invalid("Configuration schema is unavailable"))?;
    if root.get(&keys[0]).is_none() {
        return Err(invalid("Unknown configuration section"));
    }
    let allowed = match keys[0].as_str() {
        "model" => {
            keys.len() == 2
                && matches!(
                    keys[1].as_str(),
                    "profile" | "model_id" | "provider_plugin_id" | "auth_profile" | "auth_pool"
                )
        }
        "onboarding" => {
            keys.len() == 2 && matches!(keys[1].as_str(), "credential_discovery" | "open_browser")
        }
        "plugins" | "skills" => {
            keys.len() == 2 && matches!(keys[1].as_str(), "enabled" | "disabled")
        }
        _ => false,
    };
    if !allowed {
        return Err(invalid("This field requires a dedicated domain editor"));
    }
    plan_validated_field_edit(path, keys, value)
}

fn plan_validated_field_edit(
    path: PathBuf,
    keys: &[String],
    value: Option<toml::Value>,
) -> Result<ConfigEdit, ConfigError> {
    let original = read_optional(&path)?;
    let mut document = original
        .as_deref()
        .unwrap_or("")
        .parse::<toml_edit::DocumentMut>()
        .map_err(|_| invalid("Existing configuration cannot be edited safely"))?;
    let mut table = document.as_table_mut();
    for key in &keys[..keys.len() - 1] {
        if !table.contains_key(key) {
            table.insert(key, toml_edit::Item::Table(toml_edit::Table::new()));
        }
        table = table
            .get_mut(key)
            .and_then(toml_edit::Item::as_table_mut)
            .ok_or_else(|| invalid("Configuration path is not a table"))?;
    }
    let key = &keys[keys.len() - 1];
    if let Some(value) = value {
        let encoded = format!("value = {value}");
        let parsed = encoded
            .parse::<toml_edit::DocumentMut>()
            .map_err(|_| invalid("Invalid TOML value"))?;
        table.insert(key, parsed["value"].clone());
    } else {
        table.remove(key);
    }
    let updated = document.to_string();
    let mut resolved: toml::Value = toml::from_str(&updated)
        .map_err(|_| invalid("Edited configuration fails schema validation"))?;
    crate::shared_pools::expand(&mut resolved, &path)?;
    resolved
        .try_into::<BcodeConfig>()
        .map_err(|_| invalid("Edited configuration fails schema validation"))?;
    Ok(ConfigEdit {
        path,
        original,
        updated,
    })
}

/// Plan creation of an empty user-defined context without selecting it or copying credentials.
///
/// # Errors
/// Rejects invalid IDs, duplicate definitions, malformed files, and inaccessible destinations.
pub fn plan_context_creation(
    path: PathBuf,
    context: &str,
    label: &str,
) -> Result<ConfigEdit, ConfigError> {
    crate::contexts::qualify(context, "validation")?;
    let original = read_optional(&path)?;
    let parsed: toml::Value = toml::from_str(original.as_deref().unwrap_or(""))
        .map_err(|_| invalid("Existing configuration cannot be edited safely"))?;
    if parsed
        .get("contexts")
        .and_then(|value| value.get("entries"))
        .and_then(|value| value.get(context))
        .is_some()
    {
        return Err(invalid(
            "Context already exists; creation cannot overwrite its configuration",
        ));
    }
    let keys = ["contexts", "entries", context, "label"].map(str::to_owned);
    let edit = plan_validated_field_edit(path, &keys, Some(toml::Value::String(label.to_owned())))?;
    // Preserve the original version used for duplicate detection across the second read.
    if edit.original != original {
        return Err(invalid(
            "Configuration changed during context creation; review again",
        ));
    }
    Ok(edit)
}

/// Plan a context-local account declaration without writing credentials or changing bindings.
///
/// # Errors
/// Rejects invalid local IDs, duplicate declarations, or malformed destination files.
pub fn plan_context_auth_profile(
    path: PathBuf,
    context: &str,
    local: &str,
    profile: &crate::AuthProfileConfig,
) -> Result<ConfigEdit, ConfigError> {
    crate::contexts::qualify(context, local)?;
    let original = read_optional(&path)?;
    let parsed: toml::Value = toml::from_str(original.as_deref().unwrap_or(""))
        .map_err(|_| invalid("Existing configuration cannot be edited safely"))?;
    if parsed
        .get("contexts")
        .and_then(|v| v.get("entries"))
        .and_then(|v| v.get(context))
        .and_then(|v| v.get("auth"))
        .and_then(|v| v.get("profiles"))
        .and_then(|v| v.get(local))
        .is_some()
    {
        return Err(invalid(
            "Context account already exists; declaration cannot overwrite it",
        ));
    }
    let value =
        toml::Value::try_from(profile).map_err(|_| invalid("Invalid account declaration"))?;
    let keys = ["contexts", "entries", context, "auth", "profiles", local].map(str::to_owned);
    let edit = plan_validated_field_edit(path, &keys, Some(value))?;
    if edit.original != original {
        return Err(invalid(
            "Configuration changed during declaration; review again",
        ));
    }
    Ok(edit)
}

/// Plan a complete default model selection in one atomic file replacement.
/// The caller must resolve the model through the catalog before presenting this edit.
///
/// # Errors
/// Returns an error for empty selection, invalid TOML, or inaccessible configuration.
pub fn plan_model_selection(
    path: PathBuf,
    provider_plugin_id: &str,
    model_id: &str,
) -> Result<ConfigEdit, ConfigError> {
    plan_scoped_model_selection(path, None, provider_plugin_id, model_id, None)
}

/// Plan provider, model, and optional local account selection as one reviewed edit.
/// Context selection never modifies global model defaults or sibling contexts.
///
/// # Errors
/// Rejects invalid context/account IDs, empty targets, and malformed configuration.
pub fn plan_scoped_model_selection(
    path: PathBuf,
    context: Option<&str>,
    provider_plugin_id: &str,
    model_id: &str,
    auth_profile: Option<&str>,
) -> Result<ConfigEdit, ConfigError> {
    if let Some(context) = context {
        crate::contexts::qualify(context, auth_profile.unwrap_or("validation"))?;
    }
    if provider_plugin_id.is_empty() || model_id.is_empty() {
        return Err(invalid("Provider and model are required"));
    }
    plan_model_target_edit(
        path,
        context,
        provider_plugin_id,
        Some(model_id),
        auth_profile,
    )
}

fn plan_model_target_edit(
    path: PathBuf,
    context: Option<&str>,
    provider_plugin_id: &str,
    model_id: Option<&str>,
    auth_profile: Option<&str>,
) -> Result<ConfigEdit, ConfigError> {
    let original = read_optional(&path)?;
    let mut document = original
        .as_deref()
        .unwrap_or("")
        .parse::<toml_edit::DocumentMut>()
        .map_err(|_| invalid("Existing configuration cannot be edited safely"))?;
    let keys = context.map_or_else(
        || vec!["model"],
        |context| vec!["contexts", "entries", context, "model"],
    );
    let mut model = document.as_table_mut();
    for key in keys {
        if !model.contains_key(key) {
            model.insert(key, toml_edit::Item::Table(toml_edit::Table::new()));
        }
        model = model
            .get_mut(key)
            .and_then(toml_edit::Item::as_table_mut)
            .ok_or_else(|| invalid("Model selection path must be a table"))?;
    }
    model.insert("provider_plugin_id", toml_edit::value(provider_plugin_id));
    if let Some(model_id) = model_id {
        model.insert("model_id", toml_edit::value(model_id));
    } else {
        model.remove("model_id");
    }
    model.remove("profile");
    if let Some(profile) = auth_profile {
        model.insert("auth_profile", toml_edit::value(profile));
        model.remove("auth_pool");
    }
    // An explicitly selected account replaces pool routing; otherwise references are preserved.
    let updated = document.to_string();
    toml::from_str::<BcodeConfig>(&updated).map_err(|_| invalid("Invalid model configuration"))?;
    Ok(ConfigEdit {
        path,
        original,
        updated,
    })
}

/// Plan a context-local account/provider selection, clearing model and pool overrides.
/// The account must already exist in the caller's effective context configuration.
///
/// # Errors
/// Rejects invalid IDs, unavailable accounts, and malformed destination files.
pub fn plan_context_account_selection(
    path: PathBuf,
    config: &BcodeConfig,
    local: &str,
) -> Result<ConfigEdit, ConfigError> {
    let discovery = crate::contexts::prepare_model_discovery(config, Some(local))?;
    plan_model_target_edit(
        path,
        Some(&discovery.context),
        &discovery.provider_plugin_id,
        None,
        Some(local),
    )
}

fn read_optional(path: &Path) -> Result<Option<String>, ConfigError> {
    match std::fs::read_to_string(path) {
        Ok(contents) => Ok(Some(contents)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(io_error(path, error)),
    }
}
fn invalid(message: &str) -> ConfigError {
    ConfigError::Composition {
        message: message.to_owned(),
    }
}
fn io_error(path: &Path, source: std::io::Error) -> ConfigError {
    ConfigError::Io {
        path: path.to_owned(),
        source,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn context_account_declaration_is_reviewed_and_uses_isolated_storage() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        std::fs::write(
            &path,
            "[contexts]\nactive = 'custom'\n[contexts.entries.custom]\n",
        )
        .unwrap();
        let profile = crate::AuthProfileConfig {
            backend: "sshenv".to_owned(),
            provider_id: Some("example".to_owned()),
            owner_plugin_id: Some("example.plugin".to_owned()),
            scheme: Some("oauth".to_owned()),
            ..Default::default()
        };
        let edit = plan_context_auth_profile(path.clone(), "custom", "account", &profile).unwrap();
        let before = crate::load_config_from_paths(std::slice::from_ref(&path)).unwrap();
        assert!(before.auth.profiles.is_empty());
        edit.apply().unwrap();
        assert!(plan_context_auth_profile(path.clone(), "custom", "account", &profile).is_err());
        let loaded = crate::load_config_from_paths(&[path]).unwrap();
        let id = crate::contexts::qualify("custom", "account").unwrap();
        assert_eq!(loaded.auth.profiles[&id].settings["profile"], id);
        assert!(loaded.auth.bindings.is_empty());
    }

    #[test]
    fn context_creation_is_reviewed_nonselecting_and_conflict_fenced() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        let first = plan_context_creation(path.clone(), "custom", "Custom label").unwrap();
        let stale = plan_context_creation(path.clone(), "other", "Other").unwrap();
        assert!(!path.exists());
        first.apply().unwrap();
        assert!(stale.apply().is_err());
        assert!(plan_context_creation(path.clone(), "custom", "Replacement").is_err());
        let config = crate::load_config_from_paths(&[path]).unwrap();
        assert!(config.active_context.is_none());
        let contexts = config.contexts.unwrap();
        assert!(contexts.entries["custom"].auth.profiles.is_empty());
        assert_eq!(
            contexts.entries["custom"].label.as_deref(),
            Some("Custom label")
        );
    }

    #[test]
    fn explicit_context_selection_edit_preserves_definitions() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        std::fs::write(&path, "[contexts]\nactive = 'alpha'\n[contexts.entries.alpha]\nlabel = 'First'\n[contexts.entries.beta]\nlabel = 'Second'\n").unwrap();
        let edit = plan_field_edit(
            path.clone(),
            &["contexts".to_owned(), "active".to_owned()],
            Some(toml::Value::String("beta".to_owned())),
        )
        .unwrap();
        edit.apply().unwrap();
        let config = crate::load_config_from_paths(&[path]).unwrap();
        assert_eq!(config.active_context.as_deref(), Some("beta"));
        assert_eq!(config.contexts.unwrap().entries.len(), 2);
    }

    #[test]
    fn context_model_edit_preserves_global_and_sibling_selections() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        let original = "# preserved\n[model]\nprofile = 'global'\n[contexts.entries.alpha.model]\nprofile = 'before'\n[contexts.entries.beta.model]\nprofile = 'sibling'\n";
        std::fs::write(&path, original).unwrap();
        let keys = ["contexts", "entries", "alpha", "model", "profile"].map(str::to_owned);
        let edit = plan_field_edit(
            path.clone(),
            &keys,
            Some(toml::Value::String("after".to_owned())),
        )
        .unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
        edit.apply().unwrap();
        let text = std::fs::read_to_string(path).unwrap();
        let parsed: toml::Value = toml::from_str(&text).unwrap();
        assert_eq!(parsed["model"]["profile"].as_str(), Some("global"));
        assert_eq!(
            parsed["contexts"]["entries"]["alpha"]["model"]["profile"].as_str(),
            Some("after")
        );
        assert_eq!(
            parsed["contexts"]["entries"]["beta"]["model"]["profile"].as_str(),
            Some("sibling")
        );
        assert!(text.starts_with("# preserved"));
    }

    #[test]
    fn preserves_comments_and_rejects_stale_review() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        std::fs::write(&path, "# keep me\n[model]\nmodel_id = 'old'\n").unwrap();
        let keys = vec!["model".to_owned(), "model_id".to_owned()];
        let first = plan_field_edit(
            path.clone(),
            &keys,
            Some(toml::Value::String("first".to_owned())),
        )
        .unwrap();
        let stale = plan_field_edit(
            path.clone(),
            &keys,
            Some(toml::Value::String("stale".to_owned())),
        )
        .unwrap();
        first.apply().unwrap();
        assert!(stale.apply().is_err());
        let contents = std::fs::read_to_string(path).unwrap();
        assert!(contents.contains("# keep me"));
        assert!(contents.contains("first"));
    }
    #[test]
    fn model_selection_is_one_reviewed_edit_and_preserves_other_fields() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        std::fs::write(&path, "# preserved\n[model]\nprofile = 'old'\nauth_profile = 'account'\n[onboarding]\ncredential_discovery = false\n").unwrap();
        plan_model_selection(path.clone(), "bcode.provider", "model-name")
            .unwrap()
            .apply()
            .unwrap();
        let contents = std::fs::read_to_string(path).unwrap();
        let config: BcodeConfig = toml::from_str(&contents).unwrap();
        assert_eq!(
            config.model.provider_plugin_id.as_deref(),
            Some("bcode.provider")
        );
        assert_eq!(config.model.model_id.as_deref(), Some("model-name"));
        assert_eq!(config.model.auth_profile.as_deref(), Some("account"));
        assert!(config.model.profile.is_none());
        assert!(!config.onboarding.credential_discovery);
        assert!(contents.contains("# preserved"));
    }

    #[test]
    fn presentation_and_auth_require_domain_editors() {
        for section in ["auth", "tui", "presentation"] {
            assert!(plan_field_edit(PathBuf::from("unused"), &[section.to_owned()], None).is_err());
        }
    }
}