reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! ReasonKit Configuration Management
//!
//! Provides centralized configuration management for:
//! - ~/.config/reasonkit/ directory structure
//! - User-configurable defaults for CLI options
//! - Environment variable overrides
//! - Plugin registration and management
//! - Persistent settings across sessions

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Configuration errors
#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Config directory not found: {0}")]
    DirectoryNotFound(String),

    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Failed to parse config file: {0}")]
    ParseError(#[from] toml::de::Error),

    #[error("Failed to serialize config file: {0}")]
    SerializeError(#[from] toml::ser::Error),

    #[error("Invalid configuration: {0}")]
    #[allow(dead_code)] // Used by validate() method
    ValidationError(String),
}

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasonKitConfig {
    /// General settings
    pub general: GeneralConfig,

    /// LLM provider configurations
    pub providers: ProviderConfigs,

    /// ThinkTool specific settings
    pub thinktools: ThinkToolConfig,

    /// Knowledge base settings (requires 'memory' feature)
    #[cfg(feature = "memory")]
    pub knowledge_base: KnowledgeBaseConfig,

    /// Plugin configurations
    pub plugins: PluginConfigs,

    /// Output and display settings
    pub output: OutputConfig,

    /// Performance settings
    pub performance: PerformanceConfig,
}

/// General configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneralConfig {
    /// Default data directory
    pub data_dir: PathBuf,

    /// Default configuration file path
    pub config_file: Option<PathBuf>,

    /// Enable telemetry (anonymized usage data)
    pub enable_telemetry: bool,

    /// Log level (error, warn, info, debug, trace)
    pub log_level: String,

    /// Auto-update checks
    pub check_updates: bool,

    /// Experimental features
    pub experimental_features: Vec<String>,
}

/// LLM provider configurations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderConfigs {
    /// Default provider
    pub default_provider: String,

    /// API keys (sensitive data)
    #[serde(default)]
    pub api_keys: HashMap<String, String>,

    /// Provider-specific configurations
    #[serde(default)]
    pub configurations: HashMap<String, ProviderConfig>,
}

/// Provider-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderConfig {
    /// Default model for this provider
    pub default_model: String,

    /// API endpoint URL
    pub endpoint: Option<String>,

    /// Request timeout in seconds
    pub timeout: Option<u64>,

    /// Rate limiting settings
    pub rate_limit: Option<RateLimitConfig>,

    /// Fallback providers
    pub fallbacks: Vec<String>,
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfig {
    /// Requests per minute
    pub requests_per_minute: u32,

    /// Tokens per minute
    pub tokens_per_minute: Option<u64>,

    /// Concurrent requests
    pub concurrent_requests: u32,
}

/// ThinkTool configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThinkToolConfig {
    /// Default ThinkTool profile
    pub default_profile: String,

    /// Protocol-specific settings
    #[serde(default)]
    pub protocols: HashMap<String, ProtocolConfig>,

    /// Confidence thresholds
    pub confidence: ConfidenceThresholds,

    /// Budget defaults
    pub budget_defaults: BudgetDefaults,

    /// ThinkTool execution limits
    pub limits: ThinkToolLimits,
}

/// Protocol-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolConfig {
    /// Default temperature
    pub temperature: f64,

    /// Default token limit
    pub max_tokens: u32,

    /// Timeout in milliseconds
    pub timeout_ms: Option<u64>,

    /// Enable cross-validation
    pub enable_cross_validation: bool,

    /// Minimum confidence threshold
    pub min_confidence: f64,
}

/// Confidence thresholds
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceThresholds {
    /// Quick profile threshold
    pub quick: f64,

    /// Balanced profile threshold
    pub balanced: f64,

    /// Deep profile threshold
    pub deep: f64,

    /// Paranoid profile threshold
    pub paranoid: f64,

    /// Decide profile threshold
    pub decide: f64,

    /// Scientific profile threshold
    pub scientific: f64,

    /// Graph profile threshold
    pub graph: f64,

    /// Consistent profile threshold
    pub consistent: f64,

    /// Verified profile threshold
    pub verified: f64,
}

/// Budget defaults
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BudgetDefaults {
    /// Cost budget in USD
    pub cost: Option<f64>,

    /// Token budget
    pub tokens: Option<u64>,

    /// Time budget in seconds
    pub time: Option<u64>,

    /// Step budget
    pub steps: Option<usize>,
}

/// ThinkTool execution limits
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThinkToolLimits {
    /// Maximum steps per execution
    pub max_steps: usize,

    /// Maximum queries per day
    pub max_queries_per_day: Option<u32>,

    /// Maximum concurrent executions
    pub max_concurrent: usize,

    /// Maximum cache size
    pub max_cache_size_mb: u64,
}

/// Knowledge base configuration (memory feature)
#[cfg(feature = "memory")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnowledgeBaseConfig {
    /// Storage backend (qdrant, tantivy, sqlite)
    pub backend: String,

    /// Index configuration
    pub index: IndexConfig,

    /// Retrieval settings
    pub retrieval: RetrievalConfig,

    /// Embedding settings
    pub embedding: EmbeddingConfig,
}

/// Index configuration
#[cfg(feature = "memory")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexConfig {
    /// Chunk size for documents
    pub chunk_size: usize,

    /// Overlap between chunks
    pub chunk_overlap: usize,

    /// Index rebuild interval
    pub rebuild_interval_hours: u32,

    /// Enable real-time indexing
    pub real_time: bool,
}

/// Retrieval configuration
#[cfg(feature = "memory")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetrievalConfig {
    /// Default top-k results
    pub default_top_k: usize,

    /// BM25 weight
    pub bm25_weight: f32,

    /// Vector weight
    pub vector_weight: f32,

    /// RAPTOR tree depth
    pub raptor_depth: usize,

    /// Reranking enabled
    pub reranking_enabled: bool,
}

/// Embedding configuration
#[cfg(feature = "memory")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddingConfig {
    /// Model name
    pub model: String,

    /// Dimension size
    pub dimension: usize,

    /// Cache embeddings
    pub cache_enabled: bool,

    /// Cache TTL hours
    pub cache_ttl_hours: u32,
}

/// Plugin configurations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfigs {
    /// Plugin directory
    pub plugin_dir: PathBuf,

    /// Enabled plugins
    #[serde(default)]
    pub enabled: Vec<String>,

    /// Plugin-specific configurations
    #[serde(default)]
    pub configurations: HashMap<String, PluginConfig>,
}

/// Plugin-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig {
    /// Plugin version
    pub version: Option<String>,

    /// Plugin author
    pub author: Option<String>,

    /// Plugin description
    pub description: Option<String>,

    /// Plugin-specific settings
    #[serde(default)]
    pub settings: HashMap<String, toml::Value>,
}

/// Output configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputConfig {
    /// Default output format (text, json, markdown)
    pub default_format: String,

    /// Enable color output
    pub color: bool,

    /// Enable ANSI escape codes
    pub ansi: bool,

    /// Pretty-print JSON
    pub pretty_json: bool,

    /// Enable progress bars
    pub progress_bars: bool,

    /// Verbosity level (0-3)
    pub verbosity: u8,
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Enable caching
    pub caching_enabled: bool,

    /// Cache directory
    pub cache_dir: PathBuf,

    /// Cache TTL hours
    pub cache_ttl_hours: u32,

    /// Concurrent workers
    pub concurrent_workers: usize,

    /// Memory limit MB
    pub memory_limit_mb: Option<u64>,

    /// Performance monitoring enabled
    pub monitoring_enabled: bool,

    /// Alert threshold (0.05 = 5%)
    pub alert_threshold: f64,
}

/// Configuration manager
pub struct ConfigManager {
    config_dir: PathBuf,
    config_file: PathBuf,
    config: ReasonKitConfig,
    #[allow(dead_code)] // Will be used when override application is implemented
    overrides: HashMap<String, String>,
}

#[allow(dead_code)] // ConfigManager methods will be used as CLI is expanded
impl ConfigManager {
    /// Create a new configuration manager
    pub fn new() -> Result<Self, ConfigError> {
        let config_dir = Self::get_config_dir()?;
        let config_file = config_dir.join("config.toml");

        // Load or create default config
        let config = if config_file.exists() {
            Self::load_config(&config_file)?
        } else {
            Self::default_config()
        };

        Ok(Self {
            config_dir,
            config_file,
            config,
            overrides: HashMap::new(),
        })
    }

    /// Get the configuration directory
    pub fn get_config_dir() -> Result<PathBuf, ConfigError> {
        let mut config_dir = dirs::config_dir()
            .ok_or_else(|| ConfigError::DirectoryNotFound("User config directory".to_string()))?;

        config_dir.push("reasonkit");

        // Create directory if it doesn't exist
        if !config_dir.exists() {
            fs::create_dir_all(&config_dir)
                .map_err(|e| ConfigError::DirectoryNotFound(e.to_string()))?;
        }

        Ok(config_dir)
    }

    /// Load configuration from file
    pub fn load_config(path: &Path) -> Result<ReasonKitConfig, ConfigError> {
        let content = fs::read_to_string(path)?;
        let config = toml::from_str(&content)?;
        Ok(config)
    }

    /// Create default configuration
    pub fn default_config() -> ReasonKitConfig {
        ReasonKitConfig {
            general: GeneralConfig {
                data_dir: dirs::data_dir()
                    .map(|mut d| {
                        d.push("reasonkit");
                        d
                    })
                    .unwrap_or_else(|| PathBuf::from("./data")),
                config_file: None,
                enable_telemetry: true,
                log_level: "info".to_string(),
                check_updates: true,
                experimental_features: Vec::new(),
            },
            providers: ProviderConfigs {
                default_provider: "anthropic".to_string(),
                api_keys: HashMap::new(),
                configurations: HashMap::new(),
            },
            thinktools: ThinkToolConfig {
                default_profile: "balanced".to_string(),
                protocols: HashMap::new(),
                confidence: ConfidenceThresholds {
                    quick: 0.70,
                    balanced: 0.80,
                    deep: 0.85,
                    paranoid: 0.95,
                    decide: 0.85,
                    scientific: 0.90,
                    graph: 0.80,
                    consistent: 0.85,
                    verified: 0.90,
                },
                budget_defaults: BudgetDefaults {
                    cost: None,
                    tokens: Some(10000),
                    time: Some(30),
                    steps: Some(10),
                },
                limits: ThinkToolLimits {
                    max_steps: 20,
                    max_queries_per_day: Some(100),
                    max_concurrent: 4,
                    max_cache_size_mb: 100,
                },
            },
            #[cfg(feature = "memory")]
            knowledge_base: KnowledgeBaseConfig {
                backend: "sqlite".to_string(),
                index: IndexConfig {
                    chunk_size: 1000,
                    chunk_overlap: 200,
                    rebuild_interval_hours: 24,
                    real_time: true,
                },
                retrieval: RetrievalConfig {
                    default_top_k: 5,
                    bm25_weight: 0.5,
                    vector_weight: 0.5,
                    raptor_depth: 3,
                    reranking_enabled: true,
                },
                embedding: EmbeddingConfig {
                    model: "bge-base-en-v1.5".to_string(),
                    dimension: 768,
                    cache_enabled: true,
                    cache_ttl_hours: 24,
                },
            },
            plugins: PluginConfigs {
                plugin_dir: Self::get_config_dir()
                    .unwrap_or_else(|_| PathBuf::from("./plugins"))
                    .join("plugins"),
                enabled: Vec::new(),
                configurations: HashMap::new(),
            },
            output: OutputConfig {
                default_format: "text".to_string(),
                color: true,
                ansi: true,
                pretty_json: true,
                progress_bars: true,
                verbosity: 1,
            },
            performance: PerformanceConfig {
                caching_enabled: true,
                cache_dir: Self::get_config_dir()
                    .unwrap_or_else(|_| PathBuf::from("./cache"))
                    .join("cache"),
                cache_ttl_hours: 24,
                concurrent_workers: 4,
                memory_limit_mb: Some(512),
                monitoring_enabled: true,
                alert_threshold: 0.05,
            },
        }
    }

    /// Save configuration to file
    pub fn save(&self) -> Result<(), ConfigError> {
        let content = toml::to_string_pretty(&self.config)?;
        fs::write(&self.config_file, content)?;
        Ok(())
    }

    /// Get the current configuration
    pub fn config(&self) -> &ReasonKitConfig {
        &self.config
    }

    /// Get mutable configuration for updates
    pub fn config_mut(&mut self) -> &mut ReasonKitConfig {
        &mut self.config
    }

    /// Get configuration directory path
    pub fn config_dir(&self) -> &Path {
        &self.config_dir
    }

    /// Get config file path
    pub fn config_file(&self) -> &Path {
        &self.config_file
    }

    /// Set an override value
    pub fn set_override(&mut self, key: String, value: String) {
        self.overrides.insert(key, value);
    }

    /// Get configuration with overrides applied
    pub fn get_with_overrides(&self) -> ReasonKitConfig {
        // TODO: Apply overrides from self.overrides
        // In a full implementation, this would parse the keys and update nested values
        self.config.clone()
    }

    /// Reset to default configuration
    pub fn reset_defaults(&mut self) -> Result<(), ConfigError> {
        self.config = Self::default_config();
        self.save()
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<(), ConfigError> {
        // Validate confidence thresholds
        let thresholds = &self.config.thinktools.confidence;

        if thresholds.quick < 0.0 || thresholds.quick > 1.0 {
            return Err(ConfigError::ValidationError(
                "quick confidence must be between 0.0 and 1.0".to_string(),
            ));
        }

        if thresholds.balanced < 0.0 || thresholds.balanced > 1.0 {
            return Err(ConfigError::ValidationError(
                "balanced confidence must be between 0.0 and 1.0".to_string(),
            ));
        }

        if thresholds.deep < 0.0 || thresholds.deep > 1.0 {
            return Err(ConfigError::ValidationError(
                "deep confidence must be between 0.0 and 1.0".to_string(),
            ));
        }

        if thresholds.paranoid < 0.0 || thresholds.paranoid > 1.0 {
            return Err(ConfigError::ValidationError(
                "paranoid confidence must be between 0.0 and 1.0".to_string(),
            ));
        }

        // Validate consistency: should be quick < balanced < deep < paranoid
        if !(thresholds.quick <= thresholds.balanced
            && thresholds.balanced <= thresholds.deep
            && thresholds.deep <= thresholds.paranoid)
        {
            return Err(ConfigError::ValidationError(
                "confidence thresholds should be increasing: quick <= balanced <= deep <= paranoid"
                    .to_string(),
            ));
        }

        // Validate performance thresholds
        if self.config.performance.alert_threshold < 0.0
            || self.config.performance.alert_threshold > 1.0
        {
            return Err(ConfigError::ValidationError(
                "alert threshold must be between 0.0 and 1.0".to_string(),
            ));
        }

        Ok(())
    }

    /// Show current configuration
    pub fn show(&self) -> String {
        let mut output = String::new();
        output.push_str(&format!("Config file: {}\n", self.config_file.display()));
        output.push_str(&format!(
            "Config directory: {}\n\n",
            self.config_dir.display()
        ));

        output.push_str("General Settings:\n");
        output.push_str(&format!(
            "  Data directory: {}\n",
            self.config.general.data_dir.display()
        ));
        output.push_str(&format!("  Log level: {}\n", self.config.general.log_level));
        output.push_str(&format!(
            "  Telemetry: {}\n",
            self.config.general.enable_telemetry
        ));

        output.push_str("\nThinkTool Settings:\n");
        output.push_str(&format!(
            "  Default profile: {}\n",
            self.config.thinktools.default_profile
        ));
        output.push_str(&format!(
            "  Max steps: {}\n",
            self.config.thinktools.limits.max_steps
        ));

        output.push_str("  Confidence thresholds:\n");
        output.push_str(&format!(
            "    Quick: {:.0}%\n",
            self.config.thinktools.confidence.quick * 100.0
        ));
        output.push_str(&format!(
            "    Balanced: {:.0}%\n",
            self.config.thinktools.confidence.balanced * 100.0
        ));
        output.push_str(&format!(
            "    Deep: {:.0}%\n",
            self.config.thinktools.confidence.deep * 100.0
        ));
        output.push_str(&format!(
            "    Paranoid: {:.0}%\n",
            self.config.thinktools.confidence.paranoid * 100.0
        ));

        output.push_str("\nOutput Settings:\n");
        output.push_str(&format!(
            "  Default format: {}\n",
            self.config.output.default_format
        ));
        output.push_str(&format!("  Color output: {}\n", self.config.output.color));
        output.push_str(&format!("  Verbosity: {}\n", self.config.output.verbosity));

        output.push_str("\nPerformance Settings:\n");
        output.push_str(&format!(
            "  Caching: {}\n",
            self.config.performance.caching_enabled
        ));
        output.push_str(&format!(
            "  Concurrent workers: {}\n",
            self.config.performance.concurrent_workers
        ));
        output.push_str(&format!(
            "  Alert threshold: {:.1}%\n",
            self.config.performance.alert_threshold * 100.0
        ));

        output
    }

    /// Generate example configuration file
    pub fn generate_example_config() -> String {
        let config = Self::default_config();
        toml::to_string_pretty(&config)
            .unwrap_or_else(|_| "# ReasonKit Configuration Example\n# Auto-generated\n".to_string())
    }
}