zeph 0.22.1

Lightweight AI agent with hybrid inference, skills-first architecture, and multi-channel I/O
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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

pub use zeph_core::provider_factory::{BootstrapError, build_provider_from_entry};

use std::sync::Arc;

use zeph_llm::any::AnyProvider;
use zeph_llm::ollama::OllamaProvider;
use zeph_llm::provider_dyn::LlmProviderDyn;
use zeph_llm::router::cascade::ClassifierMode;
use zeph_llm::router::coe::CoeConfig as RouterCoeConfig;
use zeph_llm::router::triage::{ComplexityTier, TriageRouter};
use zeph_llm::router::{AsiRouterConfig, BanditRouterConfig, CascadeRouterConfig, RouterProvider};

use zeph_core::config::{Config, LlmRoutingStrategy, ProviderEntry};

/// Build the primary `AnyProvider` from the resolved config.
///
/// Delegates to the internal provider pool builder. Entry point for bootstrap and channel
/// initialization — call this once per startup or config reload.
///
/// # Errors
///
/// Returns `BootstrapError::Provider` when no provider in `[[llm.providers]]` can be
/// initialized.
pub fn create_provider(config: &Config) -> Result<AnyProvider, BootstrapError> {
    create_provider_from_pool(config)
}

fn build_cascade_router_config(
    cascade_cfg: &zeph_core::config::CascadeConfig,
    config: &Config,
) -> CascadeRouterConfig {
    let classifier_mode = match cascade_cfg.classifier_mode {
        zeph_core::config::CascadeClassifierMode::Judge => ClassifierMode::Judge,
        _ => ClassifierMode::Heuristic,
    };
    // SEC-CASCADE-01: clamp quality_threshold to [0.0, 1.0]; reject NaN/Inf.
    let raw_threshold = cascade_cfg.quality_threshold;
    let quality_threshold = if raw_threshold.is_finite() {
        raw_threshold.clamp(0.0, 1.0)
    } else {
        tracing::warn!(
            raw_threshold,
            "cascade quality_threshold is non-finite, defaulting to 0.5"
        );
        0.5
    };
    if (quality_threshold - raw_threshold).abs() > f64::EPSILON {
        tracing::warn!(
            raw_threshold,
            clamped = quality_threshold,
            "cascade quality_threshold out of range [0.0, 1.0], clamped"
        );
    }
    // SEC-CASCADE-02: clamp window_size to minimum 1 to prevent silent no-op tracking.
    let window_size = cascade_cfg.window_size.max(1);
    if window_size != cascade_cfg.window_size {
        tracing::warn!(
            raw = cascade_cfg.window_size,
            "cascade window_size=0 is invalid, clamped to 1"
        );
    }
    // Build summary provider for judge mode.
    let summary_provider: Option<Arc<dyn LlmProviderDyn>> =
        if classifier_mode == ClassifierMode::Judge {
            if let Some(model_spec) = config.llm.summary_model.as_deref() {
                match create_summary_provider(model_spec, config) {
                    Ok(p) => Some(Arc::new(p) as Arc<dyn LlmProviderDyn>),
                    Err(e) => {
                        tracing::warn!(
                            error = %e,
                            "cascade: failed to build judge provider, falling back to heuristic"
                        );
                        None
                    }
                }
            } else {
                tracing::warn!(
                    "cascade: classifier_mode=judge requires [llm] summary_model to \
                     be configured; falling back to heuristic"
                );
                None
            }
        } else {
            None
        };
    CascadeRouterConfig {
        quality_threshold,
        max_escalations: cascade_cfg.max_escalations,
        classifier_mode,
        window_size,
        max_cascade_tokens: cascade_cfg.max_cascade_tokens,
        summary_provider,
        cost_tiers: cascade_cfg.cost_tiers.clone(),
        judge_timeout_ms: cascade_cfg.judge_timeout_ms,
    }
}

/// Clamp a `CoE` threshold to `[0.0, 1.0]` and warn on invalid values.
fn validate_coe_threshold(name: &str, value: f64) -> f64 {
    if value.is_nan() || value.is_infinite() || !(0.0..=1.0).contains(&value) {
        tracing::warn!(
            field = name,
            value,
            "coe: threshold out of [0.0, 1.0] — clamping to valid range"
        );
        return value.clamp(0.0, 1.0);
    }
    value
}

/// Attach `CoE` to a `RouterProvider` if `[llm.coe]` is configured and enabled.
///
/// Skips silently when the secondary or embed provider cannot be resolved.
fn apply_coe(router: RouterProvider, config: &Config) -> RouterProvider {
    let Some(coe_cfg) = config.llm.coe.as_ref() else {
        return router;
    };
    if !coe_cfg.enabled {
        return router;
    }
    let pool = &config.llm.providers;
    let secondary = if coe_cfg.secondary_provider.is_empty() {
        // fall back to the first non-embed provider
        pool.iter()
            .find(|e| !e.embed)
            .and_then(|e| build_provider_from_entry(e, config, None).ok())
    } else {
        pool.iter()
            .find(|e| e.effective_name() == coe_cfg.secondary_provider.as_str())
            .and_then(|e| build_provider_from_entry(e, config, None).ok())
    };
    let embed = if coe_cfg.embedding_provider.is_empty() {
        pool.iter()
            .find(|e| e.embed)
            .and_then(|e| build_provider_from_entry(e, config, None).ok())
    } else {
        pool.iter()
            .find(|e| e.effective_name() == coe_cfg.embedding_provider.as_str())
            .and_then(|e| build_provider_from_entry(e, config, None).ok())
    };
    if let (Some(sec), Some(emb)) = (secondary, embed) {
        let intra = validate_coe_threshold("intra_threshold", coe_cfg.intra_threshold);
        let inter = validate_coe_threshold("inter_threshold", coe_cfg.inter_threshold);
        let shadow = validate_coe_threshold("shadow_sample_rate", coe_cfg.shadow_sample_rate);
        let router_coe = RouterCoeConfig {
            intra_threshold: intra,
            inter_threshold: inter,
            shadow_sample_rate: shadow,
        };
        tracing::info!("coe: enabled (intra={:.2} inter={:.2})", intra, inter);
        router.with_coe(router_coe, sec, emb)
    } else {
        tracing::warn!("coe: secondary or embed provider not resolved, CoE disabled");
        router
    }
}

/// Look up the pool's dedicated `embed = true` provider entry.
///
/// Warns when more than one entry is flagged `embed = true`: only the first (in pool
/// order) is ever used by [`apply_dedicated_embed_provider`] or `build_triage_provider`,
/// so any additional `embed = true` entry is dead configuration — it is also excluded from
/// the router's chat pool by `build_all_pool_providers`, meaning it is never dispatched to
/// at all (#5859 critic finding F3).
fn find_dedicated_embed_entry(pool: &[ProviderEntry]) -> Option<&ProviderEntry> {
    let mut embed_entries = pool.iter().filter(|e| e.embed);
    let first = embed_entries.next()?;
    let rest: Vec<String> = embed_entries.map(ProviderEntry::effective_name).collect();
    if !rest.is_empty() {
        tracing::warn!(
            used = first.effective_name(),
            unused = ?rest,
            "multiple [[llm.providers]] entries flagged embed = true; only the first is \
             used, the rest are dead configuration (never dispatched to)"
        );
    }
    Some(first)
}

/// Log the pool of chat providers that could be selected by the generic
/// `supports_embeddings()` scan when no dedicated `embed = true` provider is configured.
///
/// Without this, an operator running multiple providers of the same backend type (e.g. two
/// Ollama entries) has no way to tell from the logs which instance will actually serve
/// `embed()` calls, since selection happens dynamically per call from the router's ordered
/// pool (#5859 critic finding F5).
fn log_no_dedicated_embed_provider(pool: &[ProviderEntry]) {
    let candidates: Vec<String> = pool
        .iter()
        .filter(|e| !e.embed)
        .map(ProviderEntry::effective_name)
        .collect();
    tracing::info!(
        candidates = ?candidates,
        "no dedicated embed = true provider configured; embed() will use the first chat \
         provider reporting supports_embeddings() == true from this list, in router order"
    );
}

/// Attach the pool's dedicated `embed = true` provider to a `RouterProvider`, if configured.
///
/// `build_all_pool_providers` excludes `embed = true` entries from the router's chat
/// pool (they are not meant to be dispatched to for `chat`/`chat_stream`), which means the
/// generic `supports_embeddings()` scan in `RouterProvider::embed`/`embed_batch` would
/// otherwise never see them and could fall back to any chat provider of the same backend
/// type that happens to also report `supports_embeddings() == true` (#5859). Wiring the
/// dedicated provider in separately via `with_embed_provider` closes that gap without
/// admitting embed-only entries into the chat pool.
fn apply_dedicated_embed_provider(
    router: RouterProvider,
    pool: &[ProviderEntry],
    config: &Config,
) -> RouterProvider {
    let Some(entry) = find_dedicated_embed_entry(pool) else {
        log_no_dedicated_embed_provider(pool);
        return router;
    };
    match build_provider_from_entry(entry, config, None) {
        Ok(p) => router.with_embed_provider(p),
        Err(e) => {
            tracing::warn!(
                provider = entry.effective_name(),
                error = %e,
                "failed to build dedicated embed provider, generic embed selection will be used"
            );
            router
        }
    }
}

/// Apply ASI and `quality_gate` configuration to a `RouterProvider` from `[llm.routing]` config.
fn apply_routing_signals(router: RouterProvider, config: &Config) -> RouterProvider {
    let router_cfg = config.llm.router.as_ref();
    let mut router = router;

    // ASI coherence tracking.
    if let Some(asi_cfg) = router_cfg.and_then(|r| r.asi.as_ref())
        && asi_cfg.enabled
    {
        let threshold = asi_cfg.coherence_threshold.clamp(0.0, 1.0);
        let penalty = asi_cfg.penalty_weight.clamp(0.0, 1.0);
        if (threshold - asi_cfg.coherence_threshold).abs() > f32::EPSILON
            || (penalty - asi_cfg.penalty_weight).abs() > f32::EPSILON
        {
            tracing::warn!("asi: coherence_threshold/penalty_weight clamped to [0.0, 1.0]");
        }
        router = router.with_asi(AsiRouterConfig {
            window: asi_cfg.window,
            coherence_threshold: threshold,
            penalty_weight: penalty,
        });
    }

    // Quality gate.
    if let Some(threshold) = router_cfg.and_then(|r| r.quality_gate) {
        if threshold.is_finite() && threshold > 0.0 && threshold <= 1.0 {
            router = router.with_quality_gate(threshold);
        } else {
            tracing::warn!(
                quality_gate = threshold,
                "quality_gate must be in (0.0, 1.0], ignoring"
            );
        }
    }

    // Embed concurrency semaphore.
    let embed_concurrency = router_cfg.map_or(4, |r| r.embed_concurrency);
    router = router.with_embed_concurrency(embed_concurrency);

    router
}

/// Look up a provider entry from the pool by name (exact match on `effective_name()`) or type.
///
/// Used by quarantine, guardrail, judge, and experiment eval model resolution.
pub fn create_named_provider(
    name: impl AsRef<str>,
    config: &Config,
) -> Result<AnyProvider, BootstrapError> {
    let name = name.as_ref();
    let entry = config
        .llm
        .providers
        .iter()
        .find(|e| e.effective_name() == name || e.provider_type.as_str() == name)
        .ok_or_else(|| {
            BootstrapError::Provider(format!("provider '{name}' not found in [[llm.providers]]"))
        })?;
    build_provider_from_entry(entry, config, None)
}

/// Resolve the embedding provider for the code indexer and retriever.
///
/// Reads `config.index.embedding_provider`. When the name is non-empty and present in
/// `[[llm.providers]]`, constructs that provider. When unset, empty, or unknown, logs a
/// warning and returns `fallback` (the main agent provider).
///
/// Use this function as the single resolution point so the provider is constructed exactly
/// once and shared between the indexer and the retriever.
///
/// # Examples
///
/// ```no_run
/// use zeph_config::Config;
/// use zeph_llm::any::AnyProvider;
/// use crate::bootstrap::resolve_index_embed_provider;
///
/// # fn get_config() -> Config { unimplemented!() }
/// # fn get_fallback() -> AnyProvider { unimplemented!() }
/// let config = get_config();
/// let fallback = get_fallback();
/// // Resolved once; passed to both the indexer and the retriever/search executor.
/// let index_provider = resolve_index_embed_provider(&config, fallback);
/// ```
pub fn resolve_index_embed_provider(config: &Config, fallback: AnyProvider) -> AnyProvider {
    let Some(name) = config
        .index
        .embedding_provider
        .as_ref()
        .and_then(|p| p.as_non_empty())
    else {
        return fallback;
    };
    match create_named_provider(name, config) {
        Ok(p) => {
            tracing::info!(provider = %name, "Using dedicated embedding provider for indexer");
            p
        }
        Err(e) => {
            tracing::warn!(
                provider = %name,
                "Index embedding_provider resolution failed, using main provider: {e:#}"
            );
            fallback
        }
    }
}

/// Create an `AnyProvider` for use as the summarization provider.
///
/// `model_spec` format (set via `[llm] summary_model`):
/// - `<name>` — looks up a provider by name in `[[llm.providers]]`
/// - `ollama/<model>` — Ollama shorthand: uses the ollama provider from pool with model override
/// - `claude[/<model>]`, `openai[/<model>]`, `gemini[/<model>]` — type shorthand with optional model
pub fn create_summary_provider(
    model_spec: &str,
    config: &Config,
) -> Result<AnyProvider, BootstrapError> {
    // Try direct name lookup first (e.g. "claude", "my-openai").
    if let Some(entry) = config
        .llm
        .providers
        .iter()
        .find(|e| e.effective_name() == model_spec || e.provider_type.as_str() == model_spec)
    {
        return build_provider_from_entry(entry, config, None);
    }

    // Handle `type/model` shorthand: override the model on a matching provider.
    if let Some(((_, model), entry)) = model_spec.split_once('/').and_then(|(b, m)| {
        config
            .llm
            .providers
            .iter()
            .find(|e| e.provider_type.as_str() == b || e.effective_name() == b)
            .map(|e| ((b, m), e))
    }) {
        let mut cloned = entry.clone();
        cloned.model = Some(model.to_owned());
        // Cap summary max_tokens at 4096 — summaries are short.
        cloned.max_tokens = Some(cloned.max_tokens.unwrap_or(4096).min(4096));
        return build_provider_from_entry(&cloned, config, None);
    }

    Err(BootstrapError::Provider(format!(
        "summary_model '{model_spec}' not found in [[llm.providers]]. \
         Use a provider name or 'type/model' shorthand (e.g. 'ollama/qwen3:1.7b')."
    )))
}

/// Build the primary `AnyProvider` from the new `[[llm.providers]]` pool.
///
/// When `[llm] routing` is set to a non-None strategy, all providers in the pool are
/// initialized and wrapped in a `RouterProvider` with the appropriate strategy.
/// When routing is `None`, selects the provider marked `default = true` (or the first
/// entry) and falls back to subsequent entries on initialization failure.
#[allow(clippy::too_many_lines)]
fn create_provider_from_pool(config: &Config) -> Result<AnyProvider, BootstrapError> {
    let pool = &config.llm.providers;

    // Empty pool → default Ollama on localhost.
    if pool.is_empty() {
        let base_url = config.llm.effective_base_url();
        let model = config.llm.effective_model();
        let embed = &config.llm.embedding_model;
        return Ok(AnyProvider::Ollama(OllamaProvider::new(
            base_url,
            model.to_owned(),
            embed.clone(),
        )));
    }

    match config.llm.routing {
        LlmRoutingStrategy::Ema => {
            let providers = build_all_pool_providers(pool, config)?;
            let raw_alpha = config.llm.router_ema_alpha;
            let alpha = raw_alpha.clamp(f64::MIN_POSITIVE, 1.0);
            if (alpha - raw_alpha).abs() > f64::EPSILON {
                tracing::warn!(
                    raw_alpha,
                    clamped = alpha,
                    "router_ema_alpha out of range [MIN_POSITIVE, 1.0], clamped"
                );
            }
            let router =
                RouterProvider::new(providers).with_ema(alpha, config.llm.router_reorder_interval);
            let router = apply_coe(router, config);
            let router = apply_dedicated_embed_provider(router, pool, config);
            Ok(AnyProvider::Router(Box::new(apply_routing_signals(
                router, config,
            ))))
        }
        LlmRoutingStrategy::Thompson => {
            let providers = build_all_pool_providers(pool, config)?;
            let state_path = config
                .llm
                .router
                .as_ref()
                .and_then(|r| r.thompson_state_path.as_deref())
                .map(std::path::Path::new);
            let router = RouterProvider::new(providers).with_thompson(state_path);
            let router = apply_coe(router, config);
            let router = apply_dedicated_embed_provider(router, pool, config);
            Ok(AnyProvider::Router(Box::new(apply_routing_signals(
                router, config,
            ))))
        }
        LlmRoutingStrategy::Cascade => {
            let providers = build_all_pool_providers(pool, config)?;
            let cascade_cfg = config
                .llm
                .router
                .as_ref()
                .and_then(|r| r.cascade.clone())
                .unwrap_or_default();
            let router_cascade_cfg = build_cascade_router_config(&cascade_cfg, config);
            let embed_concurrency = config
                .llm
                .router
                .as_ref()
                .map_or(4, |r| r.embed_concurrency);
            let router = RouterProvider::new(providers)
                .with_cascade(router_cascade_cfg)
                .with_embed_concurrency(embed_concurrency);
            let router = apply_dedicated_embed_provider(router, pool, config);
            Ok(AnyProvider::Router(Box::new(router)))
        }
        LlmRoutingStrategy::Bandit => {
            let providers = build_all_pool_providers(pool, config)?;
            let bandit_cfg = config
                .llm
                .router
                .as_ref()
                .and_then(|r| r.bandit.clone())
                .unwrap_or_default();
            let state_path = bandit_cfg.state_path.as_deref().map(std::path::Path::new);
            let router_bandit_cfg = BanditRouterConfig {
                alpha: bandit_cfg.alpha,
                dim: bandit_cfg.dim,
                cost_weight: bandit_cfg.cost_weight.clamp(0.0, 1.0),
                decay_factor: bandit_cfg.decay_factor,
                warmup_queries: bandit_cfg.warmup_queries.unwrap_or(0),
                embedding_timeout_ms: bandit_cfg.embedding_timeout_ms,
                cache_size: bandit_cfg.cache_size,
                memory_confidence_threshold: bandit_cfg.memory_confidence_threshold.clamp(0.0, 1.0),
            };
            // Resolve embedding provider for feature vectors.
            let embed_provider = if bandit_cfg.embedding_provider.is_empty() {
                None
            } else if let Some(entry) = pool
                .iter()
                .find(|e| e.effective_name() == bandit_cfg.embedding_provider.as_str())
            {
                match build_provider_from_entry(entry, config, None) {
                    Ok(p) => Some(p),
                    Err(e) => {
                        tracing::warn!(
                            provider = %bandit_cfg.embedding_provider,
                            error = %e,
                            "bandit: embedding provider failed to init, bandit will use Thompson fallback"
                        );
                        None
                    }
                }
            } else {
                tracing::warn!(
                    provider = %bandit_cfg.embedding_provider,
                    "bandit: embedding_provider not found in [[llm.providers]], \
                     bandit will use Thompson fallback"
                );
                None
            };
            let embed_concurrency = config
                .llm
                .router
                .as_ref()
                .map_or(4, |r| r.embed_concurrency);
            let router = RouterProvider::new(providers)
                .with_bandit(router_bandit_cfg, state_path, embed_provider)
                .with_embed_concurrency(embed_concurrency);
            let router = apply_dedicated_embed_provider(router, pool, config);
            Ok(AnyProvider::Router(Box::new(router)))
        }
        LlmRoutingStrategy::Triage => build_triage_provider(pool, config),
        _ => build_single_provider_from_pool(pool, config),
    }
}

/// Initialize all providers in the pool, skipping those that fail with a warning.
/// Returns an error if no provider could be initialized.
fn build_all_pool_providers(
    pool: &[ProviderEntry],
    config: &Config,
) -> Result<Vec<AnyProvider>, BootstrapError> {
    let mut providers = Vec::new();
    for entry in pool {
        if entry.embed {
            continue;
        }
        match build_provider_from_entry(entry, config, None) {
            Ok(p) => providers.push(p),
            Err(e) => {
                tracing::warn!(
                    provider = entry.name.as_deref().unwrap_or("?"),
                    error = %e,
                    "skipping pool provider during routing initialization"
                );
            }
        }
    }
    if providers.is_empty() {
        return Err(BootstrapError::Provider(
            "routing enabled but no providers in [[llm.providers]] could be initialized".into(),
        ));
    }
    Ok(providers)
}

/// Build a `TriageRouter`-backed `AnyProvider` from the pool.
///
/// Reads `[llm.complexity_routing]` config and constructs tier providers by name lookup.
/// If `bypass_single_provider = true` and all configured tiers resolve to the same provider,
/// returns a single provider instead of wrapping in a `TriageRouter`.
fn build_triage_provider(
    pool: &[zeph_core::config::ProviderEntry],
    config: &zeph_core::config::Config,
) -> Result<AnyProvider, BootstrapError> {
    let cr = config.llm.complexity_routing.as_ref().ok_or_else(|| {
        BootstrapError::Provider(
            "routing = \"triage\" requires [llm.complexity_routing] section".into(),
        )
    })?;

    // Resolve triage classification provider.
    let default_triage_name = pool
        .first()
        .map(zeph_core::config::ProviderEntry::effective_name)
        .unwrap_or_default();
    let triage_prov_name = cr.triage_provider.as_ref().map_or_else(
        || default_triage_name.as_str(),
        zeph_common::ProviderName::as_str,
    );
    let triage_provider = create_named_provider(triage_prov_name, config).map_err(|e| {
        BootstrapError::Provider(format!(
            "triage_provider '{triage_prov_name}' not found in [[llm.providers]]: {e}"
        ))
    })?;

    // Build tier provider list. Tiers not configured in the mapping are skipped.
    let tier_config: [(ComplexityTier, Option<&str>); 4] = [
        (ComplexityTier::Simple, cr.tiers.simple.as_deref()),
        (ComplexityTier::Medium, cr.tiers.medium.as_deref()),
        (ComplexityTier::Complex, cr.tiers.complex.as_deref()),
        (ComplexityTier::Expert, cr.tiers.expert.as_deref()),
    ];

    // Collect (tier, config_name, provider) triples.
    // Bypass detection compares config names (not provider.name()) to correctly distinguish
    // two pool entries using the same provider type (e.g., two Claude configs for Haiku + Opus).
    let mut tier_providers: Vec<(ComplexityTier, AnyProvider)> = Vec::new();
    let mut tier_config_names: Vec<&str> = Vec::new();
    for (tier, maybe_name) in &tier_config {
        let Some(name) = maybe_name else { continue };
        match create_named_provider(name, config) {
            Ok(p) => {
                tier_providers.push((*tier, p));
                tier_config_names.push(name);
            }
            Err(e) => {
                tracing::warn!(
                    tier = tier.as_str(),
                    provider = name,
                    error = %e,
                    "triage: skipping tier provider (not found in pool)"
                );
            }
        }
    }

    if tier_providers.is_empty() {
        // No tiers configured — fall through to single provider.
        tracing::warn!(
            "triage routing: no tier providers configured, \
             falling back to single provider"
        );
        return build_single_provider_from_pool(pool, config);
    }

    // bypass_single_provider: if all tiers reference the same config entry name, skip triage.
    if cr.bypass_single_provider
        && let Some(first_name) = tier_config_names
            .first()
            .copied()
            .filter(|&n| tier_config_names.iter().all(|m| *m == n))
    {
        tracing::debug!(
            provider = first_name,
            "triage routing: all tiers map to same config entry, bypassing triage"
        );
        return build_single_provider_from_pool(pool, config);
    }

    let mut router = TriageRouter::new(
        triage_provider,
        tier_providers,
        cr.triage_timeout_secs,
        cr.max_triage_tokens,
    );
    // #5859 critic F1: without this, TriageRouter::embed/embed_batch re-implement the same
    // "first supports_embeddings() == true tier wins" scan that RouterProvider used to have,
    // which can shadow a dedicated embed = true provider with a chat-only same-backend tier.
    match find_dedicated_embed_entry(pool) {
        Some(entry) => match build_provider_from_entry(entry, config, None) {
            Ok(p) => router = router.with_embed_provider(p),
            Err(e) => {
                tracing::warn!(
                    provider = entry.effective_name(),
                    error = %e,
                    "failed to build dedicated embed provider for triage routing, \
                     generic embed selection will be used"
                );
            }
        },
        None => log_no_dedicated_embed_provider(pool),
    }
    Ok(AnyProvider::Triage(Box::new(router)))
}

/// Pick the default (or first) provider from the pool with fallback on failure.
pub(crate) fn build_single_provider_from_pool(
    pool: &[ProviderEntry],
    config: &Config,
) -> Result<AnyProvider, BootstrapError> {
    let primary_idx = pool
        .iter()
        .position(|e| e.default)
        .or_else(|| pool.iter().position(|e| !e.embed))
        .unwrap_or(0);
    let primary = &pool[primary_idx];
    match build_provider_from_entry(primary, config, None) {
        Ok(p) => Ok(p),
        Err(e) => {
            let name = primary.name.as_deref().unwrap_or("primary");
            tracing::warn!(provider = name, error = %e, "primary provider failed, trying next");
            for (i, entry) in pool.iter().enumerate() {
                if i == primary_idx {
                    continue;
                }
                match build_provider_from_entry(entry, config, None) {
                    Ok(p) => return Ok(p),
                    Err(e2) => {
                        tracing::warn!(
                            provider = entry.name.as_deref().unwrap_or("?"),
                            error = %e2,
                            "fallback provider failed"
                        );
                    }
                }
            }
            Err(BootstrapError::Provider(format!(
                "all providers in [[llm.providers]] failed to initialize; first error: {e}"
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use zeph_core::config::{Config, ProviderEntry, ProviderKind};
    use zeph_llm::any::AnyProvider;

    use super::build_all_pool_providers;

    #[test]
    fn excludes_embed_only_entry() {
        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.providers = vec![
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("embedder".into()),
                model: Some("nomic-embed-text".into()),
                embed: true,
                ..ProviderEntry::default()
            },
        ];
        let providers = build_all_pool_providers(&config.llm.providers, &config).unwrap();
        assert_eq!(providers.len(), 1);
    }

    #[test]
    fn includes_all_non_embed_entries() {
        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.providers = vec![
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat1".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat2".into()),
                model: Some("qwen3:1.7b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
        ];
        let providers = build_all_pool_providers(&config.llm.providers, &config).unwrap();
        assert_eq!(providers.len(), 2);
    }

    #[test]
    fn errors_when_all_providers_are_embed_only() {
        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.providers = vec![ProviderEntry {
            provider_type: ProviderKind::Ollama,
            name: Some("embedder".into()),
            model: Some("nomic-embed-text".into()),
            embed: true,
            ..ProviderEntry::default()
        }];
        let result = build_all_pool_providers(&config.llm.providers, &config);
        assert!(result.is_err());
    }

    #[test]
    fn active_provider_name_skips_embed_only_first_entry() {
        let providers = [
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("embedder".into()),
                model: Some("nomic-embed-text".into()),
                embed: true,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
        ];
        let active = providers
            .iter()
            .find(|e| !e.embed)
            .map_or_else(String::new, ProviderEntry::effective_name);
        assert_eq!(active, "chat");
    }

    #[test]
    fn build_single_provider_skips_embed_only_first_entry() {
        use super::build_single_provider_from_pool;

        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.providers = vec![
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("embedder".into()),
                model: Some("nomic-embed-text".into()),
                embed: true,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
        ];
        // build_single_provider_from_pool must select the non-embed entry (index 1) as primary.
        // For Ollama, provider construction succeeds without a live server.
        let result = build_single_provider_from_pool(&config.llm.providers, &config);
        assert!(result.is_ok(), "expected Ok but got: {result:?}");
    }

    // ── resolve_index_embed_provider ─────────────────────────────────────────

    fn make_fallback() -> AnyProvider {
        use zeph_llm::ollama::OllamaProvider;
        AnyProvider::Ollama(OllamaProvider::new(
            "http://127.0.0.1:1",
            "fallback".into(),
            "fallback-embed".into(),
        ))
    }

    #[test]
    fn resolve_index_embed_provider_empty_returns_fallback() {
        use super::resolve_index_embed_provider;
        let config = Config::load(Path::new("/nonexistent")).unwrap();
        // IndexConfig.embedding_provider defaults to None — empty path.
        let result = resolve_index_embed_provider(&config, make_fallback());
        assert!(
            matches!(result, AnyProvider::Ollama(_)),
            "expected fallback Ollama provider"
        );
    }

    #[test]
    fn resolve_index_embed_provider_unknown_name_returns_fallback() {
        use super::resolve_index_embed_provider;
        use zeph_common::ProviderName;
        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.index.embedding_provider = Some(ProviderName::from("does-not-exist"));
        // No matching entry in llm.providers — should warn and return fallback.
        let result = resolve_index_embed_provider(&config, make_fallback());
        assert!(
            matches!(result, AnyProvider::Ollama(_)),
            "expected fallback Ollama provider on unknown name"
        );
    }

    #[test]
    fn resolve_index_embed_provider_known_name_resolves() {
        use super::resolve_index_embed_provider;
        use zeph_common::ProviderName;
        use zeph_llm::provider::LlmProvider as _;
        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.providers = vec![ProviderEntry {
            provider_type: ProviderKind::Ollama,
            name: Some("index-embed".into()),
            model: Some("nomic-embed-text".into()),
            embed: true,
            ..ProviderEntry::default()
        }];
        config.index.embedding_provider = Some(ProviderName::from("index-embed"));
        let result = resolve_index_embed_provider(&config, make_fallback());
        // model_identifier() proves the resolved provider was constructed, not the fallback returned.
        assert_ne!(
            result.model_identifier(),
            "fallback",
            "should not return the fallback"
        );
        assert_eq!(
            result.model_identifier(),
            "nomic-embed-text",
            "should use configured model"
        );
    }

    // ── apply_dedicated_embed_provider / embed routing (#5859) ────────────────

    /// End-to-end regression for #5859 symptom 1: `build_all_pool_providers` excludes
    /// `embed = true` entries from the router's chat pool, so without
    /// `apply_dedicated_embed_provider` wiring the dedicated embedding entry, `embed()`
    /// falls through to whichever chat-only provider happens to also report
    /// `supports_embeddings() == true` (every `OllamaProvider`, unconditionally).
    ///
    /// The chat-only entry here points at an unreachable address, so if the router ever
    /// fell back to it for embedding, the call would fail instead of returning the mock
    /// server's fixed vector — a network-observable proxy for provider selection.
    #[tokio::test]
    async fn create_provider_from_pool_ema_routes_embed_to_dedicated_entry() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        use zeph_core::config::LlmRoutingStrategy;
        use zeph_llm::provider::LlmProvider as _;

        use super::create_provider_from_pool;

        let embed_server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/embed"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({ "embeddings": [[4.2, 4.2]] })),
            )
            .mount(&embed_server)
            .await;

        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.routing = LlmRoutingStrategy::Ema;
        config.llm.providers = vec![
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("embedder".into()),
                base_url: Some(embed_server.uri()),
                model: Some("nomic-embed-text".into()),
                embed: true,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat".into()),
                base_url: Some("http://127.0.0.1:1".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
        ];

        let provider =
            create_provider_from_pool(&config).expect("router construction must succeed");
        assert!(
            matches!(provider, AnyProvider::Router(_)),
            "Ema routing must produce a Router-wrapped provider"
        );

        let result = provider.embed("hello").await;
        assert_eq!(
            result.unwrap(),
            vec![4.2, 4.2],
            "embed() must route to the embed=true entry via the dedicated-embed-provider \
             side channel, not the unreachable chat-only entry"
        );
    }

    /// Same regression as above under the Cascade strategy, whose provider pool and
    /// `apply_dedicated_embed_provider` wiring path (`create_provider_from_pool`'s
    /// `LlmRoutingStrategy::Cascade` arm) is independent of the Ema arm.
    #[tokio::test]
    async fn create_provider_from_pool_cascade_routes_embed_to_dedicated_entry() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        use zeph_core::config::LlmRoutingStrategy;
        use zeph_llm::provider::LlmProvider as _;

        use super::create_provider_from_pool;

        let embed_server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/embed"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({ "embeddings": [[1.5, 2.5]] })),
            )
            .mount(&embed_server)
            .await;

        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.routing = LlmRoutingStrategy::Cascade;
        config.llm.providers = vec![
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("embedder".into()),
                base_url: Some(embed_server.uri()),
                model: Some("nomic-embed-text".into()),
                embed: true,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat".into()),
                base_url: Some("http://127.0.0.1:1".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
        ];

        let provider =
            create_provider_from_pool(&config).expect("router construction must succeed");
        assert!(
            matches!(provider, AnyProvider::Router(_)),
            "Cascade routing must produce a Router-wrapped provider"
        );

        let result = provider.embed("hello").await;
        assert_eq!(
            result.unwrap(),
            vec![1.5, 2.5],
            "embed() must route to the embed=true entry via the dedicated-embed-provider \
             side channel, not the unreachable chat-only entry"
        );
    }

    /// End-to-end regression for #5859 critic finding F1 under `routing = "triage"`:
    /// `build_triage_provider` wires the pool's `embed = true` entry into
    /// `TriageRouter::with_embed_provider` so `embed()` uses it directly instead of
    /// `TriageRouter::select_embed_provider`'s fallback scan for the first tier reporting
    /// `supports_embeddings() == true` — a scan that would otherwise be shadowed by an
    /// unrelated chat-only Ollama tier, exactly like the original `RouterProvider` bug.
    /// The `triage.rs` unit tests prove the `TriageRouter` selection logic in isolation;
    /// this test proves the bootstrap wiring (`find_dedicated_embed_entry` →
    /// `build_provider_from_entry` → `with_embed_provider`) is actually invoked.
    #[tokio::test]
    async fn build_triage_provider_routes_embed_to_dedicated_entry() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};
        use zeph_config::{ComplexityRoutingConfig, TierMapping};
        use zeph_core::config::LlmRoutingStrategy;
        use zeph_llm::provider::LlmProvider as _;

        use super::create_provider_from_pool;

        let embed_server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/embed"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({ "embeddings": [[7.0, 8.0]] })),
            )
            .mount(&embed_server)
            .await;

        let mut config = Config::load(Path::new("/nonexistent")).unwrap();
        config.llm.routing = LlmRoutingStrategy::Triage;
        config.llm.providers = vec![
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("chat".into()),
                base_url: Some("http://127.0.0.1:1".into()),
                model: Some("qwen3:8b".into()),
                embed: false,
                ..ProviderEntry::default()
            },
            ProviderEntry {
                provider_type: ProviderKind::Ollama,
                name: Some("embedder".into()),
                base_url: Some(embed_server.uri()),
                model: Some("nomic-embed-text".into()),
                embed: true,
                ..ProviderEntry::default()
            },
        ];
        // bypass_single_provider = false: a single "simple" tier mapped to the sole
        // non-embed entry would otherwise be collapsed to build_single_provider_from_pool,
        // which does not exercise the TriageRouter/with_embed_provider path at all.
        config.llm.complexity_routing = Some(ComplexityRoutingConfig {
            triage_provider: None,
            bypass_single_provider: false,
            tiers: TierMapping {
                simple: Some("chat".into()),
                ..TierMapping::default()
            },
            max_triage_tokens: 50,
            triage_timeout_secs: 5,
            fallback_strategy: None,
        });

        let provider =
            create_provider_from_pool(&config).expect("triage router construction must succeed");
        assert!(
            matches!(provider, AnyProvider::Triage(_)),
            "routing = \"triage\" must produce a Triage-wrapped provider"
        );

        let result = provider.embed("hello").await;
        assert_eq!(
            result.unwrap(),
            vec![7.0, 8.0],
            "embed() must route to the embed=true entry via the dedicated-embed-provider \
             side channel, not the first tier reporting supports_embeddings() == true"
        );
    }
}