codelore-lib 0.29.1

CodeLore — Behavioral Code Analyzer library
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
//! Synchronous two-dialect chat client for the advisory narrative layer.
//!
//! The advisory layer speaks to whatever model the operator points it at, in
//! one of two request shapes: the Anthropic-native `/v1/messages` API, or the
//! OpenAI-compatible `/chat/completions` API that local runners (Ollama, LM
//! Studio, vLLM) expose. The posture is local-first — with nothing configured,
//! resolution defaults to a local OpenAI-compatible endpoint.
//!
//! The client is deliberately blocking: `codelore-lib` carries no async
//! runtime, and one advisory completion per invocation does not warrant one. It
//! uses a single [`ureq`] agent with one total timeout and no retries.
//!
//! Environment reading is confined to [`LlmEnv::from_process_env`]; every other
//! path takes an [`LlmEnv`] by reference, so [`resolve_client`] is pure over its
//! input and the resolution matrix is unit-testable without environment races.

use std::time::Duration;

use serde_json::json;
use ureq::Agent;

use crate::{CodeLoreError, Result};

/// Model used for the Anthropic dialect when the operator sets no model.
pub const DEFAULT_ANTHROPIC_MODEL: &str = "claude-sonnet-5";

/// Base URL for the OpenAI-compatible dialect when the operator sets none —
/// Ollama's local OpenAI-compatible shim; this default makes the layer local-first.
pub const DEFAULT_OPENAI_COMPAT_BASE_URL: &str = "http://localhost:11434/v1";

/// Base URL for the Anthropic dialect when the operator sets none.
pub const DEFAULT_ANTHROPIC_BASE_URL: &str = "https://api.anthropic.com";

/// Default total per-request timeout, in seconds. Covers connect through
/// body read.
///
/// Overridable with `CODELORE_LLM_TIMEOUT_SECS`, because the default is a
/// budget rather than a fact: a small local model answers in seconds, while
/// a larger or remote one can approach the ceiling, and a user who meets it
/// otherwise has no recourse short of patching this constant.
pub const REQUEST_TIMEOUT_SECS: u64 = 120;

/// The environment variable overriding [`REQUEST_TIMEOUT_SECS`], named into
/// the `CODELORE_LLM_*` family every other client knob already uses.
pub const TIMEOUT_ENV: &str = "CODELORE_LLM_TIMEOUT_SECS";

/// Anthropic messages API version, pinned in the `anthropic-version` header.
const ANTHROPIC_VERSION: &str = "2023-06-01";

/// Response token ceiling for the advisory completion. A narrative is a few
/// tight paragraphs; this bounds a runaway generation.
const MAX_TOKENS: u32 = 1024;

/// A model that turns one system + user exchange into assistant text.
pub trait ChatClient {
    /// Complete a single system/user exchange, returning the assistant's text.
    fn complete(&self, system: &str, user: &str) -> Result<String>;
    /// The model identifier this client targets, for the advisory stamp.
    fn model_id(&self) -> &str;
}

/// Resolve the per-request timeout from a raw environment value, falling
/// back to [`REQUEST_TIMEOUT_SECS`].
///
/// A malformed or non-positive value warns and falls back rather than
/// failing the run: this layer is advisory, so a typo in an optional knob
/// should not abort an analysis. It does not pass silently, though — a
/// mistyped budget that quietly kept the old one would look exactly like
/// the ceiling this override exists to raise. Zero is refused because it
/// would abort every request instantly rather than mean "no limit".
fn resolve_timeout_secs(raw: Option<&str>) -> u64 {
    let Some(raw) = raw else {
        return REQUEST_TIMEOUT_SECS;
    };
    match raw.parse::<u64>() {
        Ok(secs) if secs > 0 => secs,
        _ => {
            tracing::warn!(
                "{TIMEOUT_ENV}={raw:?} is not a positive whole number of seconds — \
                 falling back to {REQUEST_TIMEOUT_SECS}s"
            );
            REQUEST_TIMEOUT_SECS
        }
    }
}

/// Build the shared blocking agent: one global timeout, no retries, and
/// non-2xx responses surfaced as `Ok` so the response body can be folded into
/// the error message rather than discarded.
fn build_agent() -> Agent {
    Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(resolve_timeout_secs(
            read_env(TIMEOUT_ENV).as_deref(),
        ))))
        .http_status_as_error(false)
        .build()
        .into()
}

/// POST `body` as JSON to `url` with `headers`, returning the parsed response.
///
/// The agent disables status-as-error, so a non-2xx response arrives as `Ok`;
/// this maps it to [`CodeLoreError::Analysis`] carrying the status code and the
/// first 200 characters of the response body.
fn post_json(
    agent: &Agent,
    url: &str,
    headers: &[(&str, &str)],
    body: &serde_json::Value,
) -> Result<serde_json::Value> {
    let mut request = agent.post(url);
    for (name, value) in headers {
        request = request.header(*name, *value);
    }
    let mut response = request
        .send_json(body)
        .map_err(|e| CodeLoreError::Analysis(format!("LLM request to {url} failed: {e}")))?;
    let status = response.status();
    let text = response.body_mut().read_to_string().map_err(|e| {
        CodeLoreError::Analysis(format!("reading LLM response from {url} failed: {e}"))
    })?;
    if !status.is_success() {
        let snippet: String = text.chars().take(200).collect();
        return Err(CodeLoreError::Analysis(format!(
            "LLM request to {url} returned HTTP {}: {snippet}",
            status.as_u16()
        )));
    }
    serde_json::from_str(&text).map_err(|e| {
        CodeLoreError::Analysis(format!("LLM response from {url} was not valid JSON: {e}"))
    })
}

/// Client for the Anthropic-native `/v1/messages` API.
pub struct AnthropicClient {
    agent: Agent,
    api_key: String,
    model: String,
    base_url: String,
}

impl AnthropicClient {
    /// A client posting to `{base_url}/v1/messages` as `model`, authenticated
    /// with `api_key`.
    #[must_use]
    pub fn new(api_key: String, model: String, base_url: String) -> Self {
        Self {
            agent: build_agent(),
            api_key,
            model,
            base_url,
        }
    }
}

impl ChatClient for AnthropicClient {
    fn complete(&self, system: &str, user: &str) -> Result<String> {
        let url = format!("{}/v1/messages", self.base_url.trim_end_matches('/'));
        let body = json!({
            "model": self.model,
            "max_tokens": MAX_TOKENS,
            "system": system,
            "messages": [{ "role": "user", "content": user }],
        });
        let value = post_json(
            &self.agent,
            &url,
            &[
                ("x-api-key", self.api_key.as_str()),
                ("anthropic-version", ANTHROPIC_VERSION),
            ],
            &body,
        )?;
        value["content"][0]["text"]
            .as_str()
            .map(str::to_owned)
            .ok_or_else(|| {
                CodeLoreError::Analysis(format!(
                    "Anthropic response from {url} had no text at content[0].text"
                ))
            })
    }

    fn model_id(&self) -> &str {
        &self.model
    }
}

/// Client for the OpenAI-compatible `/chat/completions` API.
pub struct OpenAiCompatClient {
    agent: Agent,
    base_url: String,
    api_key: Option<String>,
    model: String,
}

impl OpenAiCompatClient {
    /// A client posting to `{base_url}/chat/completions` as `model`. When
    /// `api_key` is set it is sent as an `Authorization: Bearer` header; local
    /// runners typically need none.
    #[must_use]
    pub fn new(base_url: String, api_key: Option<String>, model: String) -> Self {
        Self {
            agent: build_agent(),
            base_url,
            api_key,
            model,
        }
    }
}

impl ChatClient for OpenAiCompatClient {
    fn complete(&self, system: &str, user: &str) -> Result<String> {
        let url = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
        let body = json!({
            "model": self.model,
            "messages": [
                { "role": "system", "content": system },
                { "role": "user", "content": user },
            ],
        });
        let authorization = self.api_key.as_ref().map(|key| format!("Bearer {key}"));
        let mut headers: Vec<(&str, &str)> = Vec::new();
        if let Some(value) = &authorization {
            headers.push(("authorization", value.as_str()));
        }
        let value = post_json(&self.agent, &url, &headers, &body)?;
        value["choices"][0]["message"]["content"]
            .as_str()
            .map(str::to_owned)
            .ok_or_else(|| {
                CodeLoreError::Analysis(format!(
                    "OpenAI-compatible response from {url} had no text at choices[0].message.content"
                ))
            })
    }

    fn model_id(&self) -> &str {
        &self.model
    }
}

/// Raw environment inputs for client resolution, read once at the crate's only
/// environment-touching site so that resolution itself stays pure.
///
/// Deliberately does NOT derive `Debug`: two fields carry API keys, and a
/// derived impl would print them through any `{:?}` or `tracing` sink.
#[derive(Clone, Default)]
pub struct LlmEnv {
    /// `CODELORE_LLM_PROVIDER` — `anthropic` or `openai-compat`; unset selects
    /// the local OpenAI-compatible dialect, and an ambient Anthropic key
    /// without it is an error, never an implicit upgrade.
    pub provider: Option<String>,
    /// `ANTHROPIC_API_KEY` — the Anthropic dialect's credential.
    pub anthropic_key: Option<String>,
    /// `CODELORE_LLM_BASE_URL` — the OpenAI-compatible endpoint base.
    pub base_url: Option<String>,
    /// `CODELORE_LLM_API_KEY` — optional bearer token for the OpenAI-compatible
    /// endpoint.
    pub api_key: Option<String>,
    /// `CODELORE_LLM_MODEL` — required for the OpenAI-compatible dialect;
    /// overrides the default Anthropic model when the Anthropic dialect is used.
    pub model: Option<String>,
}

impl LlmEnv {
    /// Read the LLM configuration from the process environment. Empty or
    /// whitespace-only values are treated as unset. This is the crate's only
    /// environment-reading site.
    #[must_use]
    pub fn from_process_env() -> Self {
        Self {
            provider: read_env("CODELORE_LLM_PROVIDER"),
            anthropic_key: read_env("ANTHROPIC_API_KEY"),
            base_url: read_env("CODELORE_LLM_BASE_URL"),
            api_key: read_env("CODELORE_LLM_API_KEY"),
            model: read_env("CODELORE_LLM_MODEL"),
        }
    }
}

/// Read an environment variable, treating empty/whitespace-only values as unset.
fn read_env(name: &str) -> Option<String> {
    std::env::var(name)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

/// The concrete client an [`LlmEnv`] selects, before the (infallible) HTTP
/// agent is built. Split out from [`resolve_client`] so the resolution matrix
/// is unit-testable without constructing an agent.
///
/// `Debug` is implemented by hand (not derived) for the same reason [`LlmEnv`]
/// omits it: both variants carry credential material, and a derived impl would
/// print the key through any `{:?}` or `tracing` sink. The manual impl redacts
/// the key while preserving the present/absent distinction for the optional
/// bearer token.
enum Resolved {
    Anthropic {
        api_key: String,
        model: String,
        base_url: String,
    },
    OpenAiCompat {
        base_url: String,
        api_key: Option<String>,
        model: String,
    },
}

impl std::fmt::Debug for Resolved {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Anthropic {
                model, base_url, ..
            } => f
                .debug_struct("Anthropic")
                .field("api_key", &"<redacted>")
                .field("model", model)
                .field("base_url", base_url)
                .finish(),
            Self::OpenAiCompat {
                base_url,
                api_key,
                model,
            } => f
                .debug_struct("OpenAiCompat")
                .field("base_url", base_url)
                // Preserve whether a bearer token was supplied without
                // printing it: `Some("<redacted>")` vs `None`.
                .field("api_key", &api_key.as_ref().map(|_| "<redacted>"))
                .field("model", model)
                .finish(),
        }
    }
}

/// The valid `CODELORE_LLM_PROVIDER` values, echoed in the unknown-provider
/// error.
const VALID_PROVIDERS: &str = "\"anthropic\" or \"openai-compat\"";

/// Choose a client shape from environment inputs. An explicit provider is
/// REQUIRED for the hosted dialect: an ambient `ANTHROPIC_API_KEY` alone —
/// commonly exported for unrelated tooling — must never redirect repository
/// evidence to a hosted endpoint under a local-first posture, so key
/// presence without a provider is an error naming the fix, not a silent
/// dialect switch.
fn resolve(env: &LlmEnv) -> Result<Resolved> {
    match env.provider.as_deref().map(str::trim) {
        Some(provider) if provider.eq_ignore_ascii_case("anthropic") => resolve_anthropic(env),
        Some(provider) if provider.eq_ignore_ascii_case("openai-compat") => {
            resolve_openai_compat(env)
        }
        Some(other) => Err(CodeLoreError::Analysis(format!(
            "unknown CODELORE_LLM_PROVIDER {other:?} — set it to {VALID_PROVIDERS}"
        ))),
        None if env.anthropic_key.is_some() => Err(CodeLoreError::Analysis(
            "ANTHROPIC_API_KEY is set but CODELORE_LLM_PROVIDER is not — refusing to \
             infer a hosted endpoint from an ambient credential. Set \
             CODELORE_LLM_PROVIDER=anthropic to send fact sheets to the hosted API, \
             or leave it unset to stay on the local OpenAI-compatible endpoint."
                .to_string(),
        )),
        None => resolve_openai_compat(env),
    }
}

/// Resolve the Anthropic dialect. Requires an Anthropic key; the base URL is
/// always the Anthropic default (the local base env var is OpenAI-shaped).
fn resolve_anthropic(env: &LlmEnv) -> Result<Resolved> {
    let api_key = env.anthropic_key.clone().ok_or_else(|| {
        CodeLoreError::Analysis(
            "Anthropic provider selected but ANTHROPIC_API_KEY is not set".to_string(),
        )
    })?;
    Ok(Resolved::Anthropic {
        api_key,
        model: env
            .model
            .clone()
            .unwrap_or_else(|| DEFAULT_ANTHROPIC_MODEL.to_string()),
        base_url: DEFAULT_ANTHROPIC_BASE_URL.to_string(),
    })
}

/// Resolve the OpenAI-compatible dialect. Requires a model; the base URL falls
/// back to the local-first default.
fn resolve_openai_compat(env: &LlmEnv) -> Result<Resolved> {
    let model = env.model.clone().ok_or_else(|| {
        CodeLoreError::Analysis(
            "OpenAI-compatible provider requires a model — set CODELORE_LLM_MODEL \
             (e.g. from `ollama list`)"
                .to_string(),
        )
    })?;
    let base_url = env
        .base_url
        .clone()
        .unwrap_or_else(|| DEFAULT_OPENAI_COMPAT_BASE_URL.to_string());
    // A bearer token over plaintext HTTP is only acceptable to a loopback
    // listener (ollama, llama.cpp, LM Studio all bind localhost): any other
    // http:// host would leak the credential to the network path.
    if env.api_key.is_some() && base_url.starts_with("http://") && !is_loopback_http(&base_url) {
        return Err(CodeLoreError::Analysis(format!(
            "CODELORE_LLM_API_KEY is set but CODELORE_LLM_BASE_URL ({base_url}) is \
             plain http:// to a non-loopback host — the bearer token would cross \
             the network unencrypted. Use https://, or a loopback endpoint."
        )));
    }
    Ok(Resolved::OpenAiCompat {
        base_url,
        api_key: env.api_key.clone(),
        model,
    })
}

/// Whether an `http://` base URL points at a loopback host (`localhost`,
/// `127.0.0.0/8`, or `[::1]`), the only place a bearer token may travel
/// unencrypted.
fn is_loopback_http(base_url: &str) -> bool {
    let Some(rest) = base_url.strip_prefix("http://") else {
        return false;
    };
    let authority = rest.split(['/', '?']).next().unwrap_or("");
    let host = authority
        .strip_prefix('[')
        .and_then(|h| h.split(']').next())
        .unwrap_or_else(|| authority.rsplit_once(':').map_or(authority, |(h, _)| h));
    // Parse as a real address rather than prefix-matching: a hostname like
    // `127.evil.example` must not pass as loopback.
    host.eq_ignore_ascii_case("localhost")
        || host == "::1"
        || host
            .parse::<std::net::Ipv4Addr>()
            .is_ok_and(|ip| ip.is_loopback())
}

/// Resolve a [`ChatClient`] from environment inputs (local-first).
///
/// With an explicit `CODELORE_LLM_PROVIDER`, that dialect is used — the
/// Anthropic dialect requires `ANTHROPIC_API_KEY`, the OpenAI-compatible dialect
/// requires `CODELORE_LLM_MODEL`. With no provider set, resolution is
/// local-first and stays local: an ambient `ANTHROPIC_API_KEY` without the
/// explicit provider is an error, never a silent redirect of repository
/// evidence to a hosted endpoint.
pub fn resolve_client(env: &LlmEnv) -> Result<Box<dyn ChatClient>> {
    Ok(match resolve(env)? {
        Resolved::Anthropic {
            api_key,
            model,
            base_url,
        } => Box::new(AnthropicClient::new(api_key, model, base_url)),
        Resolved::OpenAiCompat {
            base_url,
            api_key,
            model,
        } => Box::new(OpenAiCompatClient::new(base_url, api_key, model)),
    })
}

#[cfg(test)]
mod tests {
    use super::{
        DEFAULT_ANTHROPIC_BASE_URL, DEFAULT_ANTHROPIC_MODEL, DEFAULT_OPENAI_COMPAT_BASE_URL,
        LlmEnv, REQUEST_TIMEOUT_SECS, Resolved, resolve, resolve_client, resolve_timeout_secs,
    };

    /// The override exists because the default is a budget, not a fact: a
    /// field study had to patch this constant to run a slower model at all.
    /// Parsing is pure so it is testable without mutating process
    /// environment, matching how every other knob here is exercised.
    #[test]
    fn timeout_override_accepts_positive_values_and_falls_back_otherwise() {
        assert_eq!(resolve_timeout_secs(Some("600")), 600);
        assert_eq!(resolve_timeout_secs(Some("1")), 1);
        assert_eq!(resolve_timeout_secs(None), REQUEST_TIMEOUT_SECS);
        for bad in ["0", "-30", "abc", "12.5", "600s", "", " "] {
            assert_eq!(
                resolve_timeout_secs(Some(bad)),
                REQUEST_TIMEOUT_SECS,
                "{bad:?} must fall back to the default"
            );
        }
    }

    #[test]
    fn explicit_anthropic_resolves_with_default_model_and_base() {
        let env = LlmEnv {
            provider: Some("anthropic".to_string()),
            anthropic_key: Some("secret".to_string()),
            ..LlmEnv::default()
        };
        match resolve(&env).expect("resolves") {
            Resolved::Anthropic {
                api_key,
                model,
                base_url,
            } => {
                assert_eq!(api_key, "secret");
                assert_eq!(model, DEFAULT_ANTHROPIC_MODEL);
                assert_eq!(base_url, DEFAULT_ANTHROPIC_BASE_URL);
            }
            Resolved::OpenAiCompat { .. } => panic!("expected the Anthropic dialect"),
        }
    }

    #[test]
    fn explicit_anthropic_without_key_names_the_key_var() {
        let env = LlmEnv {
            provider: Some("anthropic".to_string()),
            ..LlmEnv::default()
        };
        let err = resolve(&env).expect_err("missing key must error");
        assert!(
            err.to_string().contains("ANTHROPIC_API_KEY"),
            "error should name the key var: {err}"
        );
    }

    #[test]
    fn explicit_openai_compat_resolves_with_default_base() {
        let env = LlmEnv {
            provider: Some("openai-compat".to_string()),
            model: Some("llama3".to_string()),
            ..LlmEnv::default()
        };
        match resolve(&env).expect("resolves") {
            Resolved::OpenAiCompat {
                base_url,
                api_key,
                model,
            } => {
                assert_eq!(base_url, DEFAULT_OPENAI_COMPAT_BASE_URL);
                assert_eq!(api_key, None);
                assert_eq!(model, "llama3");
            }
            Resolved::Anthropic { .. } => panic!("expected the OpenAI-compatible dialect"),
        }
    }

    #[test]
    fn explicit_openai_compat_without_model_names_the_model_var_and_ollama() {
        let env = LlmEnv {
            provider: Some("openai-compat".to_string()),
            ..LlmEnv::default()
        };
        let err = resolve(&env).expect_err("missing model must error");
        let message = err.to_string();
        assert!(
            message.contains("CODELORE_LLM_MODEL"),
            "error should name the model var: {message}"
        );
        assert!(
            message.contains("ollama list"),
            "error should suggest `ollama list`: {message}"
        );
    }

    #[test]
    fn an_ambient_anthropic_key_without_a_provider_is_an_error() {
        // Local-first contract: a key exported for unrelated tooling must
        // never silently redirect repository evidence to a hosted endpoint.
        let env = LlmEnv {
            anthropic_key: Some("secret".to_string()),
            ..LlmEnv::default()
        };
        let err = resolve(&env).expect_err("ambient key must not select a dialect");
        assert!(
            err.to_string().contains("CODELORE_LLM_PROVIDER"),
            "the error must name the fix: {err}"
        );
    }

    #[test]
    fn an_explicit_anthropic_provider_selects_the_dialect() {
        let env = LlmEnv {
            provider: Some("anthropic".to_string()),
            anthropic_key: Some("secret".to_string()),
            ..LlmEnv::default()
        };
        assert!(matches!(
            resolve(&env).expect("resolves"),
            Resolved::Anthropic { .. }
        ));
    }

    #[test]
    fn a_bearer_token_over_plain_http_requires_a_loopback_host() {
        let base = |url: &str| LlmEnv {
            provider: Some("openai-compat".to_string()),
            model: Some("llama3".to_string()),
            base_url: Some(url.to_string()),
            api_key: Some("bearer".to_string()),
            ..LlmEnv::default()
        };
        for ok in [
            "http://localhost:11434/v1",
            "http://127.0.0.1:8080/v1",
            "http://[::1]:8080/v1",
            "https://api.example.com/v1",
        ] {
            assert!(resolve(&base(ok)).is_ok(), "{ok} should resolve");
        }
        for bad in [
            "http://llm.internal:8080/v1",
            "http://127.evil.example/v1", // hostname, not a loopback IP
        ] {
            let err = resolve(&base(bad)).expect_err("non-loopback http + bearer");
            assert!(
                err.to_string().contains("unencrypted"),
                "the error must explain the leak: {err}"
            );
        }
    }

    #[test]
    fn no_config_but_a_model_resolves_to_the_local_default() {
        let env = LlmEnv {
            model: Some("llama3".to_string()),
            ..LlmEnv::default()
        };
        match resolve(&env).expect("resolves") {
            Resolved::OpenAiCompat { base_url, .. } => {
                assert_eq!(base_url, DEFAULT_OPENAI_COMPAT_BASE_URL);
            }
            Resolved::Anthropic { .. } => panic!("expected the local-first dialect"),
        }
    }

    #[test]
    fn debug_redacts_credential_material() {
        // Anthropic dialect: the required key must never appear in `{:?}`.
        let anthropic = resolve(&LlmEnv {
            provider: Some("anthropic".to_string()),
            anthropic_key: Some("sk-ant-super-secret".to_string()),
            ..LlmEnv::default()
        })
        .expect("resolves");
        let rendered = format!("{anthropic:?}");
        assert!(
            !rendered.contains("sk-ant-super-secret"),
            "Debug leaked the Anthropic key: {rendered}"
        );
        assert!(
            rendered.contains("<redacted>"),
            "Debug should mark the key redacted: {rendered}"
        );

        // OpenAI-compatible dialect: the optional bearer token is redacted but
        // its presence stays visible (Some vs None).
        let openai = resolve(&LlmEnv {
            provider: Some("openai-compat".to_string()),
            base_url: Some("http://localhost:1234/v1".to_string()),
            api_key: Some("bearer-token-do-not-log".to_string()),
            model: Some("llama3".to_string()),
            ..LlmEnv::default()
        })
        .expect("resolves");
        let rendered = format!("{openai:?}");
        assert!(
            !rendered.contains("bearer-token-do-not-log"),
            "Debug leaked the bearer token: {rendered}"
        );
        assert!(
            rendered.contains("Some(\"<redacted>\")"),
            "Debug should show the token present-but-redacted: {rendered}"
        );
    }

    #[test]
    fn unknown_provider_names_the_valid_values() {
        let env = LlmEnv {
            provider: Some("gpt4all".to_string()),
            ..LlmEnv::default()
        };
        let err = resolve(&env).expect_err("unknown provider must error");
        let message = err.to_string();
        assert!(
            message.contains("anthropic") && message.contains("openai-compat"),
            "error should list the valid providers: {message}"
        );
    }

    #[test]
    fn resolve_client_wires_the_model_id() {
        let anthropic = LlmEnv {
            provider: Some("anthropic".to_string()),
            anthropic_key: Some("secret".to_string()),
            ..LlmEnv::default()
        };
        assert_eq!(
            resolve_client(&anthropic).expect("client").model_id(),
            DEFAULT_ANTHROPIC_MODEL
        );

        let local = LlmEnv {
            model: Some("llama3".to_string()),
            ..LlmEnv::default()
        };
        assert_eq!(resolve_client(&local).expect("client").model_id(), "llama3");
    }
}