Skip to main content

oxios_kernel/
config.rs

1#![allow(missing_docs)]
2//! Configuration loading from TOML files.
3//!
4//! Configuration is stored at `~/.oxios/config.toml` and controls
5//! kernel, gateway, and execution settings.
6
7use cron::Schedule;
8use serde::{Deserialize, Serialize};
9use std::str::FromStr;
10
11use crate::email::{SmtpProvider, SmtpTls};
12use crate::types::Priority;
13
14/// Cron scheduler configuration.
15#[derive(Debug, Clone, Deserialize, Serialize)]
16pub struct CronConfig {
17    /// Enable the cron scheduler.
18    #[serde(default)]
19    pub enabled: bool,
20    /// Tick interval in seconds.
21    #[serde(default = "default_tick_interval")]
22    pub tick_interval_secs: u64,
23    /// Inline job definitions from config.toml.
24    #[serde(default)]
25    pub jobs: std::collections::HashMap<String, InlineCronJob>,
26}
27
28impl Default for CronConfig {
29    fn default() -> Self {
30        Self {
31            enabled: false,
32            tick_interval_secs: default_tick_interval(),
33            jobs: std::collections::HashMap::new(),
34        }
35    }
36}
37
38fn default_tick_interval() -> u64 {
39    60
40}
41
42/// Inline cron job definition in config.toml.
43#[derive(Debug, Clone, Deserialize, Serialize)]
44pub struct InlineCronJob {
45    /// Cron expression (e.g. "0 */6 * * *").
46    pub schedule: String,
47    /// Goal description for the agent.
48    pub goal: String,
49    /// Constraints on agent behavior.
50    #[serde(default)]
51    pub constraints: Vec<String>,
52    /// Criteria that must be met for the job to be considered successful.
53    #[serde(default)]
54    pub acceptance_criteria: Vec<String>,
55    /// Toolchain preset name.
56    #[serde(default = "default_toolchain_inline")]
57    pub toolchain: String,
58    /// Job priority.
59    #[serde(default)]
60    pub priority: Priority,
61    /// Whether the job is active.
62    #[serde(default = "default_true_inline")]
63    pub enabled: bool,
64}
65
66fn default_toolchain_inline() -> String {
67    "default".into()
68}
69
70fn default_true_inline() -> bool {
71    true
72}
73
74/// Memory system configuration.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct MemoryConfig {
77    /// Enable the memory system.
78    #[serde(default = "default_true")]
79    pub enabled: bool,
80    /// Maximum memories returned by recall.
81    #[serde(default = "default_max_recall")]
82    pub max_recall: usize,
83    /// Auto-summarize sessions on completion.
84    #[serde(default = "default_true")]
85    pub auto_summarize: bool,
86    /// Capture compaction summaries as conversation memory.
87    #[serde(default = "default_true")]
88    pub capture_compaction: bool,
89    /// Memory retention in days (0 = unlimited).
90    #[serde(default)]
91    pub retention_days: u32,
92    /// Enable embedding cache.
93    #[serde(default = "default_true")]
94    pub cache_enabled: bool,
95    /// Embedding cache TTL in seconds.
96    #[serde(default = "default_cache_ttl")]
97    pub cache_ttl_secs: u64,
98    /// Maximum embedding cache entries.
99    #[serde(default = "default_cache_max_entries")]
100    pub cache_max_entries: usize,
101    /// Consolidation configuration (RFC-008).
102    #[serde(default)]
103    pub consolidation: ConsolidationConfig,
104    /// SQLite memory storage configuration (RFC-012).
105    #[serde(default)]
106    pub sqlite: SqliteMemoryConfig,
107    /// Embedding provider configuration (RFC-012).
108    #[serde(default)]
109    pub embedding: EmbeddingConfig,
110    /// Learning configuration (RFC-012 Phase 4: SONA).
111    #[serde(default)]
112    pub learning: LearningConfig,
113    /// Knowledge dream configuration (RFC-022).
114    #[serde(default)]
115    pub knowledge_dream: crate::knowledge_dream::KnowledgeDreamConfig,
116    /// AutoMemoryBridge configuration (RFC-012 Phase 7: SQLite ↔ MEMORY.md sync).
117    #[serde(default)]
118    pub bridge: MemoryBridgeConfig,
119}
120
121fn default_true() -> bool {
122    true
123}
124
125fn default_max_recall() -> usize {
126    10
127}
128
129fn default_cache_ttl() -> u64 {
130    3600 // 1 hour
131}
132
133fn default_cache_max_entries() -> usize {
134    10000
135}
136
137impl Default for MemoryConfig {
138    fn default() -> Self {
139        Self {
140            enabled: true,
141            max_recall: 10,
142            auto_summarize: true,
143            capture_compaction: true,
144            retention_days: 0,
145            cache_enabled: true,
146            cache_ttl_secs: 3600,
147            cache_max_entries: 10000,
148            consolidation: ConsolidationConfig::default(),
149            sqlite: SqliteMemoryConfig::default(),
150            embedding: EmbeddingConfig::default(),
151            learning: LearningConfig::default(),
152            knowledge_dream: crate::knowledge_dream::KnowledgeDreamConfig::default(),
153            bridge: MemoryBridgeConfig::default(),
154        }
155    }
156}
157
158// ---------------------------------------------------------------------------
159// SqliteMemoryConfig (RFC-012: SQLite Memory Storage)
160// ---------------------------------------------------------------------------
161
162/// SQLite-backed memory storage configuration (RFC-012).
163///
164/// When enabled, memories are stored in a single `memory.db` file with
165/// FTS5 BM25 + sqlite-vec KNN search. Falls back to the existing JSON
166/// + TF-IDF approach when disabled.
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct SqliteMemoryConfig {
169    /// Enable SQLite-backed memory storage.
170    #[serde(default = "default_true")]
171    pub enabled: bool,
172    /// Path to the SQLite database file.
173    /// Empty string means default: `~/.oxios/workspace/memory.db`
174    #[serde(default)]
175    pub path: String,
176    /// Embedding vector dimension.
177    /// Controls the `vec0` virtual table dimension.
178    /// Common values: 128 (fast), 256 (balanced), 768 (full Gemma).
179    #[serde(default = "default_embedding_dim")]
180    pub embedding_dim: usize,
181    /// Enable WAL mode for concurrent reads.
182    #[serde(default = "default_true")]
183    pub wal_mode: bool,
184}
185
186fn default_embedding_dim() -> usize {
187    256
188}
189
190impl Default for SqliteMemoryConfig {
191    fn default() -> Self {
192        Self {
193            enabled: true,
194            path: String::new(),
195            embedding_dim: 256,
196            wal_mode: true,
197        }
198    }
199}
200
201// ---------------------------------------------------------------------------
202// EmbeddingConfig (RFC-012: Embedding Provider)
203// ---------------------------------------------------------------------------
204
205/// Embedding provider configuration (RFC-012).
206///
207/// Controls which embedding model is used for semantic search.
208/// When `embedding-mlx` feature is enabled and `provider = "mlx"`,
209/// uses EmbeddingGemma-300m via MLX on Apple Silicon.
210/// Otherwise falls back to TF-IDF.
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct EmbeddingConfig {
213    /// Embedding provider: "tfidf" (default) or "mlx" (Apple Silicon).
214    #[serde(default = "default_embedding_provider")]
215    pub provider: String,
216    /// Matryoshka dimension: 128, 256, 512, or 768.
217    /// Only used when provider = "mlx".
218    #[serde(default = "default_embedding_dim")]
219    pub dimension: usize,
220    /// Model TTL in seconds. Unloaded after this duration of inactivity.
221    /// Only used when provider = "mlx".
222    #[serde(default = "default_model_ttl")]
223    pub model_ttl_secs: u64,
224}
225
226fn default_embedding_provider() -> String {
227    "gguf".to_string()
228}
229
230fn default_model_ttl() -> u64 {
231    300 // 5 minutes
232}
233
234impl Default for EmbeddingConfig {
235    fn default() -> Self {
236        Self {
237            provider: default_embedding_provider(),
238            dimension: default_embedding_dim(),
239            model_ttl_secs: default_model_ttl(),
240        }
241    }
242}
243
244// ---------------------------------------------------------------------------
245// LearningConfig (RFC-012 Phase 4: SONA)
246// ---------------------------------------------------------------------------
247
248/// Learning engine configuration (RFC-012 Phase 4).
249///
250/// Controls SONA self-learning persistence.
251#[derive(Debug, Clone, Serialize, Deserialize)]
252pub struct LearningConfig {
253    /// Enable the learning subsystem (SONA).
254    #[serde(default = "default_true")]
255    pub enabled: bool,
256    /// SONA operating mode: "realtime", "balanced", "research", "edge".
257    #[serde(default = "default_sona_mode")]
258    pub sona_mode: String,
259    /// Interval between automatic distillation runs (hours).
260    #[serde(default = "default_distill_interval")]
261    pub distill_interval_hours: u64,
262    /// Minimum quality score for auto-promoting patterns to long-term.
263    #[serde(default = "default_auto_promote_quality")]
264    pub auto_promote_quality: f32,
265    /// Minimum usage count before auto-promotion is considered.
266    #[serde(default = "default_auto_promote_min_usage")]
267    pub auto_promote_min_usage: u32,
268}
269
270fn default_sona_mode() -> String {
271    "balanced".to_string()
272}
273
274fn default_distill_interval() -> u64 {
275    6
276}
277
278fn default_auto_promote_quality() -> f32 {
279    0.8
280}
281
282fn default_auto_promote_min_usage() -> u32 {
283    3
284}
285
286impl Default for LearningConfig {
287    fn default() -> Self {
288        Self {
289            enabled: true,
290            sona_mode: default_sona_mode(),
291            distill_interval_hours: default_distill_interval(),
292            auto_promote_quality: default_auto_promote_quality(),
293            auto_promote_min_usage: default_auto_promote_min_usage(),
294        }
295    }
296}
297
298// ---------------------------------------------------------------------------
299// MemoryBridgeConfig (RFC-012 Phase 7: SQLite ↔ MEMORY.md)
300// ---------------------------------------------------------------------------
301
302/// AutoMemoryBridge configuration (RFC-012 Phase 7).
303///
304/// Controls bidirectional sync between SQLite memory store
305/// and external MEMORY.md files.
306#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct MemoryBridgeConfig {
308    /// Enable bidirectional sync with MEMORY.md.
309    #[serde(default)]
310    pub sync_enabled: bool,
311    /// Sync interval in seconds.
312    #[serde(default = "default_bridge_interval")]
313    pub interval_secs: u64,
314}
315
316fn default_bridge_interval() -> u64 {
317    3600
318}
319
320impl Default for MemoryBridgeConfig {
321    fn default() -> Self {
322        Self {
323            sync_enabled: false,
324            interval_secs: default_bridge_interval(),
325        }
326    }
327}
328
329// ---------------------------------------------------------------------------
330// ConsolidationConfig (RFC-008: Memory Consolidation)
331// ---------------------------------------------------------------------------
332
333/// Memory consolidation configuration (RFC-008).
334/// All values have sensible defaults — users never need to configure these.
335#[derive(Debug, Clone, Serialize, Deserialize)]
336pub struct ConsolidationConfig {
337    /// Preset: "conservative" | "balanced" | "aggressive" | "custom".
338    /// When not "custom", all other fields are overridden by the preset values.
339    /// Call `apply_preset()` once during kernel init to resolve.
340    #[serde(default = "default_preset")]
341    pub preset: String,
342
343    // ── Dream Process ─────────────────────────────────
344    #[serde(default = "default_true")]
345    pub dream_enabled: bool,
346    #[serde(default = "default_dream_interval")]
347    pub dream_interval_hours: u64,
348    #[serde(default = "default_dream_min_sessions")]
349    pub dream_min_sessions: u32,
350
351    // ── Tier Budgets ──────────────────────────────────
352    #[serde(default = "default_hot_max")]
353    pub hot_max_entries: usize,
354    #[serde(default = "default_warm_max")]
355    pub warm_max_entries: usize,
356    #[serde(default = "default_cold_max")]
357    pub cold_max_entries: usize,
358    #[serde(default = "default_hot_token_budget")]
359    pub hot_token_budget: usize,
360
361    // ── Decay ─────────────────────────────────────────
362    #[serde(default = "default_true")]
363    pub decay_enabled: bool,
364    #[serde(default = "default_one")]
365    pub decay_multiplier: f32,
366    #[serde(default = "default_decay_threshold")]
367    pub decay_threshold: f32,
368    #[serde(default = "default_retention_days")]
369    pub retention_days: u32,
370
371    // ── Auto-Protection ───────────────────────────────
372    #[serde(default = "default_true")]
373    pub auto_protection: bool,
374    #[serde(default = "default_protection_low_access")]
375    pub protection_low_access: u32,
376    #[serde(default = "default_protection_medium_access")]
377    pub protection_medium_access: u32,
378    #[serde(default = "default_protection_high_access")]
379    pub protection_high_access: u32,
380    #[serde(default = "default_protection_medium_sessions")]
381    pub protection_medium_sessions: u32,
382    #[serde(default = "default_protection_high_sessions")]
383    pub protection_high_sessions: u32,
384
385    // ── Auto-Classification ───────────────────────────
386    #[serde(default = "default_true")]
387    pub auto_classification: bool,
388    #[serde(default = "default_type_promotion_threshold")]
389    pub type_promotion_repetitions: u32,
390
391    // ── Compaction ────────────────────────────────────
392    #[serde(default = "default_compaction_threshold")]
393    pub compaction_line_threshold: usize,
394    #[serde(default = "default_true")]
395    pub llm_compaction: bool,
396
397    // ── Dream LLM ──────────────────────────────────────
398    /// Optional model for Dream LLM operations (None = rule-based fallback).
399    #[serde(default)]
400    pub dream_model: Option<String>,
401
402    // ── Protection Demotion ────────────────────────────
403    #[serde(default = "default_true")]
404    pub protection_demotion_enabled: bool,
405    #[serde(default = "default_demotion_stale_days")]
406    pub protection_demotion_stale_days: u32,
407    #[serde(default = "default_demotion_max_step")]
408    pub protection_demotion_max_step: u32,
409
410    // ── Proactive Recall ──────────────────────────────
411    #[serde(default = "default_true")]
412    pub proactive_recall: bool,
413    #[serde(default = "default_proactive_limit")]
414    pub proactive_recall_limit: usize,
415    #[serde(default = "default_proactive_threshold")]
416    pub proactive_recall_threshold: f32,
417}
418
419fn default_dream_interval() -> u64 {
420    24
421}
422fn default_dream_min_sessions() -> u32 {
423    5
424}
425fn default_hot_max() -> usize {
426    50
427}
428fn default_warm_max() -> usize {
429    500
430}
431fn default_cold_max() -> usize {
432    10_000
433}
434fn default_hot_token_budget() -> usize {
435    3_000
436}
437fn default_one() -> f32 {
438    1.0
439}
440fn default_decay_threshold() -> f32 {
441    0.05
442}
443fn default_retention_days() -> u32 {
444    90
445}
446fn default_protection_low_access() -> u32 {
447    2
448}
449fn default_protection_medium_access() -> u32 {
450    3
451}
452fn default_protection_high_access() -> u32 {
453    5
454}
455fn default_protection_medium_sessions() -> u32 {
456    2
457}
458fn default_protection_high_sessions() -> u32 {
459    3
460}
461fn default_type_promotion_threshold() -> u32 {
462    3
463}
464fn default_compaction_threshold() -> usize {
465    200
466}
467fn default_proactive_limit() -> usize {
468    5
469}
470fn default_proactive_threshold() -> f32 {
471    0.6
472}
473fn default_demotion_stale_days() -> u32 {
474    30
475}
476fn default_demotion_max_step() -> u32 {
477    1
478}
479
480fn default_preset() -> String {
481    "balanced".into()
482}
483
484impl Default for ConsolidationConfig {
485    fn default() -> Self {
486        Self {
487            preset: default_preset(),
488            dream_enabled: true,
489            dream_interval_hours: 24,
490            dream_min_sessions: 5,
491            hot_max_entries: 50,
492            warm_max_entries: 500,
493            cold_max_entries: 10_000,
494            hot_token_budget: 3_000,
495            decay_enabled: true,
496            decay_multiplier: 1.0,
497            decay_threshold: 0.05,
498            retention_days: 90,
499            auto_protection: true,
500            protection_low_access: 2,
501            protection_medium_access: 3,
502            protection_high_access: 5,
503            protection_medium_sessions: 2,
504            protection_high_sessions: 3,
505            auto_classification: true,
506            type_promotion_repetitions: 3,
507            compaction_line_threshold: 200,
508            llm_compaction: true,
509            dream_model: None,
510            protection_demotion_enabled: true,
511            protection_demotion_stale_days: 30,
512            protection_demotion_max_step: 1,
513            proactive_recall: true,
514            proactive_recall_limit: 5,
515            proactive_recall_threshold: 0.6,
516        }
517    }
518}
519
520impl ConsolidationConfig {
521    /// Apply the preset to all fields.
522    /// Call once during kernel initialization.
523    /// When `preset` is "custom", individual fields are left untouched.
524    pub fn apply_preset(&mut self) {
525        let resolved = match self.preset.as_str() {
526            "conservative" => Self::conservative(),
527            "aggressive" => Self::aggressive(),
528            "custom" => return,
529            _ => Self::default(), // "balanced" 및 알 수 없는 값
530        };
531        *self = resolved;
532    }
533
534    /// Conservative preset: slow decay, long retention, larger capacities.
535    fn conservative() -> Self {
536        Self {
537            preset: "conservative".into(),
538            dream_enabled: true,
539            dream_interval_hours: 48,
540            dream_min_sessions: 10,
541            hot_max_entries: 100,
542            warm_max_entries: 1000,
543            cold_max_entries: 50_000,
544            hot_token_budget: 5_000,
545            decay_enabled: true,
546            decay_multiplier: 0.8,
547            decay_threshold: 0.05,
548            retention_days: 365,
549            auto_protection: true,
550            protection_low_access: 3,
551            protection_medium_access: 5,
552            protection_high_access: 10,
553            protection_medium_sessions: 3,
554            protection_high_sessions: 5,
555            auto_classification: true,
556            type_promotion_repetitions: 5,
557            compaction_line_threshold: 300,
558            llm_compaction: true,
559            dream_model: None,
560            protection_demotion_enabled: true,
561            protection_demotion_stale_days: 90,
562            protection_demotion_max_step: 1,
563            proactive_recall: true,
564            proactive_recall_limit: 8,
565            proactive_recall_threshold: 0.5,
566        }
567    }
568
569    /// Aggressive preset: fast decay, short retention, smaller capacities.
570    fn aggressive() -> Self {
571        Self {
572            preset: "aggressive".into(),
573            dream_enabled: true,
574            dream_interval_hours: 4,
575            dream_min_sessions: 2,
576            hot_max_entries: 20,
577            warm_max_entries: 100,
578            cold_max_entries: 1_000,
579            hot_token_budget: 2_000,
580            decay_enabled: true,
581            decay_multiplier: 1.0,
582            decay_threshold: 0.1,
583            retention_days: 30,
584            auto_protection: true,
585            protection_low_access: 1,
586            protection_medium_access: 2,
587            protection_high_access: 3,
588            protection_medium_sessions: 1,
589            protection_high_sessions: 2,
590            auto_classification: true,
591            type_promotion_repetitions: 2,
592            compaction_line_threshold: 150,
593            llm_compaction: true,
594            dream_model: None,
595            protection_demotion_enabled: true,
596            protection_demotion_stale_days: 14,
597            protection_demotion_max_step: 2,
598            proactive_recall: true,
599            proactive_recall_limit: 3,
600            proactive_recall_threshold: 0.7,
601        }
602    }
603}
604
605/// Channel activation configuration.
606#[derive(Debug, Clone, Deserialize, Serialize, Default)]
607pub struct ChannelsConfig {
608    /// List of channel names to activate on startup.
609    /// Channels are message-only interfaces (CLI, Telegram).
610    #[serde(default)]
611    pub enabled: Vec<String>,
612
613    /// Telegram-specific configuration.
614    #[serde(default)]
615    pub telegram: TelegramChannelConfig,
616}
617
618/// Surface activation configuration.
619///
620/// Surfaces are kernel-connected control interfaces (Web dashboard, future desktop apps).
621/// They have direct kernel access for management, monitoring, and configuration.
622#[derive(Debug, Clone, Deserialize, Serialize)]
623pub struct SurfacesConfig {
624    /// List of surface names to activate on startup.
625    /// Default: ["web"] if the web feature is compiled in.
626    #[serde(default = "default_surfaces_enabled")]
627    pub enabled: Vec<String>,
628}
629
630fn default_surfaces_enabled() -> Vec<String> {
631    vec!["web".to_string()]
632}
633
634impl Default for SurfacesConfig {
635    fn default() -> Self {
636        Self {
637            enabled: default_surfaces_enabled(),
638        }
639    }
640}
641
642/// Telegram channel configuration.
643#[derive(Debug, Clone, Deserialize, Serialize)]
644pub struct TelegramChannelConfig {
645    /// Environment variable name holding the bot token.
646    #[serde(default = "default_telegram_token_env")]
647    pub bot_token_env: String,
648    /// List of allowed Telegram user IDs (empty = allow all).
649    #[serde(default)]
650    pub allowed_users: Vec<i64>,
651    /// Telegram session management settings.
652    #[serde(default)]
653    pub session: TelegramSessionConfig,
654}
655
656fn default_telegram_token_env() -> String {
657    "TELEGRAM_BOT_TOKEN".to_string()
658}
659
660impl Default for TelegramChannelConfig {
661    fn default() -> Self {
662        Self {
663            bot_token_env: default_telegram_token_env(),
664            allowed_users: Vec::new(),
665            session: TelegramSessionConfig::default(),
666        }
667    }
668}
669
670/// LLM engine configuration.
671#[derive(Debug, Clone, Deserialize, Serialize)]
672#[allow(clippy::derivable_impls)]
673pub struct EngineConfig {
674    /// Default model in "provider/model" format.
675    /// Empty string means no model configured — onboarding required.
676    #[serde(default)]
677    pub default_model: String,
678    /// Explicit API key override (highest priority).
679    /// If empty/None, falls back to oxi auth store, then env vars.
680    /// Masked when serialized to API responses.
681    #[serde(default, skip_serializing)]
682    pub api_key: Option<String>,
683    /// Per-provider options for fine-grained control (thinking mode, etc.).
684    /// Passed through to `AgentLoopConfig::provider_options`.
685    #[serde(default)]
686    pub provider_options: Option<oxi_sdk::ProviderOptions>,
687    /// Enable complexity-based model routing.
688    /// When enabled, the engine can route simple tasks to cheaper models
689    /// and complex tasks to more capable ones.
690    #[serde(default)]
691    pub routing_enabled: bool,
692    /// Prefer cost-efficient models when routing.
693    #[serde(default)]
694    pub prefer_cost_efficient: bool,
695    /// Fallback models to try when the primary model fails.
696    #[serde(default)]
697    pub fallback_models: Vec<String>,
698    /// Models excluded from automatic routing.
699    #[serde(default)]
700    pub excluded_models: Vec<String>,
701}
702
703#[allow(clippy::derivable_impls)]
704impl Default for EngineConfig {
705    fn default() -> Self {
706        Self {
707            default_model: String::new(),
708            api_key: None,
709            provider_options: None,
710            routing_enabled: false,
711            prefer_cost_efficient: false,
712            fallback_models: Vec::new(),
713            excluded_models: Vec::new(),
714        }
715    }
716}
717
718/// Daemon mode configuration.
719#[derive(Debug, Clone, Deserialize, Serialize)]
720pub struct DaemonConfig {
721    /// PID file path.
722    #[serde(default = "default_pid_file")]
723    pub pid_file: String,
724    /// Log directory.
725    #[serde(default = "default_daemon_log_dir")]
726    pub log_dir: String,
727}
728
729fn default_pid_file() -> String {
730    dirs::home_dir()
731        .map(|h| format!("{}/.oxios/oxios.pid", h.display()))
732        .unwrap_or_else(|| "./oxios.pid".into())
733}
734
735fn default_daemon_log_dir() -> String {
736    dirs::home_dir()
737        .map(|h| format!("{}/.oxios/logs", h.display()))
738        .unwrap_or_else(|| "./logs".into())
739}
740
741impl Default for DaemonConfig {
742    fn default() -> Self {
743        Self {
744            pid_file: default_pid_file(),
745            log_dir: default_daemon_log_dir(),
746        }
747    }
748}
749
750/// Session management configuration.
751#[derive(Debug, Clone, Deserialize, Serialize)]
752pub struct SessionConfig {
753    /// Maximum number of sessions to retain.
754    /// When exceeded, oldest sessions (by `updated_at`) are pruned.
755    /// Set to 0 for unlimited.
756    #[serde(default = "default_max_sessions")]
757    pub max_sessions: usize,
758
759    /// Time-to-live for sessions in hours.
760    /// Sessions older than this are automatically pruned.
761    /// Set to 0 for unlimited (no TTL-based pruning).
762    #[serde(default = "default_session_ttl_hours")]
763    pub ttl_hours: u64,
764
765    /// Enable automatic session pruning on every session save.
766    #[serde(default = "default_true")]
767    pub auto_prune: bool,
768}
769
770fn default_max_sessions() -> usize {
771    100
772}
773
774fn default_session_ttl_hours() -> u64 {
775    168 // 7 days
776}
777
778impl Default for SessionConfig {
779    fn default() -> Self {
780        Self {
781            max_sessions: default_max_sessions(),
782            ttl_hours: default_session_ttl_hours(),
783            auto_prune: true,
784        }
785    }
786}
787
788/// RFC-025 Phase 5: Mount auto-promotion configuration.
789/// Controls the background scanner that promotes frequently-used paths into
790/// Mounts. See `mount::path_promotion`.
791#[derive(Debug, Clone, Deserialize, Serialize)]
792pub struct MountsConfig {
793    /// Enable the auto-promotion scanner.
794    #[serde(default = "default_true")]
795    pub auto_promote_enabled: bool,
796    /// Minimum distinct touches within the window to trigger promotion.
797    #[serde(default = "default_promote_threshold")]
798    pub auto_promote_threshold: usize,
799    /// How far back to look, in days.
800    #[serde(default = "default_promote_window_days")]
801    pub auto_promote_window_days: i64,
802    /// Seconds between promotion scans (background cadence).
803    #[serde(default = "default_promote_interval_secs")]
804    pub auto_promote_interval_secs: u64,
805}
806
807fn default_promote_threshold() -> usize {
808    3
809}
810
811fn default_promote_window_days() -> i64 {
812    14
813}
814
815fn default_promote_interval_secs() -> u64 {
816    3600 // hourly
817}
818
819impl Default for MountsConfig {
820    fn default() -> Self {
821        Self {
822            auto_promote_enabled: true,
823            auto_promote_threshold: default_promote_threshold(),
824            auto_promote_window_days: default_promote_window_days(),
825            auto_promote_interval_secs: default_promote_interval_secs(),
826        }
827    }
828}
829
830/// Telegram session management configuration.
831#[derive(Debug, Clone, Deserialize, Serialize)]
832pub struct TelegramSessionConfig {
833    /// Automatically rotate to a new session after this many hours of inactivity.
834    /// Set to 0 to disable time-based rotation.
835    #[serde(default = "default_telegram_session_rotation_hours")]
836    pub rotation_hours: u64,
837
838    /// Maximum number of messages per session before auto-rotating.
839    /// Set to 0 for unlimited.
840    #[serde(default = "default_telegram_session_max_messages")]
841    pub max_messages: usize,
842}
843
844fn default_telegram_session_rotation_hours() -> u64 {
845    2 // 2 hours
846}
847
848fn default_telegram_session_max_messages() -> usize {
849    0 // unlimited by default
850}
851
852impl Default for TelegramSessionConfig {
853    fn default() -> Self {
854        Self {
855            rotation_hours: default_telegram_session_rotation_hours(),
856            max_messages: default_telegram_session_max_messages(),
857        }
858    }
859}
860
861/// Top-level Oxios configuration.
862#[derive(Debug, Clone, Deserialize, Serialize, Default)]
863pub struct OxiosConfig {
864    /// Kernel settings.
865    pub kernel: KernelConfig,
866    /// LLM engine settings.
867    #[serde(default)]
868    pub engine: EngineConfig,
869    /// Daemon mode settings.
870    #[serde(default)]
871    pub daemon: DaemonConfig,
872    /// Gateway settings.
873    #[serde(default)]
874    pub gateway: GatewayConfig,
875    /// Orchestrator settings (Ouroboros protocol execution).
876    #[serde(default)]
877    pub orchestrator: OrchestratorConfig,
878    /// Context manager settings (LLM context window management).
879    #[serde(default)]
880    pub context: ContextConfig,
881    /// Security/access control settings.
882    #[serde(default)]
883    pub security: SecurityConfig,
884    /// Persona system settings.
885    #[serde(default)]
886    pub persona: PersonaConfig,
887    /// Memory system settings.
888    #[serde(default)]
889    pub memory: MemoryConfig,
890    /// Cron scheduler settings.
891    #[serde(default)]
892    pub cron: CronConfig,
893    /// MCP server configurations.
894    #[serde(default)]
895    pub mcp: McpConfig,
896    /// Git version control settings.
897    #[serde(default)]
898    pub git: GitConfig,
899    /// Audit trail configuration.
900    #[serde(default)]
901    pub audit: AuditConfig,
902    /// Budget enforcement configuration.
903    #[serde(default)]
904    pub budget: BudgetConfig,
905    /// Exec configuration (host command execution bridge).
906    #[serde(default)]
907    pub exec: ExecConfig,
908    /// Resource monitor configuration.
909    #[serde(default)]
910    pub resource_monitor: ResourceMonitorConfig,
911    /// OpenTelemetry tracing configuration.
912    #[serde(default)]
913    pub otel: OtelConfig,
914    /// Logging configuration.
915    #[serde(default)]
916    pub logging: LoggingConfig,
917    /// Channel activation configuration (message interfaces: CLI, Telegram).
918    #[serde(default)]
919    pub channels: ChannelsConfig,
920    /// Surface activation configuration (control interfaces: Web dashboard).
921    #[serde(default)]
922    pub surfaces: Option<SurfacesConfig>,
923    /// Headless browser configuration.
924    #[serde(default)]
925    pub browser: BrowserConfig,
926    /// Session management configuration.
927    #[serde(default)]
928    pub session: SessionConfig,
929    /// RFC-025: Mount system configuration (auto-promotion scanner).
930    #[serde(default)]
931    pub mounts: MountsConfig,
932    /// ClawHub marketplace configuration.
933    #[serde(default)]
934    pub marketplace: MarketplaceConfig,
935    /// Calendar configuration.
936    #[serde(default)]
937    pub calendar: CalendarConfig,
938    /// Email configuration.
939    #[serde(default)]
940    pub email: EmailConfig,
941    /// Agent history log configuration.
942    #[serde(default)]
943    pub agent_log: AgentLogConfig,
944}
945
946/// Kernel configuration.
947#[derive(Debug, Clone, Deserialize, Serialize)]
948pub struct KernelConfig {
949    /// Path to the workspace directory.
950    #[serde(default = "default_workspace")]
951    pub workspace: String,
952    /// Broadcast capacity for the event bus.
953    #[serde(default = "default_event_bus_capacity")]
954    pub event_bus_capacity: usize,
955    /// Maximum number of concurrent agents.
956    #[serde(default = "default_max_agents")]
957    pub max_agents: usize,
958}
959
960fn default_workspace() -> String {
961    dirs_home().unwrap_or_else(|| ".".into())
962}
963
964fn dirs_home() -> Option<String> {
965    dirs::home_dir().map(|h| format!("{}/.oxios/workspace", h.display()))
966}
967
968fn default_event_bus_capacity() -> usize {
969    256
970}
971
972fn default_max_agents() -> usize {
973    10
974}
975
976impl Default for KernelConfig {
977    fn default() -> Self {
978        Self {
979            workspace: default_workspace(),
980            event_bus_capacity: default_event_bus_capacity(),
981            max_agents: 10,
982        }
983    }
984}
985
986/// Gateway configuration.
987#[derive(Debug, Clone, Deserialize, Serialize)]
988pub struct GatewayConfig {
989    /// Host to bind the gateway to.
990    #[serde(default = "default_gateway_host")]
991    pub host: String,
992    /// Port for the gateway server.
993    #[serde(default = "default_gateway_port")]
994    pub port: u16,
995    /// Expose `/api-docs` (Swagger UI) and `/openapi.json`.
996    ///
997    /// For safety this is gated to localhost-only binds (127.0.0.0/8, ::1,
998    /// "localhost"). Setting this to `true` while binding to a public address
999    /// is a no-op. Default: `false`.
1000    ///
1001    /// Why: Swagger UI + the full OpenAPI schema expand the attack surface
1002    /// (route discovery, parameter names, security scheme details). Local
1003    /// dev typically wants them; production typically does not.
1004    #[serde(default)]
1005    pub expose_api_docs: bool,
1006    /// RFC-024 SP1: ceiling on `send_and_wait` for HTTP request-response
1007    /// matching. The HTTP layer returns 504 Gateway Timeout when the
1008    /// orchestrator does not respond within this duration.
1009    #[serde(default = "default_response_timeout_secs")]
1010    pub response_timeout_secs: u64,
1011    /// RFC-024 SP1: in-memory replay buffer tuning (per channel).
1012    #[serde(default)]
1013    pub reliability: GatewayReliabilityConfig,
1014}
1015
1016/// RFC-024 SP1: in-memory replay buffer tuning.
1017#[derive(Debug, Clone, Serialize, Deserialize)]
1018pub struct GatewayReliabilityConfig {
1019    /// Per-channel replay buffer size. Older messages are evicted when
1020    /// the buffer is full.
1021    #[serde(default = "default_replay_buffer_size")]
1022    pub replay_buffer_size: usize,
1023    /// How long a message stays in the replay buffer.
1024    #[serde(default = "default_replay_ttl_secs")]
1025    pub replay_ttl_secs: u64,
1026}
1027
1028impl Default for GatewayReliabilityConfig {
1029    fn default() -> Self {
1030        Self {
1031            replay_buffer_size: default_replay_buffer_size(),
1032            replay_ttl_secs: default_replay_ttl_secs(),
1033        }
1034    }
1035}
1036
1037fn default_response_timeout_secs() -> u64 {
1038    120
1039}
1040fn default_replay_buffer_size() -> usize {
1041    512
1042}
1043fn default_replay_ttl_secs() -> u64 {
1044    60
1045}
1046
1047impl GatewayConfig {
1048    /// Whether the gateway may expose `/api-docs` and `/openapi.json`.
1049    ///
1050    /// Returns `true` only when both:
1051    /// - `expose_api_docs` is explicitly enabled, AND
1052    /// - the bind address is a loopback address.
1053    pub fn should_expose_api_docs(&self) -> bool {
1054        if !self.expose_api_docs {
1055            return false;
1056        }
1057        let h = self.host.trim();
1058        h == "127.0.0.1" || h == "::1" || h == "localhost" || h.starts_with("127.")
1059    }
1060}
1061
1062/// ClawHub marketplace configuration.
1063#[derive(Debug, Clone, Deserialize, Serialize)]
1064pub struct MarketplaceConfig {
1065    /// Base URL for the ClawHub registry.
1066    /// Defaults to `https://clawhub.ai`.
1067    #[serde(default)]
1068    pub base_url: Option<String>,
1069    /// Whether the marketplace is enabled.
1070    #[serde(default = "default_true")]
1071    pub enabled: bool,
1072    /// Skills.sh (Vercel Labs ecosystem) configuration.
1073    #[serde(default)]
1074    pub skills_sh: SkillsShConfig,
1075}
1076
1077/// Skills.sh registry configuration.
1078#[derive(Debug, Clone, Deserialize, Serialize)]
1079pub struct SkillsShConfig {
1080    /// Base URL for the Skills.sh API.
1081    /// Defaults to `https://skills.sh`.
1082    #[serde(default)]
1083    pub base_url: Option<String>,
1084    /// API key for Skills.sh authentication.
1085    /// Falls back to `SKILLS_SH_TOKEN` env var if not set.
1086    #[serde(default)]
1087    pub api_key: Option<String>,
1088    /// Whether Skills.sh integration is enabled.
1089    #[serde(default = "default_true")]
1090    pub enabled: bool,
1091}
1092
1093impl Default for MarketplaceConfig {
1094    fn default() -> Self {
1095        Self {
1096            base_url: Some("https://clawhub.ai".to_string()),
1097            enabled: true,
1098            skills_sh: SkillsShConfig::default(),
1099        }
1100    }
1101}
1102
1103impl Default for SkillsShConfig {
1104    fn default() -> Self {
1105        Self {
1106            base_url: None,
1107            api_key: None,
1108            enabled: true,
1109        }
1110    }
1111}
1112
1113/// Calendar configuration.
1114#[derive(Debug, Clone, Deserialize, Serialize)]
1115pub struct CalendarConfig {
1116    /// Enable the calendar system.
1117    #[serde(default)]
1118    pub enabled: bool,
1119    /// Default timezone for events.
1120    #[serde(default = "default_calendar_timezone")]
1121    pub timezone: String,
1122    /// Default reminder minutes for new events.
1123    #[serde(default = "default_reminder_minutes")]
1124    pub default_reminder_minutes: Vec<u32>,
1125    /// Alarm dispatch channels.
1126    #[serde(default)]
1127    pub alarm_channels: Vec<String>,
1128    /// Journal sync mode: "on_open", "midnight", "both".
1129    #[serde(default = "default_journal_sync")]
1130    pub journal_sync: String,
1131    /// Show cron jobs on the calendar.
1132    #[serde(default = "default_true")]
1133    pub system_calendar: bool,
1134    /// Days after which old events are archived.
1135    #[serde(default = "default_archive_days")]
1136    pub archive_after_days: u32,
1137}
1138
1139fn default_calendar_timezone() -> String {
1140    "Asia/Seoul".to_string()
1141}
1142
1143fn default_reminder_minutes() -> Vec<u32> {
1144    vec![15]
1145}
1146
1147fn default_journal_sync() -> String {
1148    "on_open".to_string()
1149}
1150
1151fn default_archive_days() -> u32 {
1152    365
1153}
1154
1155impl Default for CalendarConfig {
1156    fn default() -> Self {
1157        Self {
1158            enabled: false,
1159            timezone: default_calendar_timezone(),
1160            default_reminder_minutes: default_reminder_minutes(),
1161            alarm_channels: vec![],
1162            journal_sync: default_journal_sync(),
1163            system_calendar: true,
1164            archive_after_days: default_archive_days(),
1165        }
1166    }
1167}
1168
1169/// Email configuration.
1170///
1171/// Controls SMTP email sending. When enabled, agents gain the `send_email` tool.
1172/// v1 sends to the user's own email only.
1173#[derive(Debug, Clone, Deserialize, Serialize)]
1174pub struct EmailConfig {
1175    /// Enable the email system.
1176    #[serde(default)]
1177    pub enabled: bool,
1178    /// The user's email address (used as both sender and default recipient).
1179    #[serde(default)]
1180    pub my_email: String,
1181    /// SMTP provider preset ("gmail", "icloud", "fastmail", "custom").
1182    #[serde(default = "default_email_provider")]
1183    pub provider: SmtpProvider,
1184    /// SMTP host (auto-filled from provider if empty).
1185    #[serde(default)]
1186    pub host: String,
1187    /// SMTP port (auto-filled from provider if 0).
1188    #[serde(default)]
1189    pub port: u16,
1190    /// TLS mode (auto-filled from provider if None).
1191    #[serde(default)]
1192    pub tls: Option<SmtpTls>,
1193    /// SMTP auth username (defaults to `my_email` if empty).
1194    #[serde(default)]
1195    pub user: String,
1196    /// Credential store key for the SMTP password.
1197    /// Falls back to `OXIOS_EMAIL_PASSWORD` env var.
1198    #[serde(default = "default_email_secret_ref")]
1199    pub secret_ref: String,
1200    /// Maximum emails per hour (rate limit, default: 10).
1201    #[serde(default = "default_rate_limit_emails")]
1202    pub rate_limit_per_hour: usize,
1203}
1204
1205fn default_email_provider() -> SmtpProvider {
1206    SmtpProvider::Gmail
1207}
1208
1209fn default_email_secret_ref() -> String {
1210    "email_smtp".to_string()
1211}
1212
1213fn default_rate_limit_emails() -> usize {
1214    10
1215}
1216
1217impl Default for EmailConfig {
1218    fn default() -> Self {
1219        Self {
1220            enabled: false,
1221            my_email: String::new(),
1222            provider: default_email_provider(),
1223            host: String::new(),
1224            port: 0,
1225            tls: None,
1226            user: String::new(),
1227            secret_ref: default_email_secret_ref(),
1228            rate_limit_per_hour: default_rate_limit_emails(),
1229        }
1230    }
1231}
1232
1233impl EmailConfig {
1234    /// Resolve the effective provider, falling back to Gmail.
1235    pub fn provider(&self) -> SmtpProvider {
1236        self.provider
1237    }
1238}
1239
1240fn default_gateway_host() -> String {
1241    "127.0.0.1".into()
1242}
1243
1244fn default_gateway_port() -> u16 {
1245    4200
1246}
1247
1248impl Default for GatewayConfig {
1249    fn default() -> Self {
1250        Self {
1251            host: default_gateway_host(),
1252            port: default_gateway_port(),
1253            expose_api_docs: false,
1254            response_timeout_secs: default_response_timeout_secs(),
1255            reliability: GatewayReliabilityConfig::default(),
1256        }
1257    }
1258}
1259
1260/// Execution mode for commands.
1261///
1262/// - `Structured`: Binary allowlist + metacharacter blocking (recommended)
1263/// - `Shell`: Raw bash execution (dangerous, requires `allow_shell_mode=true`)
1264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
1265#[serde(rename_all = "lowercase")]
1266pub enum ExecMode {
1267    /// Structured binary execution with allowlist and metacharacter blocking.
1268    #[default]
1269    Structured,
1270    /// Shell execution via `bash -c`. DANGEROUS — requires explicit enable.
1271    Shell,
1272}
1273
1274/// Execution allowlist behavior mode.
1275#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1276#[serde(rename_all = "snake_case")]
1277#[derive(Default)]
1278pub enum AllowlistMode {
1279    /// All binaries are permitted (development only).
1280    Permissive,
1281    /// Only binaries in `allowed_commands` may execute.
1282    #[default]
1283    Enforced,
1284}
1285
1286/// Exec configuration.
1287///
1288/// Governs how the kernel dispatches commands for execution.
1289#[derive(Debug, Clone, Deserialize, Serialize)]
1290pub struct ExecConfig {
1291    /// Default execution mode.
1292    #[serde(default)]
1293    pub default_mode: ExecMode,
1294    /// Allow shell mode. DANGEROUS — should be false in production.
1295    #[serde(default = "default_false")]
1296    pub allow_shell_mode: bool,
1297    /// Commands allowed to run on the host.
1298    /// If empty, *all* bare-name commands are permitted (development mode).
1299    #[serde(default)]
1300    pub allowed_commands: Vec<String>,
1301    /// Allowlist enforcement mode.
1302    /// `Permissive` = empty list means all allowed (dev mode).
1303    /// `Enforced` = only listed commands allowed (production).
1304    #[serde(default)]
1305    pub allowlist_mode: AllowlistMode,
1306    /// Default timeout for an exec call in seconds.
1307    #[serde(default = "default_exec_timeout")]
1308    pub default_timeout_secs: u64,
1309    /// Maximum allowed timeout for an exec call in seconds.
1310    #[serde(default = "default_exec_max_timeout")]
1311    pub max_timeout_secs: u64,
1312}
1313
1314fn default_false() -> bool {
1315    false
1316}
1317
1318fn default_exec_timeout() -> u64 {
1319    120
1320}
1321
1322fn default_exec_max_timeout() -> u64 {
1323    600
1324}
1325
1326impl ExecConfig {
1327    /// Check whether a binary / command name is allowed to execute.
1328    ///
1329    /// In `Permissive` mode, returns `true` when `allowed_commands` is empty
1330    /// (all allowed) **or** when the name is present in the allow-list.
1331    ///
1332    /// In `Enforced` mode, only names present in the allow-list are permitted.
1333    pub fn is_binary_allowed(&self, name: &str) -> bool {
1334        match self.allowlist_mode {
1335            AllowlistMode::Permissive => {
1336                self.allowed_commands.is_empty() || self.allowed_commands.iter().any(|c| c == name)
1337            }
1338            AllowlistMode::Enforced => self.allowed_commands.iter().any(|c| c == name),
1339        }
1340    }
1341}
1342
1343impl Default for ExecConfig {
1344    fn default() -> Self {
1345        Self {
1346            default_mode: ExecMode::default(),
1347            allow_shell_mode: default_false(),
1348            allowed_commands: Vec::new(),
1349            allowlist_mode: AllowlistMode::default(),
1350            default_timeout_secs: default_exec_timeout(),
1351            max_timeout_secs: default_exec_max_timeout(),
1352        }
1353    }
1354}
1355
1356/// Orchestrator configuration (Ouroboros protocol execution).
1357#[derive(Debug, Clone, Deserialize, Serialize)]
1358pub struct OrchestratorConfig {
1359    /// Maximum evolution iterations (0 = evaluate only, no evolution).
1360    /// Default: 3.
1361    #[serde(default = "default_max_evolution_iterations")]
1362    pub max_evolution_iterations: u32,
1363
1364    /// Minimum evaluation score for task to be considered passed (0.0–1.0).
1365    /// Default: 0.8.
1366    #[serde(default = "default_min_evaluation_score")]
1367    pub min_evaluation_score: f64,
1368}
1369
1370fn default_max_evolution_iterations() -> u32 {
1371    3
1372}
1373
1374fn default_min_evaluation_score() -> f64 {
1375    0.8
1376}
1377
1378impl Default for OrchestratorConfig {
1379    fn default() -> Self {
1380        Self {
1381            max_evolution_iterations: default_max_evolution_iterations(),
1382            min_evaluation_score: default_min_evaluation_score(),
1383        }
1384    }
1385}
1386
1387/// Intent engine configuration (RFC-027 unified intent handling).
1388///
1389/// Controls the unified intent engine that replaces the legacy Ouroboros
1390/// five-phase protocol: `assess` → `crystallize` → `execute` → `review` → `retry`.
1391#[derive(Debug, Clone, Serialize, Deserialize)]
1392pub struct IntentConfig {
1393    /// Maximum retry attempts when a Substantial task fails review.
1394    /// Set to 0 to disable retries entirely.
1395    /// Default: 2.
1396    #[serde(default = "default_intent_max_retries")]
1397    pub max_retries: u32,
1398
1399    /// Minimum review score (0.0–1.0) required for a verdict to pass.
1400    /// Reviews below this threshold trigger a retry.
1401    /// Default: 0.7.
1402    #[serde(default = "default_intent_score_threshold")]
1403    pub score_threshold: f64,
1404
1405    /// Maximum clarification rounds before forcing the task to proceed
1406    /// with the system's best-guess understanding.
1407    /// Default: 3.
1408    #[serde(default = "default_intent_max_clarify_rounds")]
1409    pub max_clarify_rounds: u32,
1410
1411    /// Whether to retry Substantial tasks whose review verdict fails.
1412    /// When false, a failing review is reported back to the user directly.
1413    /// Default: true.
1414    #[serde(default = "default_intent_enable_retry")]
1415    pub enable_retry: bool,
1416
1417    /// Optional lightweight model ID for `assess`/`crystallize`/`review` calls.
1418    /// When None, the engine uses the resolver's default model.
1419    /// Default: None.
1420    #[serde(default)]
1421    pub lightweight_model: Option<String>,
1422}
1423
1424fn default_intent_max_retries() -> u32 {
1425    2
1426}
1427
1428fn default_intent_score_threshold() -> f64 {
1429    0.7
1430}
1431
1432fn default_intent_max_clarify_rounds() -> u32 {
1433    3
1434}
1435
1436fn default_intent_enable_retry() -> bool {
1437    true
1438}
1439
1440impl Default for IntentConfig {
1441    fn default() -> Self {
1442        Self {
1443            max_retries: default_intent_max_retries(),
1444            score_threshold: default_intent_score_threshold(),
1445            max_clarify_rounds: default_intent_max_clarify_rounds(),
1446            enable_retry: default_intent_enable_retry(),
1447            lightweight_model: None,
1448        }
1449    }
1450}
1451
1452/// Context manager configuration (inspired by AIOS).
1453#[derive(Debug, Clone, Deserialize, Serialize)]
1454pub struct ContextConfig {
1455    /// Maximum tokens in the active (in-context) tier.
1456    #[serde(default = "default_active_limit")]
1457    pub active_limit_tokens: usize,
1458    /// Maximum entries in the cache tier.
1459    #[serde(default = "default_cache_limit")]
1460    pub cache_limit_entries: usize,
1461}
1462
1463fn default_active_limit() -> usize {
1464    100_000
1465}
1466
1467fn default_cache_limit() -> usize {
1468    50
1469}
1470
1471impl Default for ContextConfig {
1472    fn default() -> Self {
1473        Self {
1474            active_limit_tokens: default_active_limit(),
1475            cache_limit_entries: default_cache_limit(),
1476        }
1477    }
1478}
1479
1480/// Security/access control configuration (inspired by OWASP Agentic AI).
1481#[derive(Debug, Clone, Deserialize, Serialize)]
1482pub struct SecurityConfig {
1483    /// Default allowed tools for agents (least privilege).
1484    #[serde(default = "default_allowed_tools")]
1485    pub allowed_tools: Vec<String>,
1486    /// Whether agents can make network requests by default.
1487    #[serde(default)]
1488    pub network_access: bool,
1489    /// Maximum execution time in seconds for agent tasks.
1490    #[serde(default = "default_max_exec_time")]
1491    pub max_execution_time_secs: u64,
1492    /// Maximum memory in MB for agent tasks.
1493    #[serde(default = "default_max_memory")]
1494    pub max_memory_mb: u64,
1495    /// Whether agents can fork sub-agents by default.
1496    #[serde(default)]
1497    pub can_fork: bool,
1498    /// Maximum audit log entries to retain.
1499    #[serde(default = "default_max_audit")]
1500    pub max_audit_entries: usize,
1501    /// Enable API key authentication.
1502    #[serde(default)]
1503    pub auth_enabled: bool,
1504    /// Allowed CORS origins.
1505    #[serde(default = "default_cors_origins")]
1506    pub cors_origins: Vec<String>,
1507    /// Path for audit log file (optional, enables file-based persistence).
1508    #[serde(default)]
1509    pub audit_log_path: Option<String>,
1510    /// Rate limit for API endpoints (requests per minute).
1511    #[serde(default = "default_rate_limit_per_minute")]
1512    pub rate_limit_per_minute: u32,
1513}
1514
1515fn default_allowed_tools() -> Vec<String> {
1516    vec![
1517        "read".to_string(),
1518        "write".to_string(),
1519        "edit".to_string(),
1520        "bash".to_string(),
1521        "grep".to_string(),
1522        "find".to_string(),
1523        "exec".to_string(),
1524    ]
1525}
1526
1527fn default_max_exec_time() -> u64 {
1528    300
1529}
1530
1531fn default_max_memory() -> u64 {
1532    512
1533}
1534
1535fn default_max_audit() -> usize {
1536    10_000
1537}
1538
1539fn default_rate_limit_per_minute() -> u32 {
1540    120
1541}
1542
1543fn default_cors_origins() -> Vec<String> {
1544    // Browsers treat `localhost` and `127.0.0.1` as distinct origins, so both
1545    // must be allow-listed or cross-origin requests silently fail CORS checks.
1546    // 4200 = backend that also serves the production SPA (same origin).
1547    // 5173 = Vite dev server (`bun dev` in web/).
1548    vec![
1549        "http://localhost:4200".to_string(),
1550        "http://127.0.0.1:4200".to_string(),
1551        "http://localhost:5173".to_string(),
1552        "http://127.0.0.1:5173".to_string(),
1553    ]
1554}
1555
1556impl Default for SecurityConfig {
1557    fn default() -> Self {
1558        Self {
1559            allowed_tools: default_allowed_tools(),
1560            network_access: false,
1561            max_execution_time_secs: default_max_exec_time(),
1562            max_memory_mb: default_max_memory(),
1563            can_fork: false,
1564            max_audit_entries: default_max_audit(),
1565            auth_enabled: false,
1566            cors_origins: default_cors_origins(),
1567            audit_log_path: None,
1568            rate_limit_per_minute: default_rate_limit_per_minute(),
1569        }
1570    }
1571}
1572
1573/// Persona system configuration.
1574#[derive(Debug, Clone, Deserialize, Serialize)]
1575pub struct PersonaConfig {
1576    /// Default persona ID to activate on startup.
1577    #[serde(default)]
1578    pub default_persona_id: Option<String>,
1579    /// Maximum concurrent personas.
1580    #[serde(default = "default_max_concurrent_personas")]
1581    pub max_concurrent_personas: usize,
1582}
1583
1584fn default_max_concurrent_personas() -> usize {
1585    5
1586}
1587
1588impl Default for PersonaConfig {
1589    fn default() -> Self {
1590        Self {
1591            default_persona_id: Some("dev".to_string()),
1592            max_concurrent_personas: default_max_concurrent_personas(),
1593        }
1594    }
1595}
1596
1597/// MCP server configuration loaded from config.toml.
1598///
1599/// Each key is a server name; the value is a table with:
1600/// - `command`: executable to run (e.g. "npx", "python")
1601/// - `args`: arguments array
1602/// - `env`: optional map of environment variables
1603/// - `enabled`: whether to start this server on boot (default: true)
1604#[derive(Debug, Clone, Deserialize, Serialize, Default)]
1605pub struct McpConfig {
1606    /// Map of server-name → server definition.
1607    #[serde(default)]
1608    pub servers: std::collections::HashMap<String, McpServerDef>,
1609}
1610
1611/// A single MCP server definition in config.toml.
1612#[derive(Debug, Clone, Deserialize, Serialize)]
1613pub struct McpServerDef {
1614    /// Command to execute.
1615    pub command: String,
1616    /// Arguments passed to the command.
1617    #[serde(default)]
1618    pub args: Vec<String>,
1619    /// Environment variables.
1620    #[serde(default)]
1621    pub env: std::collections::HashMap<String, String>,
1622    /// Whether this server is enabled (default: true).
1623    #[serde(default = "default_mcp_enabled")]
1624    pub enabled: bool,
1625}
1626
1627fn default_mcp_enabled() -> bool {
1628    true
1629}
1630
1631/// Git version control configuration.
1632#[derive(Debug, Clone, Deserialize, Serialize)]
1633pub struct GitConfig {
1634    /// Enable automatic commits for state changes.
1635    #[serde(default = "default_true")]
1636    pub auto_commit: bool,
1637}
1638
1639impl Default for GitConfig {
1640    fn default() -> Self {
1641        Self { auto_commit: true }
1642    }
1643}
1644
1645/// Audit trail configuration.
1646#[derive(Debug, Clone, Deserialize, Serialize)]
1647pub struct AuditConfig {
1648    /// Maximum audit entries before pruning.
1649    #[serde(default = "default_audit_max_entries")]
1650    pub max_entries: usize,
1651    /// Enable audit trail.
1652    #[serde(default = "default_true")]
1653    pub enabled: bool,
1654}
1655
1656fn default_audit_max_entries() -> usize {
1657    100_000
1658}
1659
1660impl Default for AuditConfig {
1661    fn default() -> Self {
1662        Self {
1663            max_entries: default_audit_max_entries(),
1664            enabled: true,
1665        }
1666    }
1667}
1668
1669/// Budget enforcement configuration.
1670#[derive(Debug, Clone, Deserialize, Serialize)]
1671pub struct BudgetConfig {
1672    /// Default token budget per agent (0 = unlimited).
1673    #[serde(default)]
1674    pub default_token_budget: u64,
1675    /// Default call budget per agent (0 = unlimited).
1676    #[serde(default)]
1677    pub default_calls_budget: u64,
1678    /// Default budget window in seconds.
1679    #[serde(default = "default_budget_window")]
1680    pub default_window_secs: u64,
1681    /// Enable budget enforcement.
1682    #[serde(default = "default_true")]
1683    pub enabled: bool,
1684}
1685
1686fn default_budget_window() -> u64 {
1687    3600
1688}
1689
1690impl Default for BudgetConfig {
1691    fn default() -> Self {
1692        Self {
1693            default_token_budget: 0,
1694            default_calls_budget: 0,
1695            default_window_secs: default_budget_window(),
1696            enabled: true,
1697        }
1698    }
1699}
1700
1701/// Resource monitor configuration.
1702#[derive(Debug, Clone, Deserialize, Serialize)]
1703pub struct ResourceMonitorConfig {
1704    /// Snapshot interval in seconds.
1705    #[serde(default = "default_rm_interval")]
1706    pub interval_secs: u64,
1707    /// Maximum history entries.
1708    #[serde(default = "default_rm_history_max")]
1709    pub history_max: usize,
1710    /// CPU threshold for overload.
1711    #[serde(default = "default_rm_cpu_threshold")]
1712    pub cpu_threshold: f32,
1713    /// Memory threshold for overload (percentage).
1714    #[serde(default = "default_rm_mem_threshold")]
1715    pub memory_threshold: f32,
1716    /// Load average threshold for overload.
1717    #[serde(default = "default_rm_load_threshold")]
1718    pub load_threshold: f32,
1719}
1720
1721fn default_rm_interval() -> u64 {
1722    60
1723}
1724
1725fn default_rm_history_max() -> usize {
1726    60
1727}
1728
1729fn default_rm_cpu_threshold() -> f32 {
1730    90.0
1731}
1732
1733fn default_rm_mem_threshold() -> f32 {
1734    90.0
1735}
1736
1737fn default_rm_load_threshold() -> f32 {
1738    8.0
1739}
1740
1741impl Default for ResourceMonitorConfig {
1742    fn default() -> Self {
1743        Self {
1744            interval_secs: default_rm_interval(),
1745            history_max: default_rm_history_max(),
1746            cpu_threshold: default_rm_cpu_threshold(),
1747            memory_threshold: default_rm_mem_threshold(),
1748            load_threshold: default_rm_load_threshold(),
1749        }
1750    }
1751}
1752
1753/// OpenTelemetry tracing configuration.
1754#[derive(Debug, Clone, Deserialize, Serialize)]
1755pub struct OtelConfig {
1756    /// Enable OTLP export (default: false).
1757    #[serde(default)]
1758    pub enabled: bool,
1759    /// OTLP gRPC endpoint.
1760    #[serde(default = "default_otel_endpoint")]
1761    pub endpoint: String,
1762    /// Service name for traces.
1763    #[serde(default = "default_otel_service_name")]
1764    pub service_name: String,
1765    /// Sampling ratio (0.0 to 1.0).
1766    #[serde(default = "default_otel_sampling_ratio")]
1767    pub sampling_ratio: f64,
1768}
1769
1770fn default_otel_endpoint() -> String {
1771    "http://localhost:4317".into()
1772}
1773
1774fn default_otel_service_name() -> String {
1775    "oxios".into()
1776}
1777
1778fn default_otel_sampling_ratio() -> f64 {
1779    1.0
1780}
1781
1782impl Default for OtelConfig {
1783    fn default() -> Self {
1784        Self {
1785            enabled: false,
1786            endpoint: default_otel_endpoint(),
1787            service_name: default_otel_service_name(),
1788            sampling_ratio: default_otel_sampling_ratio(),
1789        }
1790    }
1791}
1792
1793/// Agent history log configuration.
1794#[derive(Debug, Clone, Serialize, Deserialize)]
1795pub struct AgentLogConfig {
1796    /// Maximum number of agent records to keep (0 = unlimited).
1797    #[serde(default = "default_agent_log_max_entries")]
1798    pub max_entries: usize,
1799    /// TTL for agent records in hours (0 = unlimited).
1800    #[serde(default = "default_agent_log_ttl_hours")]
1801    pub ttl_hours: u64,
1802    /// Max tool_calls per agent to persist (0 = unlimited).
1803    #[serde(default = "default_agent_log_max_tool_calls")]
1804    pub max_tool_calls_per_agent: usize,
1805    /// How many agents to prune per cycle.
1806    #[serde(default = "default_agent_log_prune_batch")]
1807    pub prune_batch_size: usize,
1808    /// Path to the SQLite database file (empty = default).
1809    #[serde(default)]
1810    pub db_path: String,
1811}
1812
1813fn default_agent_log_max_entries() -> usize {
1814    10_000
1815}
1816fn default_agent_log_ttl_hours() -> u64 {
1817    720
1818}
1819fn default_agent_log_max_tool_calls() -> usize {
1820    500
1821}
1822fn default_agent_log_prune_batch() -> usize {
1823    100
1824}
1825
1826impl Default for AgentLogConfig {
1827    fn default() -> Self {
1828        Self {
1829            max_entries: 10_000,
1830            ttl_hours: 720,
1831            max_tool_calls_per_agent: 500,
1832            prune_batch_size: 100,
1833            db_path: String::new(),
1834        }
1835    }
1836}
1837
1838/// Logging configuration.
1839#[derive(Debug, Clone, Deserialize, Serialize)]
1840pub struct LoggingConfig {
1841    /// Log format: "pretty", "json", or "compact".
1842    #[serde(default = "default_log_format")]
1843    pub format: String,
1844    /// Log level override (e.g. "info", "debug"). Falls back to RUST_LOG env var.
1845    #[serde(default)]
1846    pub level: Option<String>,
1847}
1848
1849fn default_log_format() -> String {
1850    "pretty".into()
1851}
1852
1853impl Default for LoggingConfig {
1854    fn default() -> Self {
1855        Self {
1856            format: default_log_format(),
1857            level: None,
1858        }
1859    }
1860}
1861
1862/// Headless browser configuration.
1863///
1864/// Engine configuration. Passes through to `oxi-sdk` browser tools.
1865/// with an `enabled` toggle. The engine config is passed through directly
1866/// to the browser — no field-by-field duplication.
1867#[derive(Debug, Clone, Deserialize, Serialize)]
1868pub struct BrowserConfig {
1869    /// Enable the browser integration.
1870    #[serde(default = "default_browser_enabled")]
1871    pub enabled: bool,
1872
1873    /// Engine configuration — passed to oxi-sdk's `native_browser_tools_with_config()`.
1874    ///
1875    /// All fields have sensible defaults; override only what you need:
1876    ///
1877    /// ```toml
1878    /// [browser.engine]
1879    /// user_agent = "MyBot/1.0"
1880    /// obey_robots = false
1881    /// js_timeout_ms = 10000
1882    /// ```
1883    #[serde(default)]
1884    pub engine: serde_json::Value,
1885}
1886
1887fn default_browser_enabled() -> bool {
1888    true
1889}
1890
1891impl Default for BrowserConfig {
1892    fn default() -> Self {
1893        Self {
1894            enabled: true,
1895            engine: serde_json::json!({}),
1896        }
1897    }
1898}
1899
1900/// Loads configuration from a TOML file.
1901pub fn load_config(path: &std::path::Path) -> anyhow::Result<OxiosConfig> {
1902    let content = std::fs::read_to_string(path)?;
1903    let config: OxiosConfig = toml::from_str(&content)?;
1904    let (errors, warnings) = config.validate();
1905    for w in warnings {
1906        tracing::warn!("config: {}", w);
1907    }
1908    if !errors.is_empty() {
1909        let msg = errors.join("; ");
1910        anyhow::bail!("Configuration validation failed: {msg}");
1911    }
1912    Ok(config)
1913}
1914
1915impl OxiosConfig {
1916    /// Returns the effective API key from the engine config.
1917    pub fn api_key(&self) -> Option<String> {
1918        self.engine.api_key.clone().filter(|k| !k.is_empty())
1919    }
1920
1921    /// Validate configuration values and return a list of warnings.
1922    /// Returns (errors, warnings). Empty errors = valid config.
1923    pub fn validate(&self) -> (Vec<String>, Vec<String>) {
1924        let mut errors = Vec::new();
1925        let mut warnings = Vec::new();
1926
1927        // Kernel validation
1928        if self.kernel.max_agents == 0 {
1929            errors.push("kernel.max_agents must be > 0".into());
1930        }
1931        if self.kernel.workspace.is_empty() {
1932            errors.push("kernel.workspace must not be empty".into());
1933        }
1934
1935        // Gateway validation
1936        if self.gateway.port == 0 {
1937            errors.push("gateway.port must be > 0".into());
1938        }
1939        if self.gateway.port < 1024 && self.gateway.host == "0.0.0.0" {
1940            warnings.push("Running on port <1024 as 0.0.0.0 may require root".into());
1941        }
1942
1943        // Cron validation
1944        for (name, job) in &self.cron.jobs {
1945            if job.schedule.is_empty() {
1946                errors.push(format!("cron.jobs.{name}: schedule is empty"));
1947            } else {
1948                // Normalize 5-field to 6-field (prepend "0 " for seconds)
1949                let normalized = {
1950                    let fields: Vec<&str> = job.schedule.split_whitespace().collect();
1951                    match fields.len() {
1952                        5 => format!("0 {}", job.schedule),
1953                        _ => job.schedule.clone(),
1954                    }
1955                };
1956                if Schedule::from_str(&normalized).is_err() {
1957                    errors.push(format!(
1958                        "cron.jobs.{}: invalid cron expression '{}'",
1959                        name, job.schedule
1960                    ));
1961                }
1962            }
1963            if job.goal.is_empty() {
1964                errors.push(format!("cron.jobs.{name}: goal is empty"));
1965            }
1966        }
1967
1968        // Security validation
1969        if self.security.max_execution_time_secs == 0 {
1970            warnings.push("security.max_execution_time_secs is 0 — no timeout".into());
1971        }
1972
1973        // Audit validation
1974        if self.audit.max_entries == 0 {
1975            warnings.push("audit.max_entries is 0 — audit will never prune".into());
1976        }
1977
1978        // Budget validation
1979        if self.budget.default_window_secs == 0 {
1980            warnings.push("budget.default_window_secs is 0 — no time window".into());
1981        }
1982
1983        // Gateway field-level validation
1984        if self.gateway.response_timeout_secs == 0 {
1985            errors.push("gateway.response_timeout_secs must be > 0".into());
1986        }
1987
1988        // Engine: warn when an API key is committed to config in plaintext.
1989        // The auth store and env-var fallback are preferred for secret hygiene.
1990        if self.engine.api_key.as_ref().is_some_and(|k| !k.is_empty()) {
1991            warnings.push(
1992                "engine.api_key is set in config — prefer the oxi auth store or env var to avoid storing a secret on disk"
1993                    .into(),
1994            );
1995        }
1996
1997        // MCP server validation: reject empty commands (would spawn a no-op).
1998        for (name, server) in &self.mcp.servers {
1999            if server.command.trim().is_empty() {
2000                errors.push(format!("mcp.servers.{name}: command must not be empty"));
2001            }
2002        }
2003
2004        // Session validation
2005        if self.session.max_sessions == 0 && self.session.ttl_hours == 0 && self.session.auto_prune
2006        {
2007            warnings.push("session: auto_prune is enabled but both max_sessions and ttl_hours are 0 — nothing will be pruned".into());
2008        }
2009
2010        // Exec validation
2011        if self.exec.default_timeout_secs == 0 {
2012            errors.push("exec.default_timeout_secs must be > 0".into());
2013        }
2014        if self.exec.max_timeout_secs == 0 {
2015            errors.push("exec.max_timeout_secs must be > 0".into());
2016        }
2017        if self.exec.default_timeout_secs > self.exec.max_timeout_secs {
2018            errors.push(format!(
2019                "exec.default_timeout_secs ({}) must not exceed max_timeout_secs ({})",
2020                self.exec.default_timeout_secs, self.exec.max_timeout_secs
2021            ));
2022        }
2023
2024        // Resource monitor validation
2025        if self.resource_monitor.cpu_threshold > 100.0 {
2026            errors.push("resource_monitor.cpu_threshold must be <= 100".into());
2027        }
2028        if self.resource_monitor.memory_threshold > 100.0 {
2029            errors.push("resource_monitor.memory_threshold must be <= 100".into());
2030        }
2031
2032        // Channels validation (message interfaces only)
2033        for name in &self.channels.enabled {
2034            let valid = ["cli", "telegram"];
2035            if !valid.contains(&name.as_str()) {
2036                warnings.push(format!("channels.enabled: unknown channel '{name}'"));
2037            }
2038        }
2039        // Warn if 'web' is listed in channels — it should be in surfaces
2040        if self.channels.enabled.iter().any(|c| c == "web") {
2041            warnings.push(
2042                "channels.enabled: 'web' should be listed under [surfaces], not [channels]".into(),
2043            );
2044        }
2045        if self.channels.enabled.iter().any(|c| c == "telegram")
2046            && std::env::var(&self.channels.telegram.bot_token_env).is_err()
2047        {
2048            warnings.push(format!(
2049                "channels.telegram: {} env var not set — telegram channel will fail",
2050                self.channels.telegram.bot_token_env
2051            ));
2052        }
2053
2054        (errors, warnings)
2055    }
2056}
2057
2058/// Expand `~/` in paths to the user's home directory.
2059///
2060/// Shared utility for path expansion across the binary and kernel.
2061///
2062/// Resolution order for the home directory:
2063/// 1. `$HOME` environment variable (preserves existing behavior).
2064/// 2. `dirs::home_dir()` (works in environments where HOME is unset, e.g.
2065///    systemd units, containers, cron jobs).
2066/// 3. If neither is available, the literal path is returned unchanged so the
2067///    caller still gets a usable `PathBuf` rather than a panic — the failure
2068///    will surface as a normal "path not found" downstream.
2069pub fn expand_home(path: &str) -> std::path::PathBuf {
2070    if let Some(rest) = path.strip_prefix("~/") {
2071        if let Ok(home) = std::env::var("HOME") {
2072            return std::path::PathBuf::from(format!("{home}/{rest}"));
2073        }
2074        if let Some(home) = dirs::home_dir() {
2075            return home.join(rest);
2076        }
2077    }
2078    std::path::PathBuf::from(path)
2079}
2080
2081#[cfg(test)]
2082mod tests {
2083    use super::*;
2084
2085    #[test]
2086    fn test_default_config_validates() {
2087        let config = OxiosConfig::default();
2088        let (errors, _warnings) = config.validate();
2089        assert!(
2090            errors.is_empty(),
2091            "Default config should have no errors: {:?}",
2092            errors
2093        );
2094    }
2095
2096    #[test]
2097    fn test_exec_config_default_allowed_commands() {
2098        let config = ExecConfig::default();
2099        // Default is Enforced mode — empty list means NOTHING allowed.
2100        assert!(config.allowed_commands.is_empty());
2101        assert_eq!(config.allowlist_mode, AllowlistMode::Enforced);
2102        assert!(!config.is_binary_allowed("anything"));
2103        assert!(!config.is_binary_allowed("bash"));
2104    }
2105
2106    #[test]
2107    fn test_exec_config_permissive_mode() {
2108        let config = ExecConfig {
2109            allowlist_mode: AllowlistMode::Permissive,
2110            ..Default::default()
2111        };
2112        // Permissive + empty list = all allowed
2113        assert!(config.is_binary_allowed("anything"));
2114        assert!(config.is_binary_allowed("bash"));
2115    }
2116
2117    #[test]
2118    fn test_is_binary_allowed_with_allowlist() {
2119        let config = ExecConfig {
2120            allowed_commands: vec!["git".into(), "echo".into()],
2121            ..Default::default()
2122        };
2123        assert!(config.is_binary_allowed("git"));
2124        assert!(config.is_binary_allowed("echo"));
2125        assert!(!config.is_binary_allowed("bash"));
2126        assert!(!config.is_binary_allowed("rm"));
2127        assert!(!config.is_binary_allowed("sudo"));
2128    }
2129
2130    #[test]
2131    fn test_expand_home() {
2132        // With HOME set.
2133        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp/testhome".into());
2134        let expanded = expand_home("~/projects/test");
2135        assert_eq!(
2136            expanded.to_str().unwrap(),
2137            format!("{}/projects/test", home)
2138        );
2139
2140        // Non-tilde path should pass through unchanged.
2141        let abs = expand_home("/absolute/path");
2142        assert_eq!(abs, std::path::PathBuf::from("/absolute/path"));
2143
2144        // Just ~ without slash should not expand.
2145        let bare = expand_home("~something");
2146        assert_eq!(bare, std::path::PathBuf::from("~something"));
2147    }
2148
2149    #[test]
2150    fn test_invalid_cron_expression() {
2151        let mut config = OxiosConfig::default();
2152        config.cron.enabled = true;
2153        config.cron.jobs.insert(
2154            "bad-job".to_string(),
2155            InlineCronJob {
2156                schedule: "not a valid cron".to_string(),
2157                goal: "Test goal".to_string(),
2158                constraints: vec![],
2159                acceptance_criteria: vec![],
2160                toolchain: "default".to_string(),
2161                priority: Priority::Normal,
2162                enabled: true,
2163            },
2164        );
2165
2166        let (errors, _warnings) = config.validate();
2167        assert!(
2168            !errors.is_empty(),
2169            "Expected validation error for invalid cron"
2170        );
2171        let has_cron_error = errors.iter().any(|e| e.contains("invalid cron expression"));
2172        assert!(
2173            has_cron_error,
2174            "Expected 'invalid cron expression' error, got: {:?}",
2175            errors
2176        );
2177    }
2178
2179    #[test]
2180    fn test_config_serialization_roundtrip() {
2181        let config = OxiosConfig::default();
2182
2183        // Serialize to TOML string.
2184        let toml_str = toml::to_string(&config).expect("serialization should succeed");
2185
2186        // Deserialize back.
2187        let deserialized: OxiosConfig =
2188            toml::from_str(&toml_str).expect("deserialization should succeed");
2189
2190        // Key fields should match.
2191        assert_eq!(config.kernel.max_agents, deserialized.kernel.max_agents);
2192        assert_eq!(config.kernel.workspace, deserialized.kernel.workspace);
2193        assert_eq!(config.gateway.host, deserialized.gateway.host);
2194        assert_eq!(config.gateway.port, deserialized.gateway.port);
2195        assert_eq!(
2196            config.exec.default_timeout_secs,
2197            deserialized.exec.default_timeout_secs
2198        );
2199        assert_eq!(
2200            config.exec.max_timeout_secs,
2201            deserialized.exec.max_timeout_secs
2202        );
2203    }
2204
2205    #[test]
2206    fn test_exec_timeout_validation() {
2207        let mut config = OxiosConfig::default();
2208        // default_timeout > max_timeout should be an error.
2209        config.exec.default_timeout_secs = 999;
2210        config.exec.max_timeout_secs = 100;
2211        let (errors, _warnings) = config.validate();
2212        let has_error = errors.iter().any(|e| e.contains("must not exceed"));
2213        assert!(
2214            has_error,
2215            "Expected timeout ordering error, got: {:?}",
2216            errors
2217        );
2218    }
2219
2220    #[test]
2221    fn test_zero_max_agents_error() {
2222        let mut config = OxiosConfig::default();
2223        config.kernel.max_agents = 0;
2224        let (errors, _warnings) = config.validate();
2225        assert!(errors.iter().any(|e| e.contains("max_agents must be > 0")));
2226    }
2227
2228    /// Rust Default와 share/default-config.toml 간 핵심 기본값 일치 확인.
2229    /// TOML 템플릿은 "프로덕션 준비" 기본값을 가지며,
2230    /// Rust Default는 "안전한 최소" 기본값을 가질 수 있음.
2231    /// 핵심 스칼라 값(포트, 호스트, max_agents 등)은 반드시 일치해야 함.
2232    #[test]
2233    fn test_default_config_matches_toml() {
2234        let from_rust = OxiosConfig::default();
2235
2236        let toml_str = include_str!("../../../share/default-config.toml");
2237        let from_toml: OxiosConfig =
2238            toml::from_str(toml_str).expect("share/default-config.toml이 유효하지 않습니다");
2239
2240        // 핵심 스칼라 필드 — Rust와 TOML이 반드시 일치해야 함
2241        assert_eq!(
2242            from_rust.kernel.max_agents, from_toml.kernel.max_agents,
2243            "kernel.max_agents 불일치: Rust={}, TOML={}",
2244            from_rust.kernel.max_agents, from_toml.kernel.max_agents
2245        );
2246        assert_eq!(
2247            from_rust.gateway.host, from_toml.gateway.host,
2248            "gateway.host 불일치: Rust={}, TOML={}",
2249            from_rust.gateway.host, from_toml.gateway.host
2250        );
2251        assert_eq!(
2252            from_rust.gateway.port, from_toml.gateway.port,
2253            "gateway.port 불일치: Rust={}, TOML={}",
2254            from_rust.gateway.port, from_toml.gateway.port
2255        );
2256        assert_eq!(
2257            from_rust.kernel.event_bus_capacity, from_toml.kernel.event_bus_capacity,
2258            "kernel.event_bus_capacity 불일치"
2259        );
2260        assert_eq!(
2261            from_rust.memory.consolidation.preset, from_toml.memory.consolidation.preset,
2262            "memory.consolidation.preset 불일치"
2263        );
2264
2265        // TOML 템플릿이 파싱 가능한지 확인
2266        let (_, warnings) = from_toml.validate();
2267        for w in &warnings {
2268            eprintln!("default-config.toml 경고: {}", w);
2269        }
2270    }
2271
2272    /// `gateway.expose_api_docs` is gated to loopback binds for safety.
2273    /// Verifies all four cases: opt-out, opt-in + public, opt-in + loopback.
2274    #[test]
2275    fn test_gateway_should_expose_api_docs() {
2276        // Default: opt-out — never expose.
2277        let cfg = GatewayConfig::default();
2278        assert!(!cfg.should_expose_api_docs());
2279
2280        // Opt-in + public bind (0.0.0.0) — still NOT exposed.
2281        let cfg = GatewayConfig {
2282            host: "0.0.0.0".into(),
2283            port: 4200,
2284            expose_api_docs: true,
2285            ..Default::default()
2286        };
2287        assert!(
2288            !cfg.should_expose_api_docs(),
2289            "public bind must not expose api docs even when opt-in is true"
2290        );
2291
2292        // Opt-in + loopback (127.0.0.1) — exposed.
2293        let cfg = GatewayConfig {
2294            host: "127.0.0.1".into(),
2295            port: 4200,
2296            expose_api_docs: true,
2297            ..Default::default()
2298        };
2299        assert!(cfg.should_expose_api_docs());
2300
2301        // Opt-in + ::1 — exposed.
2302        let cfg = GatewayConfig {
2303            host: "::1".into(),
2304            port: 4200,
2305            expose_api_docs: true,
2306            ..Default::default()
2307        };
2308        assert!(cfg.should_expose_api_docs());
2309
2310        // Opt-in + "localhost" — exposed.
2311        let cfg = GatewayConfig {
2312            host: "localhost".into(),
2313            port: 4200,
2314            expose_api_docs: true,
2315            ..Default::default()
2316        };
2317        assert!(cfg.should_expose_api_docs());
2318
2319        // Opt-out (explicit false) + loopback — NOT exposed.
2320        let cfg = GatewayConfig {
2321            host: "127.0.0.1".into(),
2322            port: 4200,
2323            expose_api_docs: false,
2324            ..Default::default()
2325        };
2326        assert!(!cfg.should_expose_api_docs());
2327    }
2328}