zeph-config 0.19.1

Pure-data configuration types for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use serde::{Deserialize, Serialize};

use crate::defaults::{default_skill_paths, default_true};
use crate::learning::LearningConfig;
use crate::providers::ProviderName;
use crate::security::TrustConfig;

fn default_disambiguation_threshold() -> f32 {
    0.20
}

fn default_rl_learning_rate() -> f32 {
    0.01
}

fn default_rl_weight() -> f32 {
    0.3
}

fn default_rl_persist_interval() -> u32 {
    10
}

fn default_rl_warmup_updates() -> u32 {
    50
}

fn default_min_injection_score() -> f32 {
    0.20
}

fn default_cosine_weight() -> f32 {
    0.7
}

fn default_hybrid_search() -> bool {
    true
}

fn default_max_active_skills() -> usize {
    5
}

fn default_index_watch() -> bool {
    // Default off: watcher watches ALL files recursively and bypasses gitignore
    // filtering at the OS level. Projects with large .local/ or target/ directories
    // trigger continuous reindex loops, causing unbounded memory growth.
    // Users must explicitly opt in with `[index] watch = true`.
    false
}

fn default_index_search_enabled() -> bool {
    true
}

fn default_index_max_chunks() -> usize {
    12
}

fn default_index_concurrency() -> usize {
    4
}

fn default_index_batch_size() -> usize {
    32
}

fn default_index_memory_batch_size() -> usize {
    32
}

fn default_index_max_file_bytes() -> usize {
    512 * 1024
}

fn default_index_embed_concurrency() -> usize {
    2
}

fn default_index_score_threshold() -> f32 {
    0.25
}

fn default_index_budget_ratio() -> f32 {
    0.40
}

fn default_index_repo_map_tokens() -> usize {
    500
}

fn default_repo_map_ttl_secs() -> u64 {
    300
}

fn default_vault_backend() -> String {
    "env".into()
}

fn default_max_daily_cents() -> u32 {
    0
}

fn default_otlp_endpoint() -> String {
    "http://localhost:4317".into()
}

fn default_pid_file() -> String {
    "~/.zeph/zeph.pid".into()
}

fn default_health_interval() -> u64 {
    30
}

fn default_max_restart_backoff() -> u64 {
    60
}

fn default_scheduler_tick_interval() -> u64 {
    60
}

fn default_scheduler_max_tasks() -> usize {
    100
}

fn default_gateway_bind() -> String {
    "127.0.0.1".into()
}

fn default_gateway_port() -> u16 {
    8090
}

fn default_gateway_rate_limit() -> u32 {
    120
}

fn default_gateway_max_body() -> usize {
    1_048_576
}

/// Controls how skills are formatted in the system prompt.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SkillPromptMode {
    Full,
    Compact,
    #[default]
    Auto,
}

/// Skill discovery and matching configuration, nested under `[skills]` in TOML.
///
/// Controls where skills are loaded from, how they are ranked during retrieval,
/// the RL re-ranking head, NL skill generation, and automated skill mining.
///
/// # Example (TOML)
///
/// ```toml
/// [skills]
/// paths = ["~/.config/zeph/skills"]
/// max_active_skills = 5
/// disambiguation_threshold = 0.20
/// hybrid_search = true
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct SkillsConfig {
    /// Directories to scan for `*.skill.md` / `SKILL.md` files.
    #[serde(default = "default_skill_paths")]
    pub paths: Vec<String>,
    #[serde(default = "default_max_active_skills")]
    pub max_active_skills: usize,
    #[serde(default = "default_disambiguation_threshold")]
    pub disambiguation_threshold: f32,
    #[serde(default = "default_min_injection_score")]
    pub min_injection_score: f32,
    #[serde(default = "default_cosine_weight")]
    pub cosine_weight: f32,
    #[serde(default = "default_hybrid_search")]
    pub hybrid_search: bool,
    #[serde(default)]
    pub learning: LearningConfig,
    #[serde(default)]
    pub trust: TrustConfig,
    #[serde(default)]
    pub prompt_mode: SkillPromptMode,
    /// Enable two-stage category-first skill matching (requires `category` set in SKILL.md).
    /// Falls back to flat matching when no multi-skill categories are available.
    #[serde(default)]
    pub two_stage_matching: bool,
    /// Warn when any two skills have cosine similarity ≥ this threshold.
    /// Set to 0.0 (default) to disable the confusability check entirely.
    #[serde(default)]
    pub confusability_threshold: f32,

    // --- SkillOrchestra: RL routing head ---
    /// Enable RL routing head for skill re-ranking (disabled by default).
    #[serde(default)]
    pub rl_routing_enabled: bool,
    /// Learning rate for REINFORCE weight updates.
    #[serde(default = "default_rl_learning_rate")]
    pub rl_learning_rate: f32,
    /// Blend weight: `final_score = (1-rl_weight)*cosine + rl_weight*rl_score`.
    #[serde(default = "default_rl_weight")]
    pub rl_weight: f32,
    /// Persist weights every N updates (0 = persist every update).
    #[serde(default = "default_rl_persist_interval")]
    pub rl_persist_interval: u32,
    /// Skip RL blending for the first N updates (cold-start warmup).
    #[serde(default = "default_rl_warmup_updates")]
    pub rl_warmup_updates: u32,
    /// Embedding dimension for the RL routing head.
    /// Must match the output dimension of the configured embedding provider.
    /// Defaults to `None` → 1536 (`text-embedding-3-small` output dimension).
    #[serde(default)]
    pub rl_embed_dim: Option<usize>,

    // --- NL skill generation ---
    /// Provider name for `/skill create` NL generation. Empty = primary provider.
    #[serde(default)]
    pub generation_provider: ProviderName,
    /// Directory where generated skills are written. Defaults to first entry in `paths`.
    #[serde(default)]
    pub generation_output_dir: Option<String>,
    /// Skill mining configuration.
    #[serde(default)]
    pub mining: SkillMiningConfig,
}

fn default_max_repos_per_query() -> usize {
    20
}

fn default_dedup_threshold() -> f32 {
    0.85
}

fn default_rate_limit_rpm() -> u32 {
    25
}

/// Configuration for the automated skill mining pipeline (`zeph-skills-miner` binary).
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SkillMiningConfig {
    /// GitHub search queries for repo discovery (e.g. "topic:cli-tool language:rust stars:>100").
    #[serde(default)]
    pub queries: Vec<String>,
    /// Maximum repos to fetch per query (capped at 100 by GitHub API). Default: 20.
    #[serde(default = "default_max_repos_per_query")]
    pub max_repos_per_query: usize,
    /// Cosine similarity threshold for dedup against existing skills. Default: 0.85.
    #[serde(default = "default_dedup_threshold")]
    pub dedup_threshold: f32,
    /// Output directory for mined skills.
    #[serde(default)]
    pub output_dir: Option<String>,
    /// Provider name for skill generation during mining. Empty = primary provider.
    #[serde(default)]
    pub generation_provider: ProviderName,
    /// Provider name for embedding during dedup. Empty = primary provider.
    #[serde(default)]
    pub embedding_provider: ProviderName,
    /// Maximum GitHub search requests per minute. Default: 25.
    #[serde(default = "default_rate_limit_rpm")]
    pub rate_limit_rpm: u32,
}

/// Code indexing and repo-map configuration, nested under `[index]` in TOML.
///
/// When `enabled = true`, the agent indexes source files into Qdrant for semantic
/// code search. The repo map is injected into the system prompt or served via
/// `IndexMcpServer` tool calls when `mcp_enabled = true`.
///
/// # Example (TOML)
///
/// ```toml
/// [index]
/// enabled = true
/// watch = false
/// max_chunks = 12
/// score_threshold = 0.25
/// ```
#[derive(Debug, Deserialize, Serialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct IndexConfig {
    /// Enable code indexing. Default: `false`.
    #[serde(default)]
    pub enabled: bool,
    /// Enable semantic code search tool. Default: `true` (no-op when `enabled = false`).
    #[serde(default = "default_index_search_enabled")]
    pub search_enabled: bool,
    #[serde(default = "default_index_watch")]
    pub watch: bool,
    #[serde(default = "default_index_max_chunks")]
    pub max_chunks: usize,
    #[serde(default = "default_index_score_threshold")]
    pub score_threshold: f32,
    #[serde(default = "default_index_budget_ratio")]
    pub budget_ratio: f32,
    #[serde(default = "default_index_repo_map_tokens")]
    pub repo_map_tokens: usize,
    #[serde(default = "default_repo_map_ttl_secs")]
    pub repo_map_ttl_secs: u64,
    /// Enable `IndexMcpServer` tools (`symbol_definition`, `find_text_references`, `call_graph`,
    /// `module_summary`). When `true`, static repo-map injection is skipped and the LLM
    /// uses on-demand tool calls instead.
    #[serde(default)]
    pub mcp_enabled: bool,
    /// Root directory to index. When `None`, falls back to the current working directory at
    /// startup. Relative paths are resolved relative to the process working directory.
    #[serde(default)]
    pub workspace_root: Option<std::path::PathBuf>,
    /// Number of files to process concurrently during initial indexing. Default: 4.
    #[serde(default = "default_index_concurrency")]
    pub concurrency: usize,
    /// Maximum number of new chunks to batch into a single Qdrant upsert per file. Default: 32.
    #[serde(default = "default_index_batch_size")]
    pub batch_size: usize,
    /// Number of files to process per memory batch during initial indexing.
    /// After each batch the stream is dropped and the executor yields to allow
    /// the allocator to reclaim pages. Default: `32`.
    #[serde(default = "default_index_memory_batch_size")]
    pub memory_batch_size: usize,
    /// Maximum file size in bytes to index. Files larger than this are skipped.
    /// Protects against large generated files (e.g. lock files, minified JS).
    /// Default: 512 KiB.
    #[serde(default = "default_index_max_file_bytes")]
    pub max_file_bytes: usize,
    /// Name of a `[[llm.providers]]` entry to use exclusively for embedding calls during
    /// indexing. A dedicated provider prevents the indexer from contending with the guardrail
    /// at the API server level (rate limits, Ollama single-model lock). When unset or empty,
    /// falls back to the main agent provider.
    #[serde(default)]
    pub embed_provider: Option<String>,
    /// Maximum parallel `embed_batch` calls during indexing (default: 2 to stay within provider
    /// TPM limits).
    #[serde(default = "default_index_embed_concurrency")]
    pub embed_concurrency: usize,
}

impl Default for IndexConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            search_enabled: default_index_search_enabled(),
            watch: default_index_watch(),
            max_chunks: default_index_max_chunks(),
            score_threshold: default_index_score_threshold(),
            budget_ratio: default_index_budget_ratio(),
            repo_map_tokens: default_index_repo_map_tokens(),
            repo_map_ttl_secs: default_repo_map_ttl_secs(),
            mcp_enabled: false,
            workspace_root: None,
            concurrency: default_index_concurrency(),
            batch_size: default_index_batch_size(),
            memory_batch_size: default_index_memory_batch_size(),
            max_file_bytes: default_index_max_file_bytes(),
            embed_provider: None,
            embed_concurrency: default_index_embed_concurrency(),
        }
    }
}

/// Vault backend configuration, nested under `[vault]` in TOML.
///
/// Selects how API keys and secrets are resolved at startup.
///
/// # Example (TOML)
///
/// ```toml
/// [vault]
/// backend = "age"
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct VaultConfig {
    /// Vault backend identifier (`"age"`, `"env"`, or `"keyring"`). Default: `"env"`.
    #[serde(default = "default_vault_backend")]
    pub backend: String,
}

impl Default for VaultConfig {
    fn default() -> Self {
        Self {
            backend: default_vault_backend(),
        }
    }
}

/// Cost tracking and budget configuration, nested under `[cost]` in TOML.
///
/// When `enabled = true`, token costs are accumulated per session and displayed in
/// the TUI. When `max_daily_cents > 0`, the agent refuses new turns once the daily
/// budget is exhausted.
///
/// # Example (TOML)
///
/// ```toml
/// [cost]
/// enabled = true
/// max_daily_cents = 500  # $5.00 per day
/// ```
#[derive(Debug, Deserialize, Serialize)]
pub struct CostConfig {
    /// Track and display token costs. Default: `true`.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Daily spending cap in US cents (`0` = unlimited). Default: `0`.
    #[serde(default = "default_max_daily_cents")]
    pub max_daily_cents: u32,
}

impl Default for CostConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_daily_cents: default_max_daily_cents(),
        }
    }
}

/// HTTP webhook gateway configuration, nested under `[gateway]` in TOML.
///
/// When `enabled = true`, an HTTP server accepts webhook payloads and injects them
/// as user messages into the agent. Requires the `gateway` feature flag.
///
/// # Example (TOML)
///
/// ```toml
/// [gateway]
/// enabled = true
/// bind = "127.0.0.1"
/// port = 8090
/// auth_token = "secret"
/// rate_limit = 60
/// max_body_size = 1048576
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GatewayConfig {
    /// Enable the HTTP gateway. Default: `false`.
    #[serde(default)]
    pub enabled: bool,
    /// IP address to bind the gateway to. Default: `"127.0.0.1"`.
    #[serde(default = "default_gateway_bind")]
    pub bind: String,
    /// Port to listen on. Default: `8090`.
    #[serde(default = "default_gateway_port")]
    pub port: u16,
    /// Bearer token for request authentication. When set, all requests must include
    /// `Authorization: Bearer <token>`. Default: `None` (no auth).
    #[serde(default)]
    pub auth_token: Option<String>,
    /// Maximum requests per minute. Must be `> 0`. Default: `120`.
    #[serde(default = "default_gateway_rate_limit")]
    pub rate_limit: u32,
    /// Maximum request body size in bytes. Must be `<= 10 MiB`. Default: `1048576` (1 MiB).
    #[serde(default = "default_gateway_max_body")]
    pub max_body_size: usize,
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            bind: default_gateway_bind(),
            port: default_gateway_port(),
            auth_token: None,
            rate_limit: default_gateway_rate_limit(),
            max_body_size: default_gateway_max_body(),
        }
    }
}

/// Daemon / process supervisor configuration, nested under `[daemon]` in TOML.
///
/// When `enabled = true`, Zeph runs as a background process with automatic restart
/// and health monitoring.
///
/// # Example (TOML)
///
/// ```toml
/// [daemon]
/// enabled = true
/// pid_file = "~/.zeph/zeph.pid"
/// health_interval_secs = 30
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DaemonConfig {
    /// Run Zeph as a background daemon. Default: `false`.
    #[serde(default)]
    pub enabled: bool,
    /// Path to the PID file written at daemon startup. Default: `"~/.zeph/zeph.pid"`.
    #[serde(default = "default_pid_file")]
    pub pid_file: String,
    /// Interval in seconds between health checks. Default: `30`.
    #[serde(default = "default_health_interval")]
    pub health_interval_secs: u64,
    /// Maximum backoff in seconds between restart attempts. Default: `60`.
    #[serde(default = "default_max_restart_backoff")]
    pub max_restart_backoff_secs: u64,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            pid_file: default_pid_file(),
            health_interval_secs: default_health_interval(),
            max_restart_backoff_secs: default_max_restart_backoff(),
        }
    }
}

/// Cron-based task scheduler configuration, nested under `[scheduler]` in TOML.
///
/// When `enabled = true`, the scheduler runs periodic tasks on a cron schedule.
/// Requires the `scheduler` feature flag.
///
/// # Example (TOML)
///
/// ```toml
/// [scheduler]
/// enabled = true
/// tick_interval_secs = 60
/// max_tasks = 20
///
/// [[scheduler.tasks]]
/// name = "daily-summary"
/// cron = "0 9 * * *"
/// kind = "prompt"
/// prompt = "Summarize what was accomplished today."
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SchedulerConfig {
    /// Enable the task scheduler. Default: `false`.
    #[serde(default)]
    pub enabled: bool,
    /// How often the scheduler checks for due tasks, in seconds. Default: `60`.
    #[serde(default = "default_scheduler_tick_interval")]
    pub tick_interval_secs: u64,
    /// Maximum number of scheduled tasks allowed. Default: `100`.
    #[serde(default = "default_scheduler_max_tasks")]
    pub max_tasks: usize,
    /// List of scheduled task definitions.
    #[serde(default)]
    pub tasks: Vec<ScheduledTaskConfig>,
}

impl Default for SchedulerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            tick_interval_secs: default_scheduler_tick_interval(),
            max_tasks: default_scheduler_max_tasks(),
            tasks: Vec::new(),
        }
    }
}

/// Task kind for scheduled tasks.
///
/// Known variants map to built-in handlers; `Custom` accommodates user-defined task types.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ScheduledTaskKind {
    MemoryCleanup,
    SkillRefresh,
    HealthCheck,
    UpdateCheck,
    Experiment,
    Custom(String),
}

/// A single scheduled task entry, nested under `[[scheduler.tasks]]` in TOML.
///
/// Either `cron` (recurring) or `run_at` (one-shot ISO 8601 datetime) must be set.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ScheduledTaskConfig {
    /// Unique task name used in logs and the scheduler database.
    pub name: String,
    /// Cron expression for recurring tasks (e.g. `"0 9 * * *"` for daily at 09:00).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cron: Option<String>,
    /// One-shot ISO 8601 datetime for one-time tasks. Ignored when `cron` is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run_at: Option<String>,
    /// Determines which built-in handler executes this task.
    pub kind: ScheduledTaskKind,
    /// Arbitrary JSON configuration forwarded to the task handler.
    #[serde(default)]
    pub config: serde_json::Value,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn index_config_defaults() {
        let cfg = IndexConfig::default();
        assert!(!cfg.enabled);
        assert!(cfg.search_enabled);
        assert!(!cfg.watch);
        assert_eq!(cfg.concurrency, 4);
        assert_eq!(cfg.batch_size, 32);
        assert!(cfg.workspace_root.is_none());
    }

    #[test]
    fn index_config_serde_roundtrip_with_new_fields() {
        let toml = r#"
            enabled = true
            concurrency = 8
            batch_size = 16
            workspace_root = "/tmp/myproject"
        "#;
        let cfg: IndexConfig = toml::from_str(toml).unwrap();
        assert!(cfg.enabled);
        assert_eq!(cfg.concurrency, 8);
        assert_eq!(cfg.batch_size, 16);
        assert_eq!(
            cfg.workspace_root,
            Some(std::path::PathBuf::from("/tmp/myproject"))
        );
        // Re-serialize and deserialize
        let serialized = toml::to_string(&cfg).unwrap();
        let cfg2: IndexConfig = toml::from_str(&serialized).unwrap();
        assert_eq!(cfg2.concurrency, 8);
        assert_eq!(cfg2.batch_size, 16);
    }

    #[test]
    fn index_config_backward_compat_old_toml_without_new_fields() {
        // Old config without workspace_root, concurrency, batch_size — must still parse
        // and use defaults for the missing fields.
        let toml = "
            enabled = true
            max_chunks = 20
            score_threshold = 0.3
        ";
        let cfg: IndexConfig = toml::from_str(toml).unwrap();
        assert!(cfg.enabled);
        assert_eq!(cfg.max_chunks, 20);
        assert!(cfg.workspace_root.is_none());
        assert_eq!(cfg.concurrency, 4);
        assert_eq!(cfg.batch_size, 32);
    }

    #[test]
    fn index_config_workspace_root_none_by_default() {
        let cfg: IndexConfig = toml::from_str("enabled = false").unwrap();
        assert!(cfg.workspace_root.is_none());
    }
}

fn default_trace_service_name() -> String {
    "zeph".into()
}

/// Configuration for OTel-compatible trace dumps (`format = "trace"`).
///
/// When `format = "trace"`, the `TracingCollector` writes a `trace.json` file in OTLP JSON
/// format at session end. Legacy numbered dump files are NOT written by default (C-03).
/// When the `otel` feature is enabled and `otlp_endpoint` is set, spans are also exported
/// via OTLP gRPC.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct TraceConfig {
    /// OTLP gRPC endpoint (only used when `otel` feature is enabled).
    /// Default: `"http://localhost:4317"`.
    #[serde(default = "default_otlp_endpoint")]
    pub otlp_endpoint: String,
    /// Service name reported to the `OTel` collector.
    #[serde(default = "default_trace_service_name")]
    pub service_name: String,
    /// Redact sensitive data in span attributes (default: `true`) (C-01).
    #[serde(default = "default_true")]
    pub redact: bool,
}

impl Default for TraceConfig {
    fn default() -> Self {
        Self {
            otlp_endpoint: default_otlp_endpoint(),
            service_name: default_trace_service_name(),
            redact: true,
        }
    }
}

/// Debug dump configuration, nested under `[debug]` in TOML.
///
/// When `enabled = true`, LLM request/response payloads are written to disk for inspection.
/// Each session creates a subdirectory under `output_dir` named by session ID.
///
/// # Example (TOML)
///
/// ```toml
/// [debug]
/// enabled = true
/// format = "raw"
/// ```
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DebugConfig {
    /// Enable debug dump on startup (CLI `--debug-dump` takes priority).
    pub enabled: bool,
    /// Directory where per-session debug dump subdirectories are created.
    #[serde(default = "crate::defaults::default_debug_output_dir")]
    pub output_dir: std::path::PathBuf,
    /// Output format: `"json"` (default), `"raw"` (API payload), or `"trace"` (OTLP spans).
    pub format: crate::dump_format::DumpFormat,
    /// `OTel` trace configuration (only used when `format = "trace"`).
    pub traces: TraceConfig,
}

impl Default for DebugConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            output_dir: super::defaults::default_debug_output_dir(),
            format: crate::dump_format::DumpFormat::default(),
            traces: TraceConfig::default(),
        }
    }
}