-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconfig.rs
More file actions
449 lines (402 loc) · 13.3 KB
/
config.rs
File metadata and controls
449 lines (402 loc) · 13.3 KB
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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
/// Model override configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ModelConfig {
/// Override embedding model URI (e.g., "hf:repo/file.gguf").
pub embed: Option<String>,
/// Override reranker model URI.
pub rerank: Option<String>,
/// Override expansion/orchestrator model URI.
pub expand: Option<String>,
}
/// Obsidian integration configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ObsidianConfig {
#[serde(default)]
pub enabled: bool,
pub vault_name: Option<String>,
pub cli_path: Option<PathBuf>,
}
/// Agent integration configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AgentsConfig {
#[serde(default)]
pub claude_code: bool,
#[serde(default)]
pub cursor: bool,
#[serde(default)]
pub windsurf: bool,
}
/// ChatGPT Actions plugin metadata.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PluginConfig {
pub name: Option<String>,
pub description: Option<String>,
pub contact_email: Option<String>,
pub public_url: Option<String>,
}
/// User identity for AI agent context.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct IdentityConfig {
pub name: Option<String>,
pub role: Option<String>,
pub vault_purpose: Option<String>,
}
/// Memory layer feature flags.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MemoryConfig {
pub identity_enabled: bool,
pub timeline_enabled: bool,
pub mining_enabled: bool,
pub mining_strategy: String,
pub mining_on_index: bool,
}
impl Default for MemoryConfig {
fn default() -> Self {
Self {
identity_enabled: true,
timeline_enabled: true,
mining_enabled: true,
mining_strategy: "auto".into(),
mining_on_index: true,
}
}
}
/// HTTP REST API configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct HttpConfig {
pub enabled: bool,
pub port: u16,
pub host: String,
pub rate_limit: u32, // requests per minute per key, 0 = unlimited
pub cors_origins: Vec<String>,
pub api_keys: Vec<ApiKeyConfig>,
#[serde(default)]
pub plugin: PluginConfig,
}
impl Default for HttpConfig {
fn default() -> Self {
Self {
enabled: false,
port: 3000,
host: "127.0.0.1".to_string(),
rate_limit: 60,
cors_origins: vec![],
api_keys: vec![],
plugin: PluginConfig::default(),
}
}
}
/// API key entry for HTTP authentication.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiKeyConfig {
pub key: String,
pub name: String,
pub permissions: String, // "read" | "write"
}
/// Application configuration, loaded from `~/.engraph/config.toml` with CLI overrides.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
/// Path to the Obsidian vault to index.
pub vault_path: Option<PathBuf>,
/// Number of results to return from search.
pub top_n: usize,
/// Glob patterns to exclude from indexing.
pub exclude: Vec<String>,
/// Number of files to process per embedding batch.
pub batch_size: usize,
/// Whether intelligence features are enabled. None = not yet configured.
pub intelligence: Option<bool>,
/// Model override URIs.
pub models: ModelConfig,
/// Obsidian integration settings.
#[serde(default)]
pub obsidian: ObsidianConfig,
/// Agent integration settings.
#[serde(default)]
pub agents: AgentsConfig,
/// HTTP REST API settings.
#[serde(default)]
pub http: HttpConfig,
#[serde(default)]
pub identity: IdentityConfig,
#[serde(default)]
pub memory: MemoryConfig,
}
impl Default for Config {
fn default() -> Self {
Self {
vault_path: None,
top_n: 5,
exclude: vec![".obsidian/".to_string()],
batch_size: 64,
intelligence: None,
models: ModelConfig::default(),
obsidian: ObsidianConfig::default(),
agents: AgentsConfig::default(),
http: HttpConfig::default(),
identity: IdentityConfig::default(),
memory: MemoryConfig::default(),
}
}
}
impl Config {
/// Canonical data directory: `~/.engraph/`.
pub fn data_dir() -> Result<PathBuf> {
let home = dirs::home_dir().context("could not determine home directory")?;
Ok(home.join(".engraph"))
}
/// Load config from `~/.engraph/config.toml`, falling back to defaults.
pub fn load() -> Result<Self> {
let config_path = Self::data_dir()?.join("config.toml");
if config_path.exists() {
let contents = std::fs::read_to_string(&config_path)
.with_context(|| format!("failed to read {}", config_path.display()))?;
let config: Config = toml::from_str(&contents)
.with_context(|| format!("failed to parse {}", config_path.display()))?;
Ok(config)
} else {
Ok(Config::default())
}
}
/// Merge CLI-provided values over the loaded config.
pub fn merge_vault_path(&mut self, path: Option<PathBuf>) {
if path.is_some() {
self.vault_path = path;
}
}
/// Merge CLI-provided top_n over the loaded config.
pub fn merge_top_n(&mut self, n: Option<usize>) {
if let Some(n) = n {
self.top_n = n;
}
}
/// Load vault profile from `~/.engraph/vault.toml`, if it exists.
pub fn load_vault_profile() -> Result<Option<crate::profile::VaultProfile>> {
let dir = Self::data_dir()?;
crate::profile::load_vault_toml(&dir)
}
/// Whether intelligence is enabled (defaults to false if not configured).
pub fn intelligence_enabled(&self) -> bool {
self.intelligence.unwrap_or(false)
}
/// Save config to a specific path.
pub fn save_to(&self, path: &Path) -> Result<()> {
let content = toml::to_string_pretty(self).context("serializing config")?;
std::fs::write(path, content).with_context(|| format!("writing {}", path.display()))?;
Ok(())
}
/// Load config from a specific path.
pub fn load_from(path: &Path) -> Result<Self> {
let contents =
std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let config: Config =
toml::from_str(&contents).with_context(|| format!("parsing {}", path.display()))?;
Ok(config)
}
/// Save to the default config path (`~/.engraph/config.toml`).
pub fn save(&self) -> Result<()> {
let path = Self::data_dir()?.join("config.toml");
std::fs::create_dir_all(path.parent().unwrap())?;
self.save_to(&path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_config_has_sane_values() {
let cfg = Config::default();
assert_eq!(cfg.top_n, 5);
assert_eq!(cfg.batch_size, 64);
assert_eq!(cfg.exclude, vec![".obsidian/"]);
assert!(cfg.vault_path.is_none());
}
#[test]
fn data_dir_ends_with_engraph() {
let dir = Config::data_dir().unwrap();
assert!(dir.ends_with(".engraph"));
}
#[test]
fn parse_config_toml() {
let toml_str = r#"
vault_path = "/tmp/vault"
top_n = 10
exclude = ["*.canvas", ".obsidian"]
batch_size = 128
"#;
let cfg: Config = toml::from_str(toml_str).unwrap();
assert_eq!(cfg.vault_path.unwrap(), PathBuf::from("/tmp/vault"));
assert_eq!(cfg.top_n, 10);
assert_eq!(cfg.exclude, vec!["*.canvas", ".obsidian"]);
assert_eq!(cfg.batch_size, 128);
}
#[test]
fn parse_partial_config_uses_defaults() {
let toml_str = r#"top_n = 20"#;
let cfg: Config = toml::from_str(toml_str).unwrap();
assert_eq!(cfg.top_n, 20);
assert_eq!(cfg.batch_size, 64); // default
assert!(cfg.vault_path.is_none());
}
#[test]
fn merge_overrides_when_present() {
let mut cfg = Config::default();
cfg.merge_vault_path(Some(PathBuf::from("/my/vault")));
cfg.merge_top_n(Some(42));
assert_eq!(cfg.vault_path.unwrap(), PathBuf::from("/my/vault"));
assert_eq!(cfg.top_n, 42);
}
#[test]
fn merge_preserves_when_none() {
let mut cfg = Config::default();
cfg.top_n = 10;
cfg.merge_top_n(None);
assert_eq!(cfg.top_n, 10);
}
#[test]
fn load_from_nonexistent_file_returns_defaults() {
// Config::load() reads from ~/.engraph/config.toml.
// If it doesn't exist, defaults are fine. We test the parsing path
// separately above. This just ensures load() doesn't panic.
let cfg = Config::load().unwrap();
assert_eq!(cfg.batch_size, 64);
}
#[test]
fn parse_intelligence_config() {
let toml_str = r#"
intelligence = true
[models]
embed = "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf"
rerank = "hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf"
"#;
let cfg: Config = toml::from_str(toml_str).unwrap();
assert_eq!(cfg.intelligence, Some(true));
assert!(cfg.models.embed.is_some());
assert!(cfg.models.rerank.is_some());
assert!(cfg.models.expand.is_none());
}
#[test]
fn intelligence_defaults_to_none() {
let cfg = Config::default();
assert!(cfg.intelligence.is_none());
assert!(cfg.models.embed.is_none());
}
#[test]
fn intelligence_false_disables_features() {
let toml_str = r#"intelligence = false"#;
let cfg: Config = toml::from_str(toml_str).unwrap();
assert_eq!(cfg.intelligence, Some(false));
assert!(!cfg.intelligence_enabled());
}
#[test]
fn test_config_backward_compat() {
// Old format: intelligence = true at top level
let toml = r#"intelligence = true"#;
let config: Config = toml::from_str(toml).unwrap();
assert_eq!(config.intelligence, Some(true));
// New fields default to None/false
assert!(!config.obsidian.enabled);
}
#[test]
fn test_config_with_obsidian() {
let toml = r#"
intelligence = true
[obsidian]
enabled = true
vault_name = "Personal"
"#;
let config: Config = toml::from_str(toml).unwrap();
assert!(config.obsidian.enabled);
assert_eq!(config.obsidian.vault_name.as_deref(), Some("Personal"));
}
#[test]
fn test_config_with_http() {
let toml = r#"
[http]
enabled = true
port = 8080
host = "0.0.0.0"
rate_limit = 120
cors_origins = ["https://chat.openai.com"]
[[http.api_keys]]
key = "eg_test123"
name = "test-key"
permissions = "read"
"#;
let config: Config = toml::from_str(toml).unwrap();
assert!(config.http.enabled);
assert_eq!(config.http.port, 8080);
assert_eq!(config.http.api_keys.len(), 1);
assert_eq!(config.http.api_keys[0].permissions, "read");
}
#[test]
fn test_config_http_defaults() {
let toml = r#"top_n = 5"#;
let config: Config = toml::from_str(toml).unwrap();
assert!(!config.http.enabled);
assert_eq!(config.http.port, 3000);
assert_eq!(config.http.host, "127.0.0.1");
assert_eq!(config.http.rate_limit, 60);
assert!(config.http.cors_origins.is_empty());
assert!(config.http.api_keys.is_empty());
}
#[test]
fn test_config_roundtrip_with_intelligence() {
let dir = tempfile::tempdir().unwrap();
let config_path = dir.path().join("config.toml");
let mut cfg = Config::default();
cfg.intelligence = Some(true);
cfg.models.embed = Some("hf:custom/model/embed.gguf".into());
cfg.save_to(&config_path).unwrap();
let loaded = Config::load_from(&config_path).unwrap();
assert_eq!(loaded.intelligence, Some(true));
assert_eq!(
loaded.models.embed,
Some("hf:custom/model/embed.gguf".into())
);
}
#[test]
fn test_config_with_plugin() {
let toml = r#"
[http.plugin]
name = "my-vault"
public_url = "https://vault.example.com"
"#;
let config: Config = toml::from_str(toml).unwrap();
assert_eq!(config.http.plugin.name.as_deref(), Some("my-vault"));
}
#[test]
fn test_identity_config_deserializes() {
let toml_str = r#"
[identity]
name = "Test User"
role = "Developer"
vault_purpose = "notes"
"#;
let config: Config = toml::from_str(toml_str).unwrap();
assert_eq!(config.identity.name, Some("Test User".into()));
assert_eq!(config.identity.role, Some("Developer".into()));
assert_eq!(config.identity.vault_purpose, Some("notes".into()));
}
#[test]
fn test_identity_config_defaults_to_empty() {
let config = Config::default();
assert!(config.identity.name.is_none());
assert!(config.identity.role.is_none());
}
#[test]
fn test_memory_config_defaults() {
let config = Config::default();
assert!(config.memory.identity_enabled);
assert!(config.memory.timeline_enabled);
assert!(config.memory.mining_enabled);
}
}