crtx 0.1.0

CLI for the Cortex supervisory memory substrate.
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
//! Effective CLI configuration reporting.
//!
//! `cortex --print-config` is intentionally read-only: it resolves the same
//! default data layout as ordinary commands, overlays the non-secret file/env
//! config layers, then prints only non-secret values. Environment values whose
//! names look credential-bearing are redacted before serialization.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::{exit::Exit, paths::DataLayout};

const CONFIG_ENV_KEY: &str = "CORTEX_CONFIG";
const DATA_DIR_ENV_KEY: &str = "CORTEX_DATA_DIR";
const DB_PATH_ENV_KEY: &str = "CORTEX_DB_PATH";
const EVENT_LOG_PATH_ENV_KEY: &str = "CORTEX_EVENT_LOG_PATH";
const LLM_BACKEND_ENV_KEY: &str = "CORTEX_LLM_BACKEND";
const LLM_MODEL_ENV_KEY: &str = "CORTEX_LLM_MODEL";
const LLM_ENDPOINT_ENV_KEY: &str = "CORTEX_LLM_ENDPOINT";
const LLM_API_KEY_ENV_KEY: &str = "CORTEX_LLM_API_KEY";
pub(crate) const DEFAULT_OLLAMA_ENDPOINT: &str = "http://localhost:11434";
const ENV_KEYS: &[&str] = &[
    "APPDATA",
    "HOME",
    "RUST_LOG",
    "XDG_CONFIG_HOME",
    "XDG_DATA_HOME",
];
const SECRET_MARKERS: &[&str] = &[
    "ACCESS_TOKEN",
    "API_KEY",
    "AUTH",
    "CREDENTIAL",
    "KEY",
    "PASS",
    "PASSWORD",
    "PRIVATE",
    "SECRET",
    "TOKEN",
];
const REDACTED: &str = "<redacted>";

/// Snapshot of effective non-secret CLI configuration.
#[derive(Debug, Serialize)]
pub(crate) struct EffectiveConfig {
    data_dir: String,
    db_path: String,
    event_log_path: String,
    env: BTreeMap<String, String>,
}

/// Print effective non-secret configuration as stable JSON.
pub(crate) fn print_effective_config() -> Exit {
    let config = match effective_config() {
        Ok(config) => config,
        Err(exit) => return exit,
    };
    match serde_json::to_string_pretty(&config) {
        Ok(json) => {
            println!("{json}");
            Exit::Ok
        }
        Err(err) => {
            eprintln!("cortex --print-config: failed to serialize config: {err}");
            Exit::Internal
        }
    }
}

fn effective_config() -> Result<EffectiveConfig, Exit> {
    let file_config = load_file_config()?;
    let layout = resolve_configured_layout(file_config)?;
    Ok(EffectiveConfig {
        data_dir: display_path(&layout.data_dir),
        db_path: display_path(&layout.db_path),
        event_log_path: display_path(&layout.event_log_path),
        env: relevant_env(),
    })
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct FileConfig {
    data_dir: Option<PathBuf>,
    db_path: Option<PathBuf>,
    event_log_path: Option<PathBuf>,
    #[serde(default)]
    llm: Option<LlmFileConfig>,
    #[serde(default)]
    embeddings: Option<EmbeddingsFileConfig>,
    #[serde(default)]
    mcp: Option<McpFileConfig>,
}

// ─────────────────────────────────────────────────────────────────────────────
// Embeddings config types
// ─────────────────────────────────────────────────────────────────────────────

/// File-level `[embeddings]` TOML section.
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct EmbeddingsFileConfig {
    /// Embedding backend: `"stub"` (default) or `"ollama"`.
    #[serde(default = "default_embedding_backend")]
    pub(crate) backend: String,
    /// Optional Ollama-specific embedding config.
    pub(crate) ollama: Option<OllamaEmbedFileConfig>,
}

/// File-level `[embeddings.ollama]` TOML section.
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct OllamaEmbedFileConfig {
    /// Ollama base endpoint. Defaults to `http://localhost:11434`.
    #[serde(default = "default_ollama_embed_endpoint")]
    pub(crate) endpoint: String,
    /// Embedding model name (e.g. `"nomic-embed-text"`).
    #[serde(default = "default_ollama_embed_model")]
    pub(crate) model: String,
    /// Expected output dimensionality. Defaults to 768 (nomic-embed-text).
    #[serde(default = "default_ollama_embed_dim")]
    pub(crate) dim: usize,
    /// Per-call HTTP timeout in milliseconds.
    #[serde(default = "default_ollama_embed_timeout_ms")]
    pub(crate) timeout_ms: u64,
}

fn default_embedding_backend() -> String {
    "stub".to_string()
}
fn default_ollama_embed_endpoint() -> String {
    DEFAULT_OLLAMA_ENDPOINT.to_string()
}
fn default_ollama_embed_model() -> String {
    "nomic-embed-text".to_string()
}
fn default_ollama_embed_dim() -> usize {
    768
}
fn default_ollama_embed_timeout_ms() -> u64 {
    30_000
}

/// Resolved embedding backend selection.
///
/// Priority order (highest first): env vars
/// `CORTEX_EMBEDDING_BACKEND` / `CORTEX_EMBEDDING_MODEL` /
/// `CORTEX_EMBEDDING_ENDPOINT`, then the `[embeddings]` config file section,
/// then `EmbeddingBackend::Stub` as the immutable default.
///
/// # Config file example
///
/// ```toml
/// [embeddings]
/// backend = "ollama"
///
/// [embeddings.ollama]
/// endpoint = "http://localhost:11434"
/// model    = "nomic-embed-text"
/// dim      = 768
/// ```
#[derive(Debug, Clone)]
pub(crate) enum EmbeddingBackend {
    /// BLAKE3 deterministic stub — always available, zero network deps.
    /// This is the default when no embeddings config is present.
    Stub,
    /// Real semantic embeddings via a local Ollama instance.
    Ollama {
        /// Base endpoint URL, e.g. `http://localhost:11434`.
        endpoint: String,
        /// Model name, e.g. `nomic-embed-text` or `mxbai-embed-large`.
        model: String,
        /// Expected output dimensionality (e.g. 768 for nomic-embed-text).
        dim: usize,
        /// Per-call HTTP timeout in milliseconds.
        timeout_ms: u64,
    },
}

impl EmbeddingBackend {
    /// Resolve from env + config file. Falls back to `Stub` when nothing is
    /// configured or parsing fails.
    pub(crate) fn resolve() -> Self {
        let file_embeddings = load_file_config().ok().and_then(|fc| fc.embeddings);

        let backend_str = std::env::var("CORTEX_EMBEDDING_BACKEND")
            .ok()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| {
                file_embeddings
                    .as_ref()
                    .map(|e| e.backend.clone())
                    .unwrap_or_else(|| "stub".to_string())
            });

        match backend_str.as_str() {
            "ollama" => {
                let endpoint = std::env::var("CORTEX_EMBEDDING_ENDPOINT")
                    .ok()
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| {
                        file_embeddings
                            .as_ref()
                            .and_then(|e| e.ollama.as_ref())
                            .map(|o| o.endpoint.clone())
                            .unwrap_or_else(|| DEFAULT_OLLAMA_ENDPOINT.to_string())
                    });
                let model = std::env::var("CORTEX_EMBEDDING_MODEL")
                    .ok()
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| {
                        file_embeddings
                            .as_ref()
                            .and_then(|e| e.ollama.as_ref())
                            .map(|o| o.model.clone())
                            .unwrap_or_else(|| "nomic-embed-text".to_string())
                    });
                let dim = file_embeddings
                    .as_ref()
                    .and_then(|e| e.ollama.as_ref())
                    .map(|o| o.dim)
                    .unwrap_or(768);
                let timeout_ms = file_embeddings
                    .as_ref()
                    .and_then(|e| e.ollama.as_ref())
                    .map(|o| o.timeout_ms)
                    .unwrap_or(30_000);
                EmbeddingBackend::Ollama {
                    endpoint,
                    model,
                    dim,
                    timeout_ms,
                }
            }
            _ => EmbeddingBackend::Stub,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// MCP config types
// ─────────────────────────────────────────────────────────────────────────────

/// File-level `[mcp]` TOML section.
///
/// Example:
/// ```toml
/// [mcp]
/// auto_commit = true   # fully automated sessions — no confirmation token required
/// ```
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct McpFileConfig {
    /// If `true`, `cortex_session_commit` bypasses the ADR 0047 operator-confirmation
    /// token check. Equivalent to setting `CORTEX_MCP_AUTO_COMMIT=1`. The env
    /// var takes precedence when both are set.
    #[serde(default)]
    pub(crate) auto_commit: bool,
}

/// The source that activated `auto_commit` in the resolved MCP config.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) enum AutoCommitSource {
    /// `auto_commit` is `false`; no source activated it.
    #[default]
    NotSet,
    /// Activated by the `CORTEX_MCP_AUTO_COMMIT=1` environment variable.
    EnvVar,
    /// Activated by `[mcp] auto_commit = true` in the config file.
    ConfigFile,
}

/// Resolved MCP configuration.
///
/// Priority order (highest first): env var `CORTEX_MCP_AUTO_COMMIT=1`, then
/// `[mcp] auto_commit = true` in `cortex.toml`, then `false` (safe default).
#[derive(Debug, Clone, Default)]
pub(crate) struct McpConfig {
    /// Whether `cortex_session_commit` should bypass the ADR 0047 confirmation
    /// token. When `true` the confirmation token is still printed to stderr but
    /// is not required by the tool handler.
    pub(crate) auto_commit: bool,
    /// Where `auto_commit = true` came from (env var or config file).
    pub(crate) auto_commit_source: AutoCommitSource,
}

impl McpConfig {
    /// Resolve the effective MCP config from env vars and the config file.
    ///
    /// If the config file cannot be read or parsed a diagnostic is emitted to
    /// stderr and the file layer is treated as absent (fallback to `false`) so
    /// that `cortex serve` can still start.  The caller can inspect
    /// `auto_commit_source` to report WHERE auto_commit was enabled.
    pub(crate) fn resolve() -> Self {
        // Env var takes highest precedence.
        if std::env::var("CORTEX_MCP_AUTO_COMMIT").as_deref() == Ok("1") {
            return McpConfig {
                auto_commit: true,
                auto_commit_source: AutoCommitSource::EnvVar,
            };
        }

        // Fall back to config file; emit a diagnostic on parse failure instead
        // of silently discarding it (CR2-H1).
        let file_mcp = match load_file_config() {
            Ok(fc) => fc.mcp,
            Err(_) => {
                eprintln!(
                    "cortex serve: warning: failed to read or parse config file; \
                     auto_commit defaults to false"
                );
                None
            }
        };

        let auto_commit = file_mcp.map(|m| m.auto_commit).unwrap_or(false);
        let auto_commit_source = if auto_commit {
            AutoCommitSource::ConfigFile
        } else {
            AutoCommitSource::NotSet
        };

        McpConfig {
            auto_commit,
            auto_commit_source,
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// LLM config types
// ─────────────────────────────────────────────────────────────────────────────

/// File-level `[llm]` TOML section.
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct LlmFileConfig {
    #[serde(default = "default_llm_backend")]
    pub(crate) backend: String,
    pub(crate) ollama: Option<OllamaFileConfig>,
    pub(crate) claude: Option<ClaudeFileConfig>,
    /// OpenAI-compatible server config (`[llm.openai-compat]`).
    #[serde(rename = "openai-compat")]
    pub(crate) openai_compat: Option<OpenAiCompatFileConfig>,
}

/// File-level `[llm.claude]` TOML section.
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct ClaudeFileConfig {
    pub(crate) model: String,
    #[serde(default = "default_claude_max_tokens")]
    pub(crate) max_tokens: u32,
    #[serde(default = "default_claude_timeout_ms")]
    pub(crate) timeout_ms: u64,
    /// Sensitivity threshold: "low" | "medium" | "high". Default "medium".
    #[serde(default = "default_claude_max_sensitivity")]
    pub(crate) max_sensitivity: String,
}

fn default_claude_max_tokens() -> u32 {
    4096
}
fn default_claude_timeout_ms() -> u64 {
    60_000
}
fn default_claude_max_sensitivity() -> String {
    "medium".to_string()
}

/// File-level `[llm.ollama]` TOML section.
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct OllamaFileConfig {
    pub(crate) endpoint: String,
    pub(crate) model: String,
    #[serde(default = "default_ollama_timeout_ms")]
    pub(crate) timeout_ms: u64,
}

/// File-level `[llm.openai-compat]` TOML section.
///
/// Example:
/// ```toml
/// [llm]
/// backend = "openai-compat"
///
/// [llm.openai-compat]
/// base_url        = "http://localhost:1234"
/// model           = "local-model"
/// api_key         = ""          # omit or leave blank for local servers
/// max_sensitivity = "medium"    # "low" | "medium" | "high"
/// ```
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub(crate) struct OpenAiCompatFileConfig {
    /// Base URL of the OpenAI-compatible server (no trailing slash).
    pub(crate) base_url: String,
    /// Model identifier as the server knows it.
    pub(crate) model: String,
    /// Optional API key. Leave blank or absent for local servers.
    #[serde(default)]
    pub(crate) api_key: String,
    /// Per-call HTTP timeout in milliseconds.
    #[serde(default = "default_openai_compat_timeout_ms")]
    pub(crate) timeout_ms: u64,
    /// Sensitivity threshold: "low" | "medium" | "high". Default "medium".
    #[serde(default = "default_openai_compat_max_sensitivity")]
    pub(crate) max_sensitivity: String,
}

fn default_openai_compat_timeout_ms() -> u64 {
    60_000
}

fn default_openai_compat_max_sensitivity() -> String {
    "medium".to_string()
}

fn default_llm_backend() -> String {
    "offline".to_string()
}

fn default_ollama_timeout_ms() -> u64 {
    30_000
}

/// Resolved LLM backend selection.
///
/// Priority order (highest first): CLI `--model ollama:<ref>` flag (handled in
/// `run.rs`), then env vars `CORTEX_LLM_BACKEND` / `CORTEX_LLM_MODEL` /
/// `CORTEX_LLM_ENDPOINT`, then `[llm]` config file section, then
/// `LlmBackend::Offline` as the immutable default.
// Fields in the Claude/OpenAiCompat variants are parsed from config and stored
// for future adapter wiring; they are not yet read at every use site.
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub(crate) enum LlmBackend {
    /// No live model; the caller provides a deterministic offline response.
    Offline,
    /// Use the Anthropic Claude API (ADR 0048, RemoteUnsigned ceiling).
    Claude {
        /// Digest-pinned Anthropic model ID.
        model: String,
        /// Maximum tokens to generate.
        max_tokens: u32,
        /// Per-call HTTP timeout in milliseconds.
        timeout_ms: u64,
        /// Maximum memory sensitivity to include in remote prompts.
        max_sensitivity: String,
    },
    /// Use a local Ollama instance.
    Ollama {
        /// Base endpoint URL, e.g. `http://localhost:11434`.
        endpoint: String,
        /// Digest-pinned model reference.
        model: String,
        /// Per-call HTTP timeout in milliseconds.
        timeout_ms: u64,
    },
    /// Use any OpenAI-compatible server (LM Studio, LocalAI, vLLM, etc.)
    OpenAiCompat {
        /// Base URL of the server, e.g. `http://localhost:1234`.
        base_url: String,
        /// Model identifier as the server knows it.
        model: String,
        /// Optional API key; `None` or empty string means no Authorization header.
        api_key: Option<String>,
        /// Per-call HTTP timeout in milliseconds.
        timeout_ms: u64,
        /// Maximum memory sensitivity to include in remote prompts.
        max_sensitivity: String,
    },
}

impl LlmBackend {
    /// Resolve the effective backend from env vars and the config file.
    ///
    /// Config IO errors are printed to stderr but treated as absent config
    /// (fallback to `Offline`) so that `cortex run` can still execute in an
    /// offline environment when the config file is malformed.
    pub(crate) fn resolve() -> Self {
        // Attempt to load the file config; errors are non-fatal here.
        let file_llm = load_file_config().ok().and_then(|fc| fc.llm);

        // Env-layer values.
        let env_backend = std::env::var(LLM_BACKEND_ENV_KEY)
            .ok()
            .filter(|s| !s.is_empty());
        let env_model = std::env::var(LLM_MODEL_ENV_KEY)
            .ok()
            .filter(|s| !s.is_empty());
        let env_endpoint = std::env::var(LLM_ENDPOINT_ENV_KEY)
            .ok()
            .filter(|s| !s.is_empty());
        let env_api_key = std::env::var(LLM_API_KEY_ENV_KEY)
            .ok()
            .filter(|s| !s.is_empty());

        // Determine effective backend string: env > config file > "offline".
        let backend_str = env_backend
            .as_deref()
            .or_else(|| file_llm.as_ref().map(|c| c.backend.as_str()))
            .unwrap_or("offline");

        match backend_str {
            "ollama" => {
                // Model: env > config file ollama.model > none.
                let model = env_model
                    .or_else(|| {
                        file_llm
                            .as_ref()
                            .and_then(|c| c.ollama.as_ref())
                            .map(|o| o.model.clone())
                    })
                    .unwrap_or_default();

                // Endpoint: env > config file ollama.endpoint > loopback default.
                let endpoint = env_endpoint
                    .or_else(|| {
                        file_llm
                            .as_ref()
                            .and_then(|c| c.ollama.as_ref())
                            .map(|o| o.endpoint.clone())
                    })
                    .unwrap_or_else(|| DEFAULT_OLLAMA_ENDPOINT.to_string());

                let timeout_ms = file_llm
                    .as_ref()
                    .and_then(|c| c.ollama.as_ref())
                    .map(|o| o.timeout_ms)
                    .unwrap_or(30_000);

                LlmBackend::Ollama {
                    endpoint,
                    model,
                    timeout_ms,
                }
            }
            "claude" => {
                let model = env_model
                    .or_else(|| {
                        file_llm
                            .as_ref()
                            .and_then(|c| c.claude.as_ref())
                            .map(|c| c.model.clone())
                    })
                    .unwrap_or_default();
                let claude_cfg = file_llm.as_ref().and_then(|c| c.claude.as_ref());
                LlmBackend::Claude {
                    model,
                    max_tokens: claude_cfg.map(|c| c.max_tokens).unwrap_or(4096),
                    timeout_ms: claude_cfg.map(|c| c.timeout_ms).unwrap_or(60_000),
                    max_sensitivity: claude_cfg
                        .map(|c| c.max_sensitivity.clone())
                        .unwrap_or_else(|| "medium".to_string()),
                }
            }
            "openai-compat" => {
                // Base URL: env CORTEX_LLM_ENDPOINT > config file > LM Studio default.
                let base_url = env_endpoint
                    .or_else(|| {
                        file_llm
                            .as_ref()
                            .and_then(|c| c.openai_compat.as_ref())
                            .map(|o| o.base_url.clone())
                    })
                    .unwrap_or_else(|| "http://localhost:1234".to_string());

                // Model: env > config file > empty (adapter will reject empty).
                let model = env_model
                    .or_else(|| {
                        file_llm
                            .as_ref()
                            .and_then(|c| c.openai_compat.as_ref())
                            .map(|o| o.model.clone())
                    })
                    .unwrap_or_default();

                // API key: env CORTEX_LLM_API_KEY > config file > None.
                let api_key = env_api_key.or_else(|| {
                    file_llm
                        .as_ref()
                        .and_then(|c| c.openai_compat.as_ref())
                        .and_then(|o| {
                            if o.api_key.is_empty() {
                                None
                            } else {
                                Some(o.api_key.clone())
                            }
                        })
                });

                let timeout_ms = file_llm
                    .as_ref()
                    .and_then(|c| c.openai_compat.as_ref())
                    .map(|o| o.timeout_ms)
                    .unwrap_or(60_000);

                let max_sensitivity = file_llm
                    .as_ref()
                    .and_then(|c| c.openai_compat.as_ref())
                    .map(|o| o.max_sensitivity.clone())
                    .unwrap_or_else(|| "medium".to_string());

                LlmBackend::OpenAiCompat {
                    base_url,
                    model,
                    api_key,
                    timeout_ms,
                    max_sensitivity,
                }
            }
            _ => LlmBackend::Offline,
        }
    }
}

fn load_file_config() -> Result<FileConfig, Exit> {
    let explicit_path = std::env::var_os(CONFIG_ENV_KEY).filter(|value| !value.is_empty());
    let (path, required) = match explicit_path {
        Some(path) => (PathBuf::from(path), true),
        None => match default_config_path() {
            Some(path) => (path, false),
            None => return Ok(FileConfig::default()),
        },
    };

    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(err) if !required && err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(FileConfig::default());
        }
        Err(err) => {
            eprintln!(
                "cortex --print-config: failed to read config file {}: {err}",
                path.display()
            );
            return Err(Exit::PreconditionUnmet);
        }
    };

    toml::from_str(&text).map_err(|err| {
        eprintln!(
            "cortex --print-config: failed to parse config file {}: {err}",
            path.display()
        );
        Exit::Usage
    })
}

fn resolve_configured_layout(file_config: FileConfig) -> Result<DataLayout, Exit> {
    let data_dir = env_path(DATA_DIR_ENV_KEY).or(file_config.data_dir);
    let db_path = env_path(DB_PATH_ENV_KEY).or(file_config.db_path);
    let event_log_path = env_path(EVENT_LOG_PATH_ENV_KEY).or(file_config.event_log_path);

    match data_dir {
        Some(data_dir) => Ok(DataLayout {
            db_path: db_path.unwrap_or_else(|| data_dir.join("cortex.db")),
            event_log_path: event_log_path.unwrap_or_else(|| data_dir.join("events.jsonl")),
            data_dir,
        }),
        None => DataLayout::resolve(db_path, event_log_path),
    }
}

fn env_path(key: &str) -> Option<PathBuf> {
    std::env::var_os(key)
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
}

fn default_config_path() -> Option<PathBuf> {
    if let Some(config_home) = std::env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty())
    {
        return Some(
            PathBuf::from(config_home)
                .join("cortex")
                .join("config.toml"),
        );
    }
    dirs::config_dir().map(|dir| dir.join("cortex").join("config.toml"))
}

fn relevant_env() -> BTreeMap<String, String> {
    let mut env = BTreeMap::new();
    for (key, value) in std::env::vars() {
        if ENV_KEYS.contains(&key.as_str()) || key.starts_with("CORTEX_") {
            env.insert(key.clone(), redact_env_value(&key, value));
        }
    }
    env
}

fn redact_env_value(key: &str, value: String) -> String {
    if is_secret_like_key(key) {
        return REDACTED.to_string();
    }
    // Redact CORTEX_LLM_MODEL values that contain a SHA-256 digest substring
    // (e.g. `name@sha256:<64 hex chars>`). The digest is an identity anchor
    // but could double as a lookup key; redact conservatively.
    if key == LLM_MODEL_ENV_KEY && value_contains_sha256_digest(&value) {
        return REDACTED.to_string();
    }
    value
}

/// Returns `true` if `value` contains `@sha256:` followed by 64 hex characters.
fn value_contains_sha256_digest(value: &str) -> bool {
    if let Some((_before, after)) = value.split_once("@sha256:") {
        let hex_part = after
            .split_once(|c: char| !c.is_ascii_hexdigit())
            .map(|(h, _)| h)
            .unwrap_or(after);
        return hex_part.len() == 64;
    }
    false
}

fn is_secret_like_key(key: &str) -> bool {
    let upper = key.to_ascii_uppercase();
    SECRET_MARKERS.iter().any(|marker| upper.contains(marker))
}

fn display_path(path: &Path) -> String {
    path.display().to_string()
}

#[cfg(test)]
mod tests {
    use super::{is_secret_like_key, redact_env_value, REDACTED};

    #[test]
    fn secret_like_keys_are_redacted() {
        assert_eq!(
            redact_env_value("CORTEX_API_TOKEN", "secret".to_string()),
            REDACTED
        );
        assert_eq!(
            redact_env_value("CORTEX_PROFILE", "local".to_string()),
            "local"
        );
    }

    #[test]
    fn key_names_are_classified_case_insensitively() {
        assert!(is_secret_like_key("cortex_private_key_path"));
        assert!(is_secret_like_key("CORTEX_PASSWORD"));
        assert!(!is_secret_like_key("CORTEX_FIXTURES_DIR"));
    }
}