enact-config 0.0.2

Unified configuration management for Enact - secure storage with keychain and encrypted files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
//! Configuration Types - Core configuration structure
//!
//! This module defines the configuration structure that matches the TypeScript schema.
//! It's kept in sync with packages/enact-schemas/src/config.schemas.ts

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::Path;
use std::str::FromStr;

/// Runtime mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum RuntimeMode {
    #[default]
    #[serde(rename = "local")]
    Local,
    #[serde(rename = "airgapped")]
    AirGapped,
    #[serde(rename = "cloud")]
    Cloud,
}

impl FromStr for RuntimeMode {
    type Err = std::convert::Infallible;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Ok(match value.to_ascii_lowercase().as_str() {
            "airgapped" => RuntimeMode::AirGapped,
            "cloud" => RuntimeMode::Cloud,
            _ => RuntimeMode::Local,
        })
    }
}

impl fmt::Display for RuntimeMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RuntimeMode::Local => write!(f, "local"),
            RuntimeMode::AirGapped => write!(f, "airgapped"),
            RuntimeMode::Cloud => write!(f, "cloud"),
        }
    }
}

/// Provider configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct Providers {
    pub azure: Option<AzureProvider>,
    pub anthropic: Option<AnthropicProvider>,
    pub openai: Option<OpenAIProvider>,
    pub ollama: Option<OllamaProvider>,
    pub google: Option<GoogleProvider>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AzureProvider {
    pub endpoint: Option<String>,
    pub api_key: Option<String>,
    pub deployment_name: Option<String>,
    #[serde(default = "default_api_version")]
    pub api_version: String,
}

fn default_api_version() -> String {
    "2024-02-15-preview".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnthropicProvider {
    pub api_key: Option<String>,
    #[serde(default = "default_anthropic_base_url")]
    pub base_url: String,
}

fn default_anthropic_base_url() -> String {
    "https://api.anthropic.com".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenAIProvider {
    pub api_key: Option<String>,
    #[serde(default = "default_openai_base_url")]
    pub base_url: String,
    pub organization: Option<String>,
}

fn default_openai_base_url() -> String {
    "https://api.openai.com/v1".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OllamaProvider {
    #[serde(default = "default_ollama_base_url")]
    pub base_url: String,
}

fn default_ollama_base_url() -> String {
    "http://localhost:11434".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GoogleProvider {
    pub api_key: Option<String>,
    #[serde(default = "default_google_base_url")]
    pub base_url: String,
}

fn default_google_base_url() -> String {
    "https://generativelanguage.googleapis.com/v1".to_string()
}

/// Runtime configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Runtime {
    #[serde(default)]
    pub mode: RuntimeMode,
    #[serde(default = "default_max_concurrent")]
    pub max_concurrent_executions: u32,
    #[serde(default = "default_timeout")]
    pub default_timeout: u64,
    #[serde(default = "default_true")]
    pub enable_telemetry: bool,
    #[serde(default = "default_true")]
    pub allow_network: bool,
}

fn default_max_concurrent() -> u32 {
    10
}

fn default_timeout() -> u64 {
    30000
}

fn default_true() -> bool {
    true
}

impl Default for Runtime {
    fn default() -> Self {
        Self {
            mode: RuntimeMode::Local,
            max_concurrent_executions: 10,
            default_timeout: 30000,
            enable_telemetry: true,
            allow_network: true,
        }
    }
}

/// Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct Storage {
    #[serde(default = "default_event_store")]
    pub event_store: EventStore,
    #[serde(default = "default_state_store")]
    pub state_store: StateStore,
    #[serde(default = "default_filesystem_store")]
    pub artifact_store: ArtifactStore,
    #[serde(default = "default_sqlite_vector_store")]
    pub vector_store: VectorStore,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EventStore {
    #[serde(default = "default_sqlite")]
    pub r#type: String,
    pub path: Option<String>,
    pub dsn: Option<String>,
}

fn default_sqlite() -> String {
    "sqlite".to_string()
}

impl Default for EventStore {
    fn default() -> Self {
        Self {
            r#type: "jsonl".to_string(),
            path: Some("events".to_string()),
            dsn: None,
        }
    }
}

fn default_event_store() -> EventStore {
    EventStore::default()
}

impl Default for StateStore {
    fn default() -> Self {
        Self {
            r#type: "jsonl".to_string(),
            path: Some("state".to_string()),
            dsn: None,
        }
    }
}

fn default_state_store() -> StateStore {
    StateStore::default()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StateStore {
    #[serde(default = "default_sqlite")]
    pub r#type: String,
    pub path: Option<String>,
    pub dsn: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ArtifactStore {
    #[serde(default = "default_filesystem")]
    pub r#type: String,
    pub path: Option<String>,
    #[serde(default = "default_zstd")]
    pub compression: String,
}

fn default_filesystem() -> String {
    "filesystem".to_string()
}

fn default_zstd() -> String {
    "zstd".to_string()
}

impl Default for ArtifactStore {
    fn default() -> Self {
        Self {
            r#type: "filesystem".to_string(),
            path: None,
            compression: "zstd".to_string(),
        }
    }
}

fn default_filesystem_store() -> ArtifactStore {
    ArtifactStore::default()
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VectorStore {
    #[serde(default = "default_sqlite")]
    pub r#type: String,
    pub url: Option<String>,
    pub collection: Option<String>,
    pub path: Option<String>,
    pub dsn: Option<String>,
}

impl Default for VectorStore {
    fn default() -> Self {
        Self {
            r#type: "sqlite".to_string(),
            url: None,
            collection: None,
            path: None,
            dsn: None,
        }
    }
}

fn default_sqlite_vector_store() -> VectorStore {
    VectorStore::default()
}

/// Tools configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct Tools {
    #[serde(default)]
    pub ingestion: IngestionTools,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct IngestionTools {
    #[serde(default = "default_pdf")]
    pub pdf: PdfIngestion,
    #[serde(default = "default_ocr")]
    pub ocr: OcrIngestion,
    #[serde(default = "default_embeddings")]
    pub embeddings: EmbeddingsIngestion,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PdfIngestion {
    #[serde(default = "default_pdfium")]
    pub engine: String,
}

impl Default for PdfIngestion {
    fn default() -> Self {
        Self {
            engine: "pdfium".to_string(),
        }
    }
}

fn default_pdfium() -> String {
    "pdfium".to_string()
}

fn default_pdf() -> PdfIngestion {
    PdfIngestion {
        engine: "pdfium".to_string(),
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OcrIngestion {
    #[serde(default = "default_tesseract")]
    pub engine: String,
    #[serde(default = "default_languages")]
    pub languages: Vec<String>,
}

impl Default for OcrIngestion {
    fn default() -> Self {
        Self {
            engine: "tesseract".to_string(),
            languages: vec!["eng".to_string()],
        }
    }
}

fn default_tesseract() -> String {
    "tesseract".to_string()
}

fn default_languages() -> Vec<String> {
    vec!["eng".to_string()]
}

fn default_ocr() -> OcrIngestion {
    OcrIngestion {
        engine: "tesseract".to_string(),
        languages: vec!["eng".to_string()],
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EmbeddingsIngestion {
    #[serde(default = "default_fastembed")]
    pub engine: String,
    pub model: Option<String>,
}

impl Default for EmbeddingsIngestion {
    fn default() -> Self {
        Self {
            engine: "fastembed".to_string(),
            model: None,
        }
    }
}

fn default_fastembed() -> String {
    "fastembed".to_string()
}

fn default_embeddings() -> EmbeddingsIngestion {
    EmbeddingsIngestion {
        engine: "fastembed".to_string(),
        model: None,
    }
}

/// Cloud configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Cloud {
    pub api_url: Option<String>,
    pub tenant_id: Option<String>,
    #[serde(default)]
    pub auto_sync: bool,
}

/// Human-in-the-loop approval configuration
///
/// Configures when and how tool calls require human approval before execution.
///
/// ## Policies
///
/// - `always_approve` - Auto-approve all tool calls (default)
/// - `always_deny` - Block all tool calls
/// - `ask` or `always_require` - Prompt user for every tool call
/// - `ask_once` - Prompt once per tool, remember decisions for session
/// - `pattern` - Only prompt for tools matching `require_patterns` regexes
///
/// ## Example YAML
///
/// ```yaml
/// approval:
///   enabled: true
///   policy: pattern
///   require_patterns:
///     - "Edit|Write|Bash"   # Prompt for file-modifying tools
///     - "mcp__.*"           # Prompt for all MCP tools
///   timeout_seconds: 300
///   tool_overrides:
///     Read: always_approve  # Auto-approve Read tool
///     Glob: always_approve  # Auto-approve Glob tool
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ApprovalConfig {
    /// Whether approval is enabled
    #[serde(default)]
    pub enabled: bool,

    /// Policy type: "always_approve", "always_deny", "ask", "ask_once", "pattern"
    #[serde(default = "default_approval_policy")]
    pub policy: String,

    /// Maximum steps before requiring approval (for threshold policy)
    pub max_steps: Option<usize>,

    /// Patterns that require approval (for pattern policy)
    /// e.g., ["Edit|Write|Bash", "mcp__.*"]
    pub require_patterns: Option<Vec<String>>,

    /// Timeout for waiting for approval (in seconds)
    #[serde(default = "default_approval_timeout")]
    pub timeout_seconds: u64,

    /// Per-tool policy overrides (tool_name -> policy)
    /// e.g., {"Read": "always_approve", "Bash": "ask"}
    #[serde(default)]
    pub tool_overrides: Option<std::collections::HashMap<String, String>>,
}

fn default_approval_policy() -> String {
    "always_approve".to_string()
}

fn default_approval_timeout() -> u64 {
    300 // 5 minutes
}

impl Default for ApprovalConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            policy: "always_approve".to_string(),
            max_steps: None,
            require_patterns: None,
            timeout_seconds: 300,
            tool_overrides: None,
        }
    }
}

/// Episodic memory configuration
///
/// Configures daily logs, session snapshots, and consolidation rules
/// for episodic (short-term) memory storage.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MemoryConfig {
    /// Memory backend: "sqlite", "markdown", "none"
    #[serde(default = "default_memory_backend")]
    pub backend: String,

    /// Directory for daily log files (relative to workspace)
    #[serde(default = "default_daily_logs_dir")]
    pub daily_logs_dir: String,

    /// Maximum entries per daily log before rolling
    #[serde(default = "default_max_daily_entries")]
    pub max_daily_entries: usize,

    /// Whether to automatically consolidate to semantic memory
    #[serde(default)]
    pub auto_consolidate: bool,

    /// Time of day to run consolidation (HH:MM format)
    pub consolidation_time: Option<String>,

    /// Number of days to retain episodic logs (None = forever)
    pub retention_days: Option<u32>,

    /// Whether to include timestamps in entries
    #[serde(default = "default_true")]
    pub include_timestamps: bool,
}

fn default_memory_backend() -> String {
    "markdown".to_string()
}

fn default_daily_logs_dir() -> String {
    "memory".to_string()
}

fn default_max_daily_entries() -> usize {
    100
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            backend: "markdown".to_string(),
            daily_logs_dir: "memory".to_string(),
            max_daily_entries: 100,
            auto_consolidate: true,
            consolidation_time: Some("03:00".to_string()),
            retention_days: Some(30),
            include_timestamps: true,
        }
    }
}

/// Session/conversation management configuration
///
/// Controls context rotation, idle timeouts, and cleanup behavior.
/// Can be overridden at agent or channel level using `SessionConfigOverride`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionConfig {
    /// Maximum conversation turns before context rotation.
    #[serde(default = "default_max_turns")]
    pub max_turns: usize,

    /// Rotate context when estimated token usage exceeds this percentage of model max.
    #[serde(default = "default_rotation_threshold_pct")]
    pub rotation_threshold_pct: u8,

    /// Rotate context after this many seconds of inactivity.
    #[serde(default = "default_idle_timeout_secs")]
    pub idle_timeout_secs: u64,

    /// Interval for cleanup task to remove stale conversations (seconds).
    #[serde(default = "default_cleanup_interval_secs")]
    pub cleanup_interval_secs: u64,

    /// Remove conversations idle longer than this (seconds).
    #[serde(default = "default_cleanup_idle_threshold_secs")]
    pub cleanup_idle_threshold_secs: u64,
}

fn default_max_turns() -> usize {
    20
}

fn default_rotation_threshold_pct() -> u8 {
    80
}

fn default_idle_timeout_secs() -> u64 {
    1800 // 30 minutes
}

fn default_cleanup_interval_secs() -> u64 {
    300 // 5 minutes
}

fn default_cleanup_idle_threshold_secs() -> u64 {
    3600 // 1 hour
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            max_turns: default_max_turns(),
            rotation_threshold_pct: default_rotation_threshold_pct(),
            idle_timeout_secs: default_idle_timeout_secs(),
            cleanup_interval_secs: default_cleanup_interval_secs(),
            cleanup_idle_threshold_secs: default_cleanup_idle_threshold_secs(),
        }
    }
}

/// Optional session config overrides for agent.yaml or channels.yaml.
///
/// Fields set to `None` inherit from the parent configuration level.
/// Override hierarchy: Channel > Agent > Global > Defaults
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct SessionConfigOverride {
    pub max_turns: Option<usize>,
    pub rotation_threshold_pct: Option<u8>,
    pub idle_timeout_secs: Option<u64>,
    pub cleanup_interval_secs: Option<u64>,
    pub cleanup_idle_threshold_secs: Option<u64>,
}

impl SessionConfigOverride {
    /// Apply this override onto a base SessionConfig.
    /// Fields that are `None` inherit from the base.
    pub fn apply_to(&self, base: &SessionConfig) -> SessionConfig {
        SessionConfig {
            max_turns: self.max_turns.unwrap_or(base.max_turns),
            rotation_threshold_pct: self
                .rotation_threshold_pct
                .unwrap_or(base.rotation_threshold_pct),
            idle_timeout_secs: self.idle_timeout_secs.unwrap_or(base.idle_timeout_secs),
            cleanup_interval_secs: self
                .cleanup_interval_secs
                .unwrap_or(base.cleanup_interval_secs),
            cleanup_idle_threshold_secs: self
                .cleanup_idle_threshold_secs
                .unwrap_or(base.cleanup_idle_threshold_secs),
        }
    }
}

/// HTTP/gRPC server configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ServerConfig {
    /// Port for the HTTP gateway (default: 8080)
    #[serde(default = "default_server_port")]
    pub port: u16,
    /// Host address to bind to (default: "0.0.0.0")
    #[serde(default = "default_server_host")]
    pub host: String,
    /// gRPC port (default: 50051)
    #[serde(default = "default_grpc_port")]
    pub grpc_port: u16,
    /// Documentation server port (default: 1111)
    #[serde(default = "default_docs_port")]
    pub docs_port: u16,
    /// Base URL for the docs server (e.g. "http://127.0.0.1:1111"). When unset, derived from docs_port.
    /// Used to rewrite asset URLs in HTML so CSS/JS load correctly when serving pre-built docs locally.
    #[serde(default)]
    pub docs_base_url: Option<String>,
}

fn default_server_port() -> u16 {
    8080
}

fn default_server_host() -> String {
    "0.0.0.0".to_string()
}

fn default_grpc_port() -> u16 {
    50051
}

fn default_docs_port() -> u16 {
    1111
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            port: default_server_port(),
            host: default_server_host(),
            grpc_port: default_grpc_port(),
            docs_port: default_docs_port(),
            docs_base_url: None,
        }
    }
}

/// Logging paths (relative to ENACT_HOME)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LoggingConfig {
    /// Path relative to ENACT_HOME for daemon log file
    #[serde(default = "default_daemon_log")]
    pub daemon_log: String,
    /// Path relative to ENACT_HOME for serve log file
    #[serde(default = "default_serve_log")]
    pub serve_log: String,
}

/// Observability configuration
///
/// Controls tracing, logging, and metrics for LLM calls, token usage,
/// memory access, guardrails, and context windows.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ObservabilityConfig {
    /// Enable LLM call tracing (start/end/failed events)
    #[serde(default = "default_true")]
    pub trace_llm_calls: bool,

    /// Log full prompts (expensive - use for debugging only)
    #[serde(default)]
    pub log_full_prompts: bool,

    /// Log full responses (expensive - use for debugging only)
    #[serde(default)]
    pub log_full_responses: bool,

    /// Track token usage and emit token.usage events
    #[serde(default = "default_true")]
    pub track_token_usage: bool,

    /// Trace memory access (recall/store events)
    #[serde(default = "default_true")]
    pub trace_memory_access: bool,

    /// Enable context window snapshots
    #[serde(default)]
    pub enable_context_snapshots: bool,

    /// Enable reasoning trace capture
    #[serde(default)]
    pub capture_reasoning_traces: bool,

    /// Maximum content length for logged prompts/responses (truncation limit)
    #[serde(default = "default_max_content_length")]
    pub max_content_length: usize,
}

fn default_max_content_length() -> usize {
    1000
}

impl Default for ObservabilityConfig {
    fn default() -> Self {
        Self {
            trace_llm_calls: true,
            log_full_prompts: false,
            log_full_responses: false,
            track_token_usage: true,
            trace_memory_access: true,
            enable_context_snapshots: false,
            capture_reasoning_traces: false,
            max_content_length: 1000,
        }
    }
}

fn default_daemon_log() -> String {
    "logs/daemon.log".to_string()
}

fn default_serve_log() -> String {
    "logs/serve.log".to_string()
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            daemon_log: default_daemon_log(),
            serve_log: default_serve_log(),
        }
    }
}

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Default model id for run/serve (e.g. azure_foundry:text:gpt-4-1-mini). Read from ~/.enact/config.yaml.
    #[serde(default)]
    pub default_model_id: Option<String>,
    #[serde(default)]
    pub providers: Providers,
    #[serde(default)]
    pub runtime: Runtime,
    #[serde(default)]
    pub storage: Storage,
    #[serde(default)]
    pub tools: Tools,
    pub cloud: Option<Cloud>,
    /// HTTP/gRPC server configuration
    #[serde(default)]
    pub server: ServerConfig,
    /// Human-in-the-loop approval configuration
    #[serde(default)]
    pub approval: ApprovalConfig,
    /// Memory configuration
    #[serde(default)]
    pub memory: MemoryConfig,
    /// Session/conversation management configuration
    #[serde(default)]
    pub session: SessionConfig,
    /// Log file paths (relative to ENACT_HOME)
    #[serde(default)]
    pub logging: LoggingConfig,
    /// Observability configuration (LLM tracing, token usage, memory access, etc.)
    #[serde(default)]
    pub observability: ObservabilityConfig,
}

impl Config {
    /// Load global config from ENACT_HOME/config.yaml.
    /// If the file does not exist, returns default config.
    pub fn load_from_home() -> Result<Self> {
        let path = crate::home::enact_home().join("config.yaml");
        Self::load_from_yaml_path(&path)
    }

    /// Write default config to `path` if the file does not exist.
    /// Used by install/doctor/serve to ensure config.yaml is present.
    pub fn ensure_default_at(path: &Path) -> Result<()> {
        if path.exists() {
            return Ok(());
        }
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).context("Failed to create config directory")?;
        }
        Self::default().save_to_yaml_path(path)
    }

    /// Save global config to ENACT_HOME/config.yaml.
    /// Creates a rolling backup of all config files before writing.
    pub fn save_to_home(&self) -> Result<()> {
        crate::home::create_config_backup()?;
        let path = crate::home::enact_home().join("config.yaml");
        self.save_to_yaml_path(&path)
    }

    /// Load config from a YAML file path.
    pub fn load_from_yaml_path(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let s = std::fs::read_to_string(path).context("Failed to read config file")?;
        let config: Config = serde_yaml::from_str(&s).context("Failed to parse config YAML")?;
        Ok(config)
    }

    /// Save config to a YAML file path.
    pub fn save_to_yaml_path(&self, path: &Path) -> Result<()> {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).context("Failed to create config directory")?;
        }
        let s = serde_yaml::to_string(self).context("Failed to serialize config to YAML")?;
        std::fs::write(path, s).context("Failed to write config file")?;
        Ok(())
    }
}