bamboo-config 2026.7.26

Configuration, settings, paths, encryption and keyword-masking for the Bamboo agent framework
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
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
//! Independently persisted configuration modules and their registrar.
//!
//! A module owns one sidecar file in Bamboo's data directory.  Modules are
//! deliberately object-safe so new configuration domains can be registered
//! without adding another field to the root [`crate::Config`] DTO.

use std::{any::Any, collections::HashMap, path::Path};

use anyhow::{anyhow, Result};
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};

/// A named, independently loadable and flushable configuration domain.
#[async_trait]
pub trait ConfigModule: Send + Sync {
    fn name(&self) -> &'static str;
    async fn load(&mut self, data_dir: &Path) -> Result<()>;
    async fn save(&self, data_dir: &Path) -> Result<()>;
    async fn reload(&mut self, data_dir: &Path) -> Result<()> {
        self.load(data_dir).await
    }
    fn validate(&self) -> Result<()>;
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

/// Registrar for configuration domains. Each module can be loaded or saved
/// without serializing unrelated configuration.
#[derive(Default)]
pub struct ConfigRegistry {
    modules: HashMap<String, Box<dyn ConfigModule>>,
}

impl ConfigRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register<M: ConfigModule + 'static>(
        &mut self,
        module: M,
    ) -> Option<Box<dyn ConfigModule>> {
        self.modules
            .insert(module.name().to_owned(), Box::new(module))
    }

    pub fn module<T: 'static>(&self, name: &str) -> Option<&T> {
        self.modules.get(name)?.as_any().downcast_ref()
    }

    pub fn module_mut<T: 'static>(&mut self, name: &str) -> Option<&mut T> {
        self.modules.get_mut(name)?.as_any_mut().downcast_mut()
    }

    pub async fn load_all(&mut self, data_dir: &Path) -> Result<()> {
        for module in self.modules.values_mut() {
            module.load(data_dir).await?;
            module.validate()?;
        }
        Ok(())
    }

    pub async fn reload_module(&mut self, name: &str, data_dir: &Path) -> Result<()> {
        let module = self
            .modules
            .get_mut(name)
            .ok_or_else(|| anyhow!("unknown config module: {name}"))?;
        module.reload(data_dir).await?;
        module.validate()
    }

    pub async fn save_module(&self, name: &str, data_dir: &Path) -> Result<()> {
        let module = self
            .modules
            .get(name)
            .ok_or_else(|| anyhow!("unknown config module: {name}"))?;
        module.validate()?;
        module.save(data_dir).await
    }

    pub async fn save_all(&self, data_dir: &Path) -> Result<()> {
        for module in self.modules.values() {
            module.validate()?;
            module.save(data_dir).await?;
        }
        Ok(())
    }
}

pub(crate) fn load_sidecar<T: DeserializeOwned>(path: &Path) -> Result<Option<T>> {
    if !path.exists() {
        return Ok(None);
    }
    let bytes = std::fs::read(path)?;
    match serde_json::from_slice(&bytes) {
        Ok(value) => Ok(Some(value)),
        Err(primary_error) => {
            let backup = path.with_extension("json.bak");
            if backup.exists() {
                let backup_bytes = std::fs::read(&backup)?;
                return serde_json::from_slice(&backup_bytes)
                    .map(Some)
                    .map_err(Into::into);
            }
            Err(primary_error.into())
        }
    }
}

pub(crate) fn save_sidecar<T: Serialize + DeserializeOwned>(path: &Path, value: &T) -> Result<()> {
    crate::config_store::AtomicFileStore::new(path)
        .backup_generations(1)
        .write_json(value)?;
    Ok(())
}

/// Save a sidecar whose deserializer intentionally drops in-memory-only
/// fields (for example provider plaintext API keys). The previous generation
/// is parsed and reserialized before becoming the backup so a hand-written
/// plaintext secret is never copied verbatim into `*.json.bak`.
pub(crate) fn save_sidecar_with_sanitized_backup<T: Serialize + DeserializeOwned>(
    path: &Path,
    value: &T,
) -> Result<()> {
    crate::config_store::AtomicFileStore::new(path)
        .backup_generations(1)
        .write_json(value)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::time::SystemTime;

    use serde_json::json;
    use tempfile::TempDir;

    use crate::{
        Config, ConfigRegistry, MemoryConfig, OpenAIConfig, ProviderConfigs, ProviderConfigsModule,
    };

    fn write_json(path: &Path, value: serde_json::Value) {
        std::fs::write(path, serde_json::to_vec_pretty(&value).unwrap()).unwrap();
    }

    use std::path::Path;

    #[test]
    fn legacy_inline_sections_load_and_migrate_to_sidecars() {
        let dir = TempDir::new().unwrap();
        write_json(
            &dir.path().join("config.json"),
            json!({
                "memory": { "background_model": "legacy-memory" },
                "subagents": { "max_concurrent": 3 },
                "providers": { "openai": { "model": "legacy-model" } }
            }),
        );

        let config = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
        assert_eq!(
            config.memory.as_ref().unwrap().background_model.as_deref(),
            Some("legacy-memory")
        );
        assert_eq!(config.subagents.max_concurrent, Some(3));
        assert_eq!(
            config.providers.openai.as_ref().unwrap().model.as_deref(),
            Some("legacy-model")
        );

        config.save_to_dir(dir.path().to_path_buf()).unwrap();
        let root: serde_json::Value =
            serde_json::from_slice(&std::fs::read(dir.path().join("config.json")).unwrap())
                .unwrap();
        assert!(root.get("memory").is_none());
        assert!(root.get("subagents").is_none());
        assert!(root.get("providers").is_none());
        assert!(dir.path().join("memory.json").exists());
        assert!(dir.path().join("subagents.json").exists());
        assert!(dir.path().join("providers.json").exists());

        let reloaded = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
        assert_eq!(
            reloaded
                .memory
                .as_ref()
                .unwrap()
                .background_model
                .as_deref(),
            Some("legacy-memory")
        );
        assert_eq!(reloaded.subagents.max_concurrent, Some(3));
        assert_eq!(
            reloaded.providers.openai.as_ref().unwrap().model.as_deref(),
            Some("legacy-model")
        );
    }

    #[test]
    fn invalid_provider_credential_refs_from_external_edits_are_rejected() {
        for invalid_ref in ["../credentials".to_string(), "x".repeat(161)] {
            let dir = TempDir::new().unwrap();
            write_json(
                &dir.path().join("config.json"),
                json!({
                    "providers": {"openai": {"model": "root-lkg"}}
                }),
            );
            write_json(
                &dir.path().join("providers.json"),
                json!({
                    "openai": {
                        "model": "must-not-load",
                        "credential_ref": invalid_ref
                    }
                }),
            );

            let config = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
            assert_eq!(
                config.providers.openai.as_ref().unwrap().model.as_deref(),
                Some("root-lkg")
            );
        }
    }

    #[test]
    fn sidecars_override_legacy_inline_sections() {
        let dir = TempDir::new().unwrap();
        write_json(
            &dir.path().join("config.json"),
            json!({
                "memory": { "background_model": "inline" },
                "subagents": { "max_concurrent": 1 },
                "providers": { "openai": { "model": "inline" } }
            }),
        );
        write_json(
            &dir.path().join("memory.json"),
            json!({"background_model": "sidecar"}),
        );
        write_json(
            &dir.path().join("subagents.json"),
            json!({"max_concurrent": 9}),
        );
        write_json(
            &dir.path().join("providers.json"),
            json!({"openai": {"model": "sidecar"}}),
        );

        let config = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
        assert_eq!(
            config.memory.as_ref().unwrap().background_model.as_deref(),
            Some("sidecar")
        );
        assert_eq!(config.subagents.max_concurrent, Some(9));
        assert_eq!(
            config.providers.openai.as_ref().unwrap().model.as_deref(),
            Some("sidecar")
        );
    }

    #[test]
    fn independent_memory_save_does_not_touch_other_documents() {
        let dir = TempDir::new().unwrap();
        let config = Config::default();
        config.save_to_dir(dir.path().to_path_buf()).unwrap();
        let paths = ["config.json", "providers.json", "subagents.json"];
        let before: Vec<_> = paths
            .iter()
            .map(|name| {
                let path = dir.path().join(name);
                (
                    std::fs::read(&path).unwrap(),
                    std::fs::metadata(path)
                        .unwrap()
                        .modified()
                        .unwrap_or(SystemTime::UNIX_EPOCH),
                )
            })
            .collect();

        let mut changed = config;
        changed.memory.0 = Some(MemoryConfig {
            background_model: Some("new-memory".into()),
            ..MemoryConfig::default()
        });
        changed.save_memory_to_dir(dir.path()).unwrap();

        for (index, name) in paths.iter().enumerate() {
            let path = dir.path().join(name);
            assert_eq!(
                std::fs::read(&path).unwrap(),
                before[index].0,
                "{name} bytes changed"
            );
            assert_eq!(
                std::fs::metadata(path)
                    .unwrap()
                    .modified()
                    .unwrap_or(SystemTime::UNIX_EPOCH),
                before[index].1,
                "{name} mtime changed"
            );
        }
    }

    #[test]
    fn providers_sidecar_never_contains_plaintext_api_key() {
        let _key = crate::encryption::set_test_encryption_key([23; 32]);
        let dir = TempDir::new().unwrap();
        let reference = crate::credential_ref("provider", "openai", "api_key").unwrap();
        crate::CredentialStore::open(dir.path())
            .replace(
                reference.clone(),
                "sk-plaintext-must-not-leak",
                crate::CredentialSource::User,
                0,
            )
            .unwrap();
        let mut config = Config::default();
        config.providers.openai = Some(OpenAIConfig {
            api_key: "sk-plaintext-must-not-leak".into(),
            credential_ref: Some(reference),
            ..OpenAIConfig::default()
        });
        config.save_providers_to_dir(dir.path()).unwrap();
        let raw = std::fs::read_to_string(dir.path().join("providers.json")).unwrap();
        assert!(!raw.contains("sk-plaintext-must-not-leak"));
        assert!(!raw.contains("api_key_encrypted"));
        assert!(raw.contains("credential_ref"));
    }

    #[test]
    fn malformed_sidecar_recovers_from_last_known_good_backup() {
        let dir = TempDir::new().unwrap();
        write_json(&dir.path().join("config.json"), json!({}));
        write_json(
            &dir.path().join("memory.json.bak"),
            json!({"background_model": "recovered"}),
        );
        std::fs::write(dir.path().join("memory.json"), b"{broken").unwrap();

        let config = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
        assert_eq!(
            config.memory.as_ref().unwrap().background_model.as_deref(),
            Some("recovered")
        );
        assert_eq!(
            std::fs::read(dir.path().join("memory.json")).unwrap(),
            b"{broken"
        );
    }

    #[test]
    fn schema_invalid_sidecar_is_not_promoted_over_last_known_good_backup() {
        let dir = TempDir::new().unwrap();
        write_json(&dir.path().join("config.json"), json!({}));
        write_json(
            &dir.path().join("memory.json.bak"),
            json!({"background_model": "recovered"}),
        );
        write_json(
            &dir.path().join("memory.json"),
            json!({"auto_dream_interval_secs": "not-a-number"}),
        );

        let config = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
        assert_eq!(
            config.memory.as_ref().unwrap().background_model.as_deref(),
            Some("recovered")
        );
        config.save_memory_to_dir(dir.path()).unwrap();

        let backup: MemoryConfig =
            serde_json::from_slice(&std::fs::read(dir.path().join("memory.json.bak")).unwrap())
                .unwrap();
        assert_eq!(backup.background_model.as_deref(), Some("recovered"));
    }

    #[test]
    fn provider_registry_save_encrypts_keys_and_sanitizes_backup() {
        let _key = crate::encryption::set_test_encryption_key([29; 32]);
        let dir = TempDir::new().unwrap();
        write_json(
            &dir.path().join("providers.json"),
            json!({"openai": {"api_key": "sk-old-plaintext", "model": "old"}}),
        );
        crate::migrate_provider_mcp_credentials(dir.path()).unwrap();
        let reference = crate::credential_ref("provider", "openai", "api_key").unwrap();
        let store = crate::CredentialStore::open(dir.path());
        store
            .replace(
                reference.clone(),
                "sk-new-plaintext",
                crate::CredentialSource::User,
                store.revision().unwrap(),
            )
            .unwrap();

        let providers = ProviderConfigs {
            openai: Some(OpenAIConfig {
                api_key: "sk-new-plaintext".into(),
                credential_ref: Some(reference),
                model: Some("new".into()),
                ..OpenAIConfig::default()
            }),
            ..ProviderConfigs::default()
        };
        let mut registry = ConfigRegistry::new();
        registry.register(ProviderConfigsModule(providers));
        futures::executor::block_on(registry.save_module("providers", dir.path())).unwrap();

        let current = std::fs::read_to_string(dir.path().join("providers.json")).unwrap();
        assert!(!current.contains("sk-new-plaintext"));
        assert!(!current.contains("api_key_encrypted"));
        assert!(current.contains("credential_ref"));
        let backup = std::fs::read_to_string(dir.path().join("providers.json.bak")).unwrap();
        assert!(!backup.contains("sk-old-plaintext"));

        let mut loaded = ConfigRegistry::new();
        loaded.register(ProviderConfigsModule::default());
        futures::executor::block_on(loaded.load_all(dir.path())).unwrap();
        let module = loaded.module::<ProviderConfigsModule>("providers").unwrap();
        assert_eq!(
            module.0.openai.as_ref().unwrap().api_key,
            "sk-new-plaintext"
        );

        // Config's compatibility path performs its historical hydration pass
        // after module load. The module-level hydration above must remain
        // idempotent when reached through that path.
        let config = Config::from_data_dir_without_env(Some(dir.path().to_path_buf()));
        assert_eq!(
            config.providers.openai.as_ref().unwrap().api_key,
            "sk-new-plaintext"
        );
    }

    #[test]
    fn sidecars_are_durable_before_root_migration_rewrite() {
        let dir = TempDir::new().unwrap();
        // A directory at config.json forces the final atomic rename to fail.
        // The independently persisted modules must already be durable so a
        // failed root rewrite cannot discard the migration source of truth.
        std::fs::create_dir(dir.path().join("config.json")).unwrap();
        let mut config = Config::default();
        config.memory.0 = Some(MemoryConfig {
            background_model: Some("durable-before-root".into()),
            ..MemoryConfig::default()
        });

        assert!(config.save_to_dir(dir.path().to_path_buf()).is_err());
        let memory: MemoryConfig =
            serde_json::from_slice(&std::fs::read(dir.path().join("memory.json")).unwrap())
                .unwrap();
        assert_eq!(
            memory.background_model.as_deref(),
            Some("durable-before-root")
        );
        assert!(dir.path().join("subagents.json").exists());
        let providers: ProviderConfigs =
            serde_json::from_slice(&std::fs::read(dir.path().join("providers.json")).unwrap())
                .unwrap();
        assert!(providers.openai.is_none());
        assert!(providers.anthropic.is_none());
        assert!(providers.gemini.is_none());
        assert!(providers.bodhi.is_none());
    }
}