terraphim_orchestrator 1.19.3

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
//! Routing decision engine for ADF agent dispatch.
//!
//! Combines KG routing, keyword routing, and static config as first-class
//! signals. All candidates are collected and scored, with the winning signal
//! recorded in the decision rationale. Budget pressure biases route selection
//! toward cheaper models when an agent's spend approaches its limit.

use crate::control_plane::telemetry::{RouteSelectionStrategy, TelemetryStore};
use crate::cost_tracker::BudgetVerdict;
use crate::kg_router::KgRouter;
use crate::provider_budget::{provider_key_for_model, ProviderBudgetTracker};
use std::path::PathBuf;
use std::sync::Arc;
use terraphim_types::capability::{CostLevel, Latency, Provider, ProviderType};

#[derive(Debug, Clone, PartialEq)]
pub enum RouteSource {
    KnowledgeGraph,
    KeywordRouting,
    StaticConfig,
    CombinedKgKeyword,
    CliDefault,
}

impl std::fmt::Display for RouteSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RouteSource::KnowledgeGraph => write!(f, "KG"),
            RouteSource::KeywordRouting => write!(f, "keyword"),
            RouteSource::StaticConfig => write!(f, "static"),
            RouteSource::CombinedKgKeyword => write!(f, "KG+keyword"),
            RouteSource::CliDefault => write!(f, "CLI default"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BudgetPressure {
    NoPressure,
    NearExhaustion,
    Exhausted,
}

impl BudgetPressure {
    pub fn from_verdict(verdict: &BudgetVerdict) -> Self {
        match verdict {
            BudgetVerdict::Exhausted { .. } => BudgetPressure::Exhausted,
            BudgetVerdict::NearExhaustion { .. } => BudgetPressure::NearExhaustion,
            _ => BudgetPressure::NoPressure,
        }
    }

    pub fn cost_penalty(&self, cost_level: &CostLevel) -> f64 {
        match self {
            BudgetPressure::NoPressure => 0.0,
            BudgetPressure::NearExhaustion => match cost_level {
                CostLevel::Cheap => 0.0,
                CostLevel::Moderate => 0.15,
                CostLevel::Expensive => 0.35,
            },
            BudgetPressure::Exhausted => match cost_level {
                CostLevel::Cheap => 0.10,
                CostLevel::Moderate => 0.40,
                CostLevel::Expensive => 0.70,
            },
        }
    }
}

#[derive(Debug, Clone)]
pub struct DispatchContext {
    pub agent_name: String,
    pub task: String,
    pub static_model: Option<String>,
    pub cli_tool: String,
    pub layer: crate::config::AgentLayer,
    pub session_id: Option<String>,
}

#[derive(Debug, Clone)]
pub struct RouteCandidate {
    pub provider: Provider,
    pub model: String,
    pub cli_tool: String,
    pub source: RouteSource,
    pub confidence: f64,
}

#[derive(Debug, Clone)]
pub struct RoutingDecision {
    pub candidate: RouteCandidate,
    pub rationale: String,
    pub all_candidates: Vec<RouteCandidate>,
    pub primary_available: bool,
    pub dominant_signal: RouteSource,
    pub budget_pressure: BudgetPressure,
    pub budget_influenced: bool,
    pub telemetry_influenced: bool,
}

fn make_agent_provider(agent_name: &str, cli_tool: &str) -> Provider {
    Provider {
        id: format!("{}-agent", agent_name),
        name: format!("{} (agent)", agent_name),
        provider_type: ProviderType::Agent {
            agent_id: agent_name.to_string(),
            cli_command: cli_tool.to_string(),
            working_dir: PathBuf::from(
                std::env::current_dir()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
            ),
        },
        capabilities: vec![],
        cost_level: CostLevel::Moderate,
        latency: Latency::Medium,
        keywords: vec![],
    }
}

struct CollectedCandidates {
    kg: Vec<RouteCandidate>,
    keyword: Vec<RouteCandidate>,
    static_model: Option<RouteCandidate>,
}

pub struct RoutingDecisionEngine {
    kg_router: Option<Arc<KgRouter>>,
    /// Snapshot of unhealthy provider names at construction time.
    unhealthy_providers: Vec<String>,
    router: terraphim_router::Router,
    telemetry_store: Option<Arc<TelemetryStore>>,
    /// Per-provider hour/day budget tracker. When present, candidates
    /// whose provider verdict is `Exhausted` are stripped before scoring
    /// and `NearExhaustion` entries are deprioritised.
    provider_budget: Option<Arc<ProviderBudgetTracker>>,
    /// Strategy for selecting the best model when telemetry data is available.
    route_selection_strategy: RouteSelectionStrategy,
}

impl RoutingDecisionEngine {
    pub fn new(
        kg_router: Option<Arc<KgRouter>>,
        unhealthy_providers: Vec<String>,
        router: terraphim_router::Router,
        telemetry_store: Option<Arc<TelemetryStore>>,
    ) -> Self {
        Self::with_provider_budget_and_strategy(
            kg_router,
            unhealthy_providers,
            router,
            telemetry_store,
            None,
            RouteSelectionStrategy::Fastest,
        )
    }

    pub fn with_provider_budget(
        kg_router: Option<Arc<KgRouter>>,
        unhealthy_providers: Vec<String>,
        router: terraphim_router::Router,
        telemetry_store: Option<Arc<TelemetryStore>>,
        provider_budget: Option<Arc<ProviderBudgetTracker>>,
    ) -> Self {
        Self::with_provider_budget_and_strategy(
            kg_router,
            unhealthy_providers,
            router,
            telemetry_store,
            provider_budget,
            RouteSelectionStrategy::Fastest,
        )
    }

    pub fn with_provider_budget_and_strategy(
        kg_router: Option<Arc<KgRouter>>,
        unhealthy_providers: Vec<String>,
        router: terraphim_router::Router,
        telemetry_store: Option<Arc<TelemetryStore>>,
        provider_budget: Option<Arc<ProviderBudgetTracker>>,
        route_selection_strategy: RouteSelectionStrategy,
    ) -> Self {
        Self {
            kg_router,
            unhealthy_providers,
            router,
            telemetry_store,
            provider_budget,
            route_selection_strategy,
        }
    }

    fn cli_name(ctx: &DispatchContext) -> &str {
        std::path::Path::new(&ctx.cli_tool)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&ctx.cli_tool)
    }

    fn supports_model_flag(cli_name: &str) -> bool {
        matches!(cli_name, "claude" | "claude-code" | "opencode")
    }

    fn budget_pressure(verdict: &BudgetVerdict) -> BudgetPressure {
        BudgetPressure::from_verdict(verdict)
    }

    fn collect_kg_candidates(&self, ctx: &DispatchContext) -> Vec<RouteCandidate> {
        let kg_router = match self.kg_router {
            Some(ref r) => r,
            None => return Vec::new(),
        };

        let decision = match kg_router.route_agent(&ctx.task) {
            Some(d) => d,
            None => return Vec::new(),
        };

        let unhealthy = &self.unhealthy_providers;
        let mut candidates = Vec::new();

        for route in &decision.fallback_routes {
            let is_healthy = !unhealthy.iter().any(|u| u == &route.provider);
            let is_primary = route.provider == decision.provider;

            let cli_tool = route
                .action
                .as_ref()
                .and_then(|a| a.split_whitespace().next())
                .map(String::from)
                .unwrap_or_else(|| ctx.cli_tool.clone());

            let confidence = if is_primary {
                decision.confidence
            } else {
                decision.confidence * 0.8
            };

            let confidence = if is_healthy {
                confidence
            } else {
                confidence * 0.5
            };

            candidates.push(RouteCandidate {
                provider: make_agent_provider(&ctx.agent_name, &cli_tool),
                model: route.model.clone(),
                cli_tool,
                source: RouteSource::KnowledgeGraph,
                confidence,
            });
        }

        candidates
    }

    fn collect_keyword_candidates(&self, ctx: &DispatchContext) -> Vec<RouteCandidate> {
        let routing_ctx = terraphim_router::RoutingContext::default();
        let decision = match self.router.route(&ctx.task, &routing_ctx) {
            Ok(d) => d,
            Err(_) => return Vec::new(),
        };

        let model_id = match &decision.provider.provider_type {
            ProviderType::Llm { model_id, .. } => model_id.clone(),
            _ => return Vec::new(),
        };

        vec![RouteCandidate {
            provider: make_agent_provider(&ctx.agent_name, &ctx.cli_tool),
            model: model_id,
            cli_tool: ctx.cli_tool.clone(),
            source: RouteSource::KeywordRouting,
            confidence: decision.confidence as f64,
        }]
    }

    fn collect_static_candidate(&self, ctx: &DispatchContext) -> Option<RouteCandidate> {
        ctx.static_model.as_ref().map(|model| RouteCandidate {
            provider: make_agent_provider(&ctx.agent_name, &ctx.cli_tool),
            model: model.clone(),
            cli_tool: ctx.cli_tool.clone(),
            source: RouteSource::StaticConfig,
            confidence: 0.8,
        })
    }

    fn collect_all_candidates(&self, ctx: &DispatchContext) -> CollectedCandidates {
        CollectedCandidates {
            kg: self.collect_kg_candidates(ctx),
            keyword: self.collect_keyword_candidates(ctx),
            static_model: self.collect_static_candidate(ctx),
        }
    }

    fn score_candidate(candidate: &RouteCandidate, pressure: BudgetPressure) -> f64 {
        let source_weight = match candidate.source {
            RouteSource::KnowledgeGraph => 1.0,
            RouteSource::CombinedKgKeyword => 1.0,
            RouteSource::KeywordRouting => 0.8,
            RouteSource::StaticConfig => 0.6,
            RouteSource::CliDefault => 0.3,
        };
        let base = source_weight * candidate.confidence;
        let penalty = pressure.cost_penalty(&candidate.provider.cost_level);
        base * (1.0 - penalty)
    }

    pub async fn decide_route(
        &self,
        ctx: &DispatchContext,
        budget_verdict: &BudgetVerdict,
    ) -> RoutingDecision {
        let cli_name = Self::cli_name(ctx);
        let pressure = Self::budget_pressure(budget_verdict);

        if !Self::supports_model_flag(cli_name) {
            let candidate = RouteCandidate {
                provider: make_agent_provider(&ctx.agent_name, &ctx.cli_tool),
                model: String::new(),
                cli_tool: ctx.cli_tool.clone(),
                source: RouteSource::CliDefault,
                confidence: 0.5,
            };
            return RoutingDecision {
                candidate: candidate.clone(),
                rationale: format!("Using CLI default (no model routing for {})", cli_name),
                all_candidates: vec![candidate],
                primary_available: false,
                dominant_signal: RouteSource::CliDefault,
                budget_pressure: pressure,
                budget_influenced: false,
                telemetry_influenced: false,
            };
        }

        let collected = self.collect_all_candidates(ctx);
        let mut all_candidates = Vec::new();

        let has_kg = !collected.kg.is_empty();
        let has_keyword = !collected.keyword.is_empty();

        if has_kg && has_keyword {
            if let (Some(kg_cand), Some(kw_cand)) =
                (collected.kg.first(), collected.keyword.first())
            {
                if kg_cand.model == kw_cand.model {
                    let merged = RouteCandidate {
                        provider: kg_cand.provider.clone(),
                        model: kg_cand.model.clone(),
                        cli_tool: kg_cand.cli_tool.clone(),
                        source: RouteSource::CombinedKgKeyword,
                        confidence: (kg_cand.confidence + kw_cand.confidence) / 2.0,
                    };
                    all_candidates.push(merged);
                } else {
                    all_candidates.extend(collected.kg.clone());
                    all_candidates.extend(collected.keyword.clone());
                }
            }
        } else {
            all_candidates.extend(collected.kg.clone());
            all_candidates.extend(collected.keyword.clone());
        }

        if let Some(static_cand) = &collected.static_model {
            all_candidates.push(static_cand.clone());
        }

        // Defence-in-depth: strip any candidate whose model prefix is not an
        // allowed subscription provider. Load-time `validate()` already enforces
        // C1/C3 but a malformed KG or telemetry store could still surface a
        // banned target at runtime. Drop it before scoring so the engine
        // cannot select a pay-per-use provider.
        let before_filter = all_candidates.len();
        all_candidates.retain(|cand| {
            let allowed = crate::config::is_allowed_provider(&cand.model);
            if !allowed {
                tracing::warn!(
                    agent = %ctx.agent_name,
                    provider = %cand.provider.name,
                    model = %cand.model,
                    source = ?cand.source,
                    "routing: dropped banned candidate (C1/C3 gate)"
                );
            }
            allowed
        });
        let filtered_out = before_filter - all_candidates.len();

        // Per-provider budget gate: drop candidates whose hourly or daily
        // spend has exhausted its configured cap. `NearExhaustion` does
        // not drop the candidate but is factored into the score below.
        let mut budget_exhausted_keys: Vec<String> = Vec::new();
        let mut near_exhaustion_keys: Vec<String> = Vec::new();
        if let Some(tracker) = self.provider_budget.as_ref() {
            let before_budget = all_candidates.len();
            all_candidates.retain(|cand| {
                let Some(key) = provider_key_for_model(&cand.model) else {
                    return true;
                };
                match tracker.check(key) {
                    BudgetVerdict::Exhausted { .. } => {
                        if !budget_exhausted_keys.iter().any(|k| k == key) {
                            budget_exhausted_keys.push(key.to_string());
                        }
                        tracing::warn!(
                            agent = %ctx.agent_name,
                            provider_key = %key,
                            model = %cand.model,
                            "routing: dropped provider-budget-exhausted candidate"
                        );
                        false
                    }
                    BudgetVerdict::NearExhaustion { .. } => {
                        if !near_exhaustion_keys.iter().any(|k| k == key) {
                            near_exhaustion_keys.push(key.to_string());
                        }
                        true
                    }
                    _ => true,
                }
            });
            let budget_dropped = before_budget - all_candidates.len();
            if budget_dropped > 0 {
                tracing::info!(
                    agent = %ctx.agent_name,
                    dropped = budget_dropped,
                    "routing: stripped provider-budget-exhausted candidates"
                );
            }
        }

        if all_candidates.is_empty() {
            let candidate = RouteCandidate {
                provider: make_agent_provider(&ctx.agent_name, &ctx.cli_tool),
                model: String::new(),
                cli_tool: ctx.cli_tool.clone(),
                source: RouteSource::CliDefault,
                confidence: 0.5,
            };
            let rationale = if filtered_out > 0 {
                format!(
                    "All {} candidate(s) filtered out by C1/C3 allow-list; using CLI default ({})",
                    filtered_out, cli_name
                )
            } else if !budget_exhausted_keys.is_empty() {
                format!(
                    "All candidates dropped by provider-budget gate ({}); using CLI default ({})",
                    budget_exhausted_keys.join(","),
                    cli_name
                )
            } else {
                format!(
                    "No routing signal matched; using CLI default ({})",
                    cli_name
                )
            };
            return RoutingDecision {
                candidate: candidate.clone(),
                rationale,
                all_candidates: vec![candidate],
                primary_available: false,
                dominant_signal: RouteSource::CliDefault,
                budget_pressure: pressure,
                budget_influenced: false,
                telemetry_influenced: false,
            };
        }
        let no_pressure_scores: Vec<f64> = all_candidates
            .iter()
            .map(|c| Self::score_candidate(c, BudgetPressure::NoPressure))
            .collect();
        let mut pressured_scores: Vec<f64> = all_candidates
            .iter()
            .map(|c| Self::score_candidate(c, pressure))
            .collect();

        // Provider-budget near-exhaustion deprioritisation. Multiply the
        // score by 0.6 so a candidate whose provider is 80%+ into its
        // quota is still eligible but loses to a healthy alternative.
        let mut provider_budget_influenced = false;
        if !near_exhaustion_keys.is_empty() {
            for (i, cand) in all_candidates.iter().enumerate() {
                if let Some(key) = provider_key_for_model(&cand.model) {
                    if near_exhaustion_keys.iter().any(|k| k == key) {
                        pressured_scores[i] *= 0.6;
                        provider_budget_influenced = true;
                    }
                }
            }
        }

        // Apply telemetry-based scoring adjustments according to strategy
        let mut telemetry_influenced = false;
        if let Some(ref store) = self.telemetry_store {
            let mut performances = Vec::with_capacity(all_candidates.len());
            for candidate in &all_candidates {
                performances.push(store.model_performance(&candidate.model).await);
            }

            for (i, perf) in performances.iter().enumerate() {
                if perf.is_subscription_limited() {
                    pressured_scores[i] *= 0.1;
                    telemetry_influenced = true;
                    continue;
                }

                if perf.successful_completions == 0 {
                    continue;
                }

                match self.route_selection_strategy {
                    RouteSelectionStrategy::Fastest => {
                        let latency_bonus = if perf.avg_latency_ms > 0.0 {
                            let normalized = (perf.avg_latency_ms / 10000.0).min(1.0);
                            (1.0 - normalized) * 0.3
                        } else {
                            0.0
                        };
                        let success_bonus = (perf.success_rate - 0.5).max(0.0) * 0.1;
                        let bonus = latency_bonus + success_bonus;
                        if bonus > 0.01 {
                            pressured_scores[i] *= 1.0 + bonus;
                            telemetry_influenced = true;
                        }
                    }
                    RouteSelectionStrategy::Cheapest => {
                        let cost_bonus = if perf.avg_cost_per_1k_tokens > 0.0 {
                            let normalized = (perf.avg_cost_per_1k_tokens / 0.1).min(1.0); // 0.1 USD/1k as max reference
                            (1.0 - normalized) * 0.3
                        } else {
                            0.15 // Small bonus for truly free models with zero cost data
                        };
                        let success_bonus = (perf.success_rate - 0.5).max(0.0) * 0.1;
                        let bonus = cost_bonus + success_bonus;
                        if bonus > 0.01 {
                            pressured_scores[i] *= 1.0 + bonus;
                            telemetry_influenced = true;
                        }
                    }
                    RouteSelectionStrategy::FreeThenCheapest => {
                        if perf.is_free {
                            // Strong bonus for free models
                            pressured_scores[i] *= 1.5;
                            telemetry_influenced = true;
                        } else {
                            let cost_bonus = if perf.avg_cost_per_1k_tokens > 0.0 {
                                let normalized = (perf.avg_cost_per_1k_tokens / 0.1).min(1.0);
                                (1.0 - normalized) * 0.2
                            } else {
                                0.1
                            };
                            let success_bonus = (perf.success_rate - 0.5).max(0.0) * 0.1;
                            let bonus = cost_bonus + success_bonus;
                            if bonus > 0.01 {
                                pressured_scores[i] *= 1.0 + bonus;
                                telemetry_influenced = true;
                            }
                        }
                    }
                }
            }
        }

        let mut indexed: Vec<usize> = (0..all_candidates.len()).collect();
        #[allow(clippy::unnecessary_sort_by)]
        indexed.sort_by(|&a, &b| {
            pressured_scores[b]
                .partial_cmp(&pressured_scores[a])
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        let winner_idx = indexed[0];
        let winner = &all_candidates[winner_idx];
        let dominant_signal = winner.source.clone();

        let agent_budget_influenced = pressure != BudgetPressure::NoPressure
            && no_pressure_scores.iter().enumerate().any(|(i, &s)| {
                let was_winner = s >= no_pressure_scores[winner_idx];
                let now_loses = pressured_scores[i] < pressured_scores[winner_idx];
                was_winner && now_loses
            });
        let budget_influenced = agent_budget_influenced || provider_budget_influenced;

        let mut rationale_parts = Vec::new();

        if has_kg {
            rationale_parts.push(format!("KG: {} candidates", collected.kg.len()));
        }
        if has_keyword {
            rationale_parts.push(format!("keyword: {} candidates", collected.keyword.len()));
        }
        if collected.static_model.is_some() {
            rationale_parts.push("static config".to_string());
        }

        let signal_summary = if rationale_parts.is_empty() {
            "no signals".to_string()
        } else {
            rationale_parts.join(", ")
        };

        let mut rationale = format!(
            "Selected {} via {} (score: {:.3}, confidence: {:.2}). Signals: {}",
            winner.model,
            winner.source,
            pressured_scores[winner_idx],
            winner.confidence,
            signal_summary,
        );

        if agent_budget_influenced {
            rationale.push_str(". Budget pressure biased selection toward cheaper model");
        }
        if provider_budget_influenced {
            rationale.push_str(&format!(
                ". Provider near-exhaustion deprioritised: {}",
                near_exhaustion_keys.join(","),
            ));
        }
        if telemetry_influenced {
            rationale.push_str(". Telemetry data influenced selection");
        }

        let primary_available = !matches!(winner.source, RouteSource::CliDefault);

        RoutingDecision {
            candidate: winner.clone(),
            rationale,
            all_candidates,
            primary_available,
            dominant_signal,
            budget_pressure: pressure,
            budget_influenced,
            telemetry_influenced,
        }
    }
}

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

    fn create_test_context_with_cli(
        agent_name: &str,
        task: &str,
        cli_tool: &str,
    ) -> DispatchContext {
        DispatchContext {
            agent_name: agent_name.to_string(),
            task: task.to_string(),
            static_model: None,
            cli_tool: cli_tool.to_string(),
            layer: crate::config::AgentLayer::Core,
            session_id: None,
        }
    }

    fn create_test_context_with_static_model(
        agent_name: &str,
        task: &str,
        static_model: &str,
    ) -> DispatchContext {
        DispatchContext {
            agent_name: agent_name.to_string(),
            task: task.to_string(),
            static_model: Some(static_model.to_string()),
            cli_tool: "opencode".to_string(),
            layer: crate::config::AgentLayer::Core,
            session_id: None,
        }
    }

    fn test_engine() -> RoutingDecisionEngine {
        RoutingDecisionEngine::new(None, Vec::new(), terraphim_router::Router::new(), None)
    }

    fn test_engine_with_spent(
        agent_name: &str,
        budget_cents: Option<u64>,
        spend_usd: f64,
    ) -> (RoutingDecisionEngine, CostTracker) {
        let mut ct = CostTracker::new();
        ct.register(agent_name, budget_cents);
        ct.record_cost(agent_name, spend_usd);
        let engine =
            RoutingDecisionEngine::new(None, Vec::new(), terraphim_router::Router::new(), None);
        (engine, ct)
    }

    #[tokio::test]
    async fn test_cli_default_for_unsupported_tool() {
        let engine = test_engine();
        let ctx = create_test_context_with_cli("test-agent", "Implement a feature", "codex");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::CliDefault);
        assert!(decision.candidate.model.is_empty());
        assert!(decision.rationale.contains("codex"));
        assert_eq!(decision.dominant_signal, RouteSource::CliDefault);
        assert_eq!(decision.budget_pressure, BudgetPressure::NoPressure);
        assert!(!decision.budget_influenced);
    }

    #[tokio::test]
    async fn test_static_model_selected_when_only_signal() {
        let engine = test_engine();
        // Use an allow-list-conformant bare model -- `sonnet` is a
        // claude-code CLI alias and passes C1/C3.
        let ctx =
            create_test_context_with_static_model("test-agent", "Implement a feature", "sonnet");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::StaticConfig);
        assert_eq!(decision.candidate.model, "sonnet");
        assert!(decision.rationale.contains("static config"));
        assert_eq!(decision.dominant_signal, RouteSource::StaticConfig);
    }

    #[tokio::test]
    async fn test_unsupported_cli_ignores_static_model() {
        let engine = test_engine();
        let ctx = DispatchContext {
            agent_name: "test-agent".to_string(),
            task: "Implement a feature".to_string(),
            static_model: Some("some-model".to_string()),
            cli_tool: "codex".to_string(),
            layer: crate::config::AgentLayer::Core,
            session_id: None,
        };
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::CliDefault);
        assert_eq!(decision.dominant_signal, RouteSource::CliDefault);
    }

    #[tokio::test]
    async fn test_opencode_gets_static_model() {
        let engine = test_engine();
        let ctx = create_test_context_with_static_model(
            "test-agent",
            "Implement a feature",
            "kimi-for-coding/k2p5",
        );
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::StaticConfig);
        assert_eq!(decision.candidate.model, "kimi-for-coding/k2p5");
    }

    #[tokio::test]
    async fn test_cli_default_when_no_signals_match() {
        let engine = test_engine();
        let ctx = create_test_context_with_cli("test-agent", "do something", "opencode");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::CliDefault);
        assert!(decision.rationale.contains("No routing signal matched"));
        assert_eq!(decision.dominant_signal, RouteSource::CliDefault);
    }

    #[tokio::test]
    async fn test_rationale_records_dominant_signal() {
        let engine = test_engine();
        // `opus` is an allow-list-conformant claude-code CLI alias.
        let ctx = create_test_context_with_static_model("agent", "task", "opus");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert!(decision.rationale.contains("static config"));
        assert!(decision.rationale.contains("Selected opus"));
    }

    #[tokio::test]
    async fn test_all_candidates_collected_from_multiple_sources() {
        let engine = test_engine();
        let ctx = DispatchContext {
            agent_name: "test-agent".to_string(),
            task: "implement feature".to_string(),
            // Allow-list-conformant static model.
            static_model: Some("kimi-for-coding/k2p5".to_string()),
            cli_tool: "opencode".to_string(),
            layer: crate::config::AgentLayer::Core,
            session_id: None,
        };
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert!(!decision.all_candidates.is_empty());
        assert!(decision
            .all_candidates
            .iter()
            .any(|c| c.source == RouteSource::StaticConfig));
    }

    #[tokio::test]
    async fn test_combined_kg_keyword_when_models_agree() {
        use std::fs;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("impl.md"),
            "priority:: 50\nsynonyms:: implement, build\nroute:: kimi, kimi-for-coding/k2p5\n",
        )
        .unwrap();

        let kg_router = Arc::new(crate::kg_router::KgRouter::load(dir.path()).unwrap());
        let engine = RoutingDecisionEngine::new(
            Some(kg_router),
            Vec::new(),
            terraphim_router::Router::new(),
            None,
        );

        let ctx = create_test_context_with_cli("agent", "implement feature", "opencode");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert!(
            decision.candidate.source == RouteSource::KnowledgeGraph
                || decision.candidate.source == RouteSource::CombinedKgKeyword
                || decision.candidate.source == RouteSource::KeywordRouting,
            "expected a routing signal, got {:?}",
            decision.candidate.source,
        );
        assert!(decision.primary_available);
    }

    #[tokio::test]
    async fn test_kg_only_no_keyword_match() {
        use std::fs;
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("security.md"),
            "priority:: 80\nsynonyms:: security audit, CVE\nroute:: anthropic, opus\n",
        )
        .unwrap();

        let kg_router = Arc::new(crate::kg_router::KgRouter::load(dir.path()).unwrap());
        let engine = RoutingDecisionEngine::new(
            Some(kg_router),
            Vec::new(),
            terraphim_router::Router::new(),
            None,
        );

        let ctx = create_test_context_with_cli("agent", "security audit the codebase", "opencode");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::KnowledgeGraph);
        assert!(decision.candidate.model.contains("opus"));
        assert_eq!(decision.dominant_signal, RouteSource::KnowledgeGraph);
    }

    #[tokio::test]
    async fn test_keyword_only_no_kg_match() {
        let engine = test_engine();
        let ctx = create_test_context_with_cli("agent", "implement a feature", "opencode");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert!(
            decision.candidate.source == RouteSource::KeywordRouting
                || decision.candidate.source == RouteSource::CliDefault,
        );
    }

    #[tokio::test]
    async fn test_dispatch_context_session_id() {
        let ctx = DispatchContext {
            agent_name: "test-agent".to_string(),
            task: "Do something".to_string(),
            static_model: Some("model-id".to_string()),
            cli_tool: "claude".to_string(),
            layer: crate::config::AgentLayer::Safety,
            session_id: Some("sess-123".to_string()),
        };
        assert_eq!(ctx.session_id, Some("sess-123".to_string()));
    }

    #[tokio::test]
    async fn test_route_source_display() {
        assert_eq!(RouteSource::KnowledgeGraph.to_string(), "KG");
        assert_eq!(RouteSource::KeywordRouting.to_string(), "keyword");
        assert_eq!(RouteSource::StaticConfig.to_string(), "static");
        assert_eq!(RouteSource::CombinedKgKeyword.to_string(), "KG+keyword");
        assert_eq!(RouteSource::CliDefault.to_string(), "CLI default");
    }

    #[tokio::test]
    async fn test_make_agent_provider() {
        let provider = make_agent_provider("my-agent", "opencode");
        assert!(provider.id.contains("my-agent"));
        if let ProviderType::Agent {
            agent_id,
            cli_command,
            ..
        } = &provider.provider_type
        {
            assert_eq!(agent_id, "my-agent");
            assert_eq!(cli_command, "opencode");
        } else {
            panic!("expected Agent provider type");
        }
    }

    #[tokio::test]
    async fn test_budget_pressure_no_pressure_for_uncapped() {
        let engine = test_engine();
        let ctx = create_test_context_with_static_model("test-agent", "task", "model-x");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.budget_pressure, BudgetPressure::NoPressure);
        assert!(!decision.budget_influenced);
    }

    #[tokio::test]
    async fn test_budget_pressure_near_exhaustion_detected() {
        let (engine, ct) = test_engine_with_spent("test-agent", Some(10000), 85.0);
        let ctx = create_test_context_with_static_model("test-agent", "task", "model-x");
        let decision = engine.decide_route(&ctx, &ct.check("test-agent")).await;

        assert_eq!(decision.budget_pressure, BudgetPressure::NearExhaustion);
    }

    #[tokio::test]
    async fn test_budget_pressure_exhausted_detected() {
        let (engine, ct) = test_engine_with_spent("test-agent", Some(10000), 100.0);
        let ctx = create_test_context_with_static_model("test-agent", "task", "model-x");
        let decision = engine.decide_route(&ctx, &ct.check("test-agent")).await;

        assert_eq!(decision.budget_pressure, BudgetPressure::Exhausted);
    }

    #[tokio::test]
    async fn test_budget_pressure_penalty_calculation() {
        let no_pressure = BudgetPressure::NoPressure;
        assert_eq!(no_pressure.cost_penalty(&CostLevel::Cheap), 0.0);
        assert_eq!(no_pressure.cost_penalty(&CostLevel::Moderate), 0.0);
        assert_eq!(no_pressure.cost_penalty(&CostLevel::Expensive), 0.0);

        let near = BudgetPressure::NearExhaustion;
        assert_eq!(near.cost_penalty(&CostLevel::Cheap), 0.0);
        assert!((near.cost_penalty(&CostLevel::Moderate) - 0.15).abs() < 0.001);
        assert!((near.cost_penalty(&CostLevel::Expensive) - 0.35).abs() < 0.001);

        let exhausted = BudgetPressure::Exhausted;
        assert!((exhausted.cost_penalty(&CostLevel::Cheap) - 0.10).abs() < 0.001);
        assert!((exhausted.cost_penalty(&CostLevel::Moderate) - 0.40).abs() < 0.001);
        assert!((exhausted.cost_penalty(&CostLevel::Expensive) - 0.70).abs() < 0.001);
    }

    #[tokio::test]
    async fn test_budget_influences_rationale_when_pressure() {
        let (engine, ct) = test_engine_with_spent("test-agent", Some(10000), 85.0);
        let ctx = create_test_context_with_static_model("test-agent", "task", "model-x");
        let decision = engine.decide_route(&ctx, &ct.check("test-agent")).await;

        assert_eq!(decision.budget_pressure, BudgetPressure::NearExhaustion);
    }

    #[tokio::test]
    async fn test_budget_verdict_conversion() {
        assert_eq!(
            BudgetPressure::from_verdict(&BudgetVerdict::Uncapped),
            BudgetPressure::NoPressure
        );
        assert_eq!(
            BudgetPressure::from_verdict(&BudgetVerdict::WithinBudget),
            BudgetPressure::NoPressure
        );
        assert_eq!(
            BudgetPressure::from_verdict(&BudgetVerdict::NearExhaustion {
                spent_cents: 80,
                budget_cents: 100
            }),
            BudgetPressure::NearExhaustion
        );
        assert_eq!(
            BudgetPressure::from_verdict(&BudgetVerdict::Exhausted {
                spent_cents: 100,
                budget_cents: 100
            }),
            BudgetPressure::Exhausted
        );
    }

    #[tokio::test]
    async fn test_score_candidate_with_budget_pressure() {
        let candidate = RouteCandidate {
            provider: Provider {
                id: "test".to_string(),
                name: "test".to_string(),
                provider_type: ProviderType::Agent {
                    agent_id: "test".to_string(),
                    cli_command: "opencode".to_string(),
                    working_dir: PathBuf::from("/tmp"),
                },
                capabilities: vec![],
                cost_level: CostLevel::Expensive,
                latency: Latency::Medium,
                keywords: vec![],
            },
            model: "opus".to_string(),
            cli_tool: "opencode".to_string(),
            source: RouteSource::KnowledgeGraph,
            confidence: 0.9,
        };

        let score_no_pressure =
            RoutingDecisionEngine::score_candidate(&candidate, BudgetPressure::NoPressure);
        let score_near =
            RoutingDecisionEngine::score_candidate(&candidate, BudgetPressure::NearExhaustion);
        let score_exhausted =
            RoutingDecisionEngine::score_candidate(&candidate, BudgetPressure::Exhausted);

        assert!(score_no_pressure > score_near);
        assert!(score_near > score_exhausted);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_telemetry_penalises_subscription_limited_model() {
        use crate::control_plane::telemetry::{CompletionEvent, TelemetryStore, TokenBreakdown};

        let store = TelemetryStore::new(3600);
        store
            .record(CompletionEvent {
                model: "opencode-go/limited-model".to_string(),
                session_id: "test".to_string(),
                completed_at: chrono::Utc::now(),
                latency_ms: 0,
                success: false,
                tokens: TokenBreakdown::default(),
                cost_usd: 0.0,
                error: Some("weekly session limit reached".to_string()),
            })
            .await;

        let engine = RoutingDecisionEngine::new(
            None,
            Vec::new(),
            terraphim_router::Router::new(),
            Some(Arc::new(store)),
        );

        let ctx =
            create_test_context_with_static_model("agent", "task", "opencode-go/limited-model");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert!(
            decision.telemetry_influenced,
            "telemetry should influence when subscription limited"
        );
        assert!(
            decision.rationale.contains("Telemetry"),
            "rationale should mention telemetry"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn test_telemetry_boosts_high_success_model() {
        use crate::control_plane::telemetry::{CompletionEvent, TelemetryStore, TokenBreakdown};

        let store = TelemetryStore::new(3600);
        // Record 10 successful completions with good latency
        for _ in 0..10 {
            store
                .record(CompletionEvent {
                    model: "opencode-go/fast-model".to_string(),
                    session_id: "test".to_string(),
                    completed_at: chrono::Utc::now(),
                    latency_ms: 200,
                    success: true,
                    tokens: TokenBreakdown {
                        total: 500,
                        input: 400,
                        output: 100,
                        ..Default::default()
                    },
                    cost_usd: 0.005,
                    error: None,
                })
                .await;
        }

        let engine = RoutingDecisionEngine::new(
            None,
            Vec::new(),
            terraphim_router::Router::new(),
            Some(Arc::new(store)),
        );

        let ctx = create_test_context_with_static_model(
            "agent",
            "implement feature",
            "opencode-go/fast-model",
        );
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert!(
            decision.telemetry_influenced,
            "telemetry should influence with high success rate"
        );
        assert!(
            decision.rationale.contains("Telemetry"),
            "rationale should mention telemetry"
        );
    }

    // --- C1/C3 allow-list filter ---

    #[tokio::test]
    async fn test_c3_banned_static_model_falls_back_to_cli_default() {
        // A malformed static model that names a banned provider must not
        // survive routing; the engine falls back to the CLI default.
        let engine = test_engine();
        let ctx = create_test_context_with_static_model(
            "agent-with-bad-static",
            "task",
            "github-copilot/gpt-4.1",
        );
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        assert_eq!(decision.candidate.source, RouteSource::CliDefault);
        assert!(decision.candidate.model.is_empty());
        assert!(
            decision.rationale.contains("C1/C3 allow-list"),
            "rationale should call out the filter: {}",
            decision.rationale
        );
    }

    #[tokio::test]
    async fn test_c3_banned_minimax_prefix_rejected_but_plan_allowed() {
        let engine = test_engine();

        let banned_ctx =
            create_test_context_with_static_model("agent", "task", "minimax/MiniMax-M2.5");
        let banned_decision = engine
            .decide_route(&banned_ctx, &BudgetVerdict::Uncapped)
            .await;
        assert_eq!(banned_decision.candidate.source, RouteSource::CliDefault);

        let allowed_ctx = create_test_context_with_static_model(
            "agent",
            "task",
            "minimax-coding-plan/MiniMax-M2.5",
        );
        let allowed_decision = engine
            .decide_route(&allowed_ctx, &BudgetVerdict::Uncapped)
            .await;
        assert_eq!(allowed_decision.candidate.source, RouteSource::StaticConfig);
        assert_eq!(
            allowed_decision.candidate.model,
            "minimax-coding-plan/MiniMax-M2.5"
        );
    }

    #[tokio::test]
    async fn test_c1_allowed_subscription_prefix_passes() {
        let engine = test_engine();
        let ctx = create_test_context_with_static_model("agent", "task", "kimi-for-coding/k2p5");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;
        assert_eq!(decision.candidate.source, RouteSource::StaticConfig);
        assert_eq!(decision.candidate.model, "kimi-for-coding/k2p5");
    }

    // --- Provider-budget gate ---

    #[tokio::test]
    async fn test_provider_budget_exhausted_drops_candidate() {
        // opencode-go capped at $0.50/hour; push past it and the static
        // candidate must be stripped before scoring, forcing CLI default.
        let tracker =
            ProviderBudgetTracker::new(vec![crate::provider_budget::ProviderBudgetConfig {
                id: "opencode-go".to_string(),
                max_hour_cents: Some(50),
                max_day_cents: None,
                error_signatures: None,
            }]);
        let _ = tracker.record_cost("opencode-go", 1.00);
        let engine = RoutingDecisionEngine::with_provider_budget(
            None,
            Vec::new(),
            terraphim_router::Router::new(),
            None,
            Some(Arc::new(tracker)),
        );
        let ctx =
            create_test_context_with_static_model("agent", "task", "opencode-go/minimax-m2.5");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;
        assert_eq!(decision.candidate.source, RouteSource::CliDefault);
        assert!(
            decision.rationale.contains("provider-budget"),
            "rationale should call out provider-budget: {}",
            decision.rationale
        );
    }

    #[tokio::test]
    async fn test_provider_budget_near_exhaustion_deprioritises() {
        // opencode-go at ~85% (well into the NearExhaustion band) and
        // kimi-for-coding has no cap. Both candidates survive the filter
        // but opencode-go's score is knocked down so the healthier
        // kimi-for-coding wins. Rationale must cite the near-exhaustion.
        let tracker =
            ProviderBudgetTracker::new(vec![crate::provider_budget::ProviderBudgetConfig {
                id: "opencode-go".to_string(),
                max_hour_cents: Some(100),
                max_day_cents: None,
                error_signatures: None,
            }]);
        // Spend $0.85 -> 85% of $1/hr cap -> NearExhaustion.
        let _ = tracker.record_cost("opencode-go", 0.85);
        let engine = RoutingDecisionEngine::with_provider_budget(
            None,
            Vec::new(),
            terraphim_router::Router::new(),
            None,
            Some(Arc::new(tracker)),
        );
        // Static model references opencode-go; confidence 0.8.
        let ctx =
            create_test_context_with_static_model("agent", "task", "opencode-go/minimax-m2.5");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;

        // Near-exhaustion candidate still wins because it's the only
        // signal, but the score must be penalised and the rationale
        // must mention the provider key.
        assert_eq!(decision.candidate.source, RouteSource::StaticConfig);
        assert!(
            decision.budget_influenced,
            "budget_influenced flag should be set"
        );
        assert!(
            decision.rationale.contains("opencode-go"),
            "rationale should name the near-exhausted provider: {}",
            decision.rationale
        );
    }

    #[tokio::test]
    async fn test_provider_budget_uncapped_provider_unaffected() {
        let tracker =
            ProviderBudgetTracker::new(vec![crate::provider_budget::ProviderBudgetConfig {
                id: "opencode-go".to_string(),
                max_hour_cents: Some(100),
                max_day_cents: None,
                error_signatures: None,
            }]);
        // kimi-for-coding has no config entry -> Uncapped -> no effect.
        let engine = RoutingDecisionEngine::with_provider_budget(
            None,
            Vec::new(),
            terraphim_router::Router::new(),
            None,
            Some(Arc::new(tracker)),
        );
        let ctx = create_test_context_with_static_model("agent", "task", "kimi-for-coding/k2p5");
        let decision = engine.decide_route(&ctx, &BudgetVerdict::Uncapped).await;
        assert_eq!(decision.candidate.source, RouteSource::StaticConfig);
        assert_eq!(decision.candidate.model, "kimi-for-coding/k2p5");
        assert!(!decision.budget_influenced);
    }
}