xybrid-core 0.1.0

Core runtime for hybrid cloud-edge AI inference: model execution, pipeline orchestration, and routing primitives.
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
//! Local Orchestration Authority - Fully functional offline implementation.
//!
//! This is the default authority that ships with xybrid. It uses device metrics
//! and heuristics to make decisions locally. No network calls, no phone-home,
//! completely transparent.
//!
//! ## How It Works
//!
//! `LocalAuthority` wraps the existing `PolicyEngine` and `RoutingEngine`:
//!
//! - **Policy evaluation**: Delegates to `DefaultPolicyEngine`
//! - **Target resolution**: Delegates to `DefaultRoutingEngine`, respects explicit targets
//! - **Model selection**: Uses `CacheProvider` to check availability, falls back to registry
//!
//! ## Cache Provider
//!
//! LocalAuthority uses a `CacheProvider` trait to check model availability.
//! This abstraction allows:
//! - Core to check cache without depending on SDK
//! - SDK to inject its own cache implementation at bootstrap time
//! - Custom cache providers for testing or specialized deployments
//!
//! ## Decision Quality
//!
//! Local decisions are deterministic and have high confidence (1.0) because they
//! use only local information. For smarter decisions based on fleet data, use
//! `RemoteAuthority`.

use super::types::*;
use super::OrchestrationAuthority;
use crate::cache_provider::{CacheProvider, FilesystemCacheProvider};
use crate::device::ResourceSnapshotProvider;
use crate::ir::Envelope;
use crate::orchestrator::policy_engine::{DefaultPolicyEngine, PolicyEngine};
use crate::orchestrator::routing_engine::{
    DefaultRoutingEngine, LocalAvailability, LocalReliabilityHint, RouteTarget, RoutingDecision,
    RoutingEngine,
};
use crate::pipeline::ExecutionTarget;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

const DEFAULT_HYSTERESIS_TTL: Duration = Duration::from_secs(30);
const RELIABILITY_WINDOW: usize = 32;
const DEFAULT_HISTORY_BIAS_K: usize = 3;
const MAX_HYSTERESIS_KEYS: usize = 256;
const MAX_RELIABILITY_KEYS: usize = 256;

/// Local orchestration authority - fully functional offline.
///
/// This is the default authority that ships with xybrid.
/// It uses device metrics and heuristics to make decisions locally.
/// No network calls, no phone-home, completely transparent.
///
/// # Example
///
/// ```no_run
/// # fn _example() {
/// use xybrid_core::orchestrator::authority::{LocalAuthority, OrchestrationAuthority, PolicyRequest};
///
/// # let request: PolicyRequest = unimplemented!();
/// let authority = LocalAuthority::new();
/// let decision = authority.apply_policy(&request);
/// println!("Decision: {:?} ({})", decision.result, decision.reason);
/// # }
/// ```
pub struct LocalAuthority {
    policy_engine: DefaultPolicyEngine,
    /// Wrapped in Mutex for interior mutability (RoutingEngine::decide requires &mut self).
    routing_engine: Mutex<DefaultRoutingEngine>,
    /// Cache provider for checking model availability.
    cache_provider: Arc<dyn CacheProvider>,
    /// Optional test seam for live resource snapshots.
    resource_provider: Option<Arc<dyn ResourceSnapshotProvider>>,
    /// Sticky cloud routing after a local abort.
    hysteresis: Mutex<HashMap<(String, AbortReason), Instant>>,
    /// Recent local outcomes for similar device signal buckets.
    reliability: Mutex<HashMap<(String, SignalContext), VecDeque<OutcomeCategory>>>,
    history_bias_k: usize,
}

impl LocalAuthority {
    /// Create a new LocalAuthority with default policy, routing, and cache provider.
    pub fn new() -> Self {
        // Prewarm the static-capability cache. First call to
        // `detect_capabilities()` can take ~1s on macOS/iOS because
        // `MLAllComputeDevices` lazy-loads Core ML. Doing it here keeps
        // that cost out of latency-sensitive routing paths (e.g. the
        // hysteresis check measured in tens of ms).
        crate::device::capabilities::prewarm();
        Self {
            policy_engine: DefaultPolicyEngine::with_default_policy(),
            routing_engine: Mutex::new(DefaultRoutingEngine::new()),
            cache_provider: Arc::new(FilesystemCacheProvider::new()),
            resource_provider: None,
            hysteresis: Mutex::new(HashMap::new()),
            reliability: Mutex::new(HashMap::new()),
            history_bias_k: DEFAULT_HISTORY_BIAS_K,
        }
    }

    /// Create a LocalAuthority with a custom cache provider.
    pub fn with_cache_provider(cache_provider: Arc<dyn CacheProvider>) -> Self {
        crate::device::capabilities::prewarm();
        Self {
            policy_engine: DefaultPolicyEngine::with_default_policy(),
            routing_engine: Mutex::new(DefaultRoutingEngine::new()),
            cache_provider,
            resource_provider: None,
            hysteresis: Mutex::new(HashMap::new()),
            reliability: Mutex::new(HashMap::new()),
            history_bias_k: DEFAULT_HISTORY_BIAS_K,
        }
    }

    /// Create a LocalAuthority with a custom policy engine.
    pub fn with_policy_engine(policy_engine: DefaultPolicyEngine) -> Self {
        crate::device::capabilities::prewarm();
        Self {
            policy_engine,
            routing_engine: Mutex::new(DefaultRoutingEngine::new()),
            cache_provider: Arc::new(FilesystemCacheProvider::new()),
            resource_provider: None,
            hysteresis: Mutex::new(HashMap::new()),
            reliability: Mutex::new(HashMap::new()),
            history_bias_k: DEFAULT_HISTORY_BIAS_K,
        }
    }

    /// Create a LocalAuthority with custom policy engine and cache provider.
    pub fn with_policy_and_cache(
        policy_engine: DefaultPolicyEngine,
        cache_provider: Arc<dyn CacheProvider>,
    ) -> Self {
        crate::device::capabilities::prewarm();
        Self {
            policy_engine,
            routing_engine: Mutex::new(DefaultRoutingEngine::new()),
            cache_provider,
            resource_provider: None,
            hysteresis: Mutex::new(HashMap::new()),
            reliability: Mutex::new(HashMap::new()),
            history_bias_k: DEFAULT_HISTORY_BIAS_K,
        }
    }

    /// Use an injectable resource provider. Intended for tests and embedded
    /// hosts that already own resource sampling.
    pub fn with_resource_provider(mut self, provider: Arc<dyn ResourceSnapshotProvider>) -> Self {
        self.resource_provider = Some(provider);
        self
    }

    /// Override the consecutive unreliable-outcome threshold.
    pub fn with_history_bias_k(mut self, k: usize) -> Self {
        self.history_bias_k = k.max(1);
        self
    }

    /// Mark a model as recently aborted so the next matching route sticks to cloud.
    pub fn record_abort_for_hysteresis(&self, model_id: &str, reason: AbortReason, ttl: Duration) {
        let expires_at = Instant::now() + ttl;
        if let Ok(mut hysteresis) = self.hysteresis.lock() {
            Self::prune_hysteresis(&mut hysteresis);
            hysteresis.insert((model_id.to_string(), reason), expires_at);
            Self::prune_hysteresis(&mut hysteresis);
        }
    }

    pub fn record_abort_for_hysteresis_default_ttl(&self, model_id: &str, reason: AbortReason) {
        self.record_abort_for_hysteresis(model_id, reason, DEFAULT_HYSTERESIS_TTL);
    }

    /// Check if a model exists locally using the cache provider.
    fn check_model_exists(&self, model_id: &str) -> bool {
        self.cache_provider.is_model_cached(model_id)
    }

    /// Find the local path for a model using the cache provider.
    fn find_local_model(&self, model_id: &str) -> Option<String> {
        self.cache_provider
            .get_model_path(model_id)
            .and_then(|p| p.to_str().map(|s| s.to_string()))
    }

    fn active_hysteresis_for(&self, model_id: &str) -> Option<AbortReason> {
        let mut hysteresis = self.hysteresis.lock().ok()?;
        Self::prune_hysteresis(&mut hysteresis);
        // Pick the most recently-recorded reason (max expires_at) when a
        // model has multiple coexisting hysteresis entries. HashMap key
        // iteration order is non-deterministic, so a naive `keys().find_map`
        // would pick StressMemory or StressThermal arbitrarily across
        // process restarts and after map mutations — flaking the
        // explanatory `reason` string surfaced as the platform-event
        // `abort_reason` field. The most recent reason is the one that
        // actually pushed the device over the edge, so it is the more
        // user-meaningful pick.
        hysteresis
            .iter()
            .filter(|((candidate_model_id, _), _)| candidate_model_id == model_id)
            .max_by_key(|(_, expires_at)| **expires_at)
            .map(|((_, reason), _)| *reason)
    }

    fn history_snapshot(&self, model_id: &str, signal: SignalContext) -> VecDeque<OutcomeCategory> {
        self.reliability
            .lock()
            .ok()
            .and_then(|history| history.get(&(model_id.to_string(), signal)).cloned())
            .unwrap_or_default()
    }

    fn reliability_hint(&self, model_id: &str, signal: SignalContext) -> LocalReliabilityHint {
        let history = self.history_snapshot(model_id, signal);
        if history.is_empty() {
            return LocalReliabilityHint::EMPTY;
        }
        let unreliable = history
            .iter()
            .filter(|category| category.is_local_unreliable())
            .count();
        LocalReliabilityHint {
            recent_abort_rate: unreliable as f32 / history.len() as f32,
            sample_size: history.len() as u32,
        }
    }

    fn history_bias_should_skip_local(&self, model_id: &str, signal: SignalContext) -> bool {
        let history = self.history_snapshot(model_id, signal);
        if history.len() < self.history_bias_k {
            return false;
        }
        history
            .iter()
            .rev()
            .take(self.history_bias_k)
            .all(OutcomeCategory::is_local_unreliable)
    }

    fn prune_hysteresis(hysteresis: &mut HashMap<(String, AbortReason), Instant>) {
        let now = Instant::now();
        hysteresis.retain(|_, expires_at| *expires_at > now);
        while hysteresis.len() > MAX_HYSTERESIS_KEYS {
            let Some((key, _)) = hysteresis
                .iter()
                .min_by_key(|(_, expires_at)| **expires_at)
                .map(|(key, expires_at)| (key.clone(), *expires_at))
            else {
                break;
            };
            hysteresis.remove(&key);
        }
    }

    fn prune_reliability(
        reliability: &mut HashMap<(String, SignalContext), VecDeque<OutcomeCategory>>,
    ) {
        // Bounded random-replacement: when at the cap, evict the bucket
        // with the smallest history (least information). Falls back to
        // arbitrary iteration order for empty buckets, which is fine —
        // empty buckets carry no signal anyway. True LRU would require a
        // per-bucket timestamp; the smallest-history heuristic is a
        // reasonable middle ground and is a strict improvement over
        // arbitrary HashMap iteration order, biasing eviction away from
        // hot buckets that have accumulated useful history.
        while reliability.len() > MAX_RELIABILITY_KEYS {
            let Some(victim) = reliability
                .iter()
                .min_by_key(|(_, history)| history.len())
                .map(|(key, _)| key.clone())
            else {
                break;
            };
            reliability.remove(&victim);
        }
    }
}

impl Default for LocalAuthority {
    fn default() -> Self {
        Self::new()
    }
}

impl OrchestrationAuthority for LocalAuthority {
    fn apply_policy(&self, request: &PolicyRequest) -> AuthorityDecision<PolicyOutcome> {
        let result =
            self.policy_engine
                .evaluate(&request.stage_id, &request.envelope, &request.metrics);

        let outcome = if result.allowed {
            if result.transforms_applied.is_empty() {
                PolicyOutcome::Allow
            } else {
                PolicyOutcome::Transform {
                    transforms: result.transforms_applied.clone(),
                }
            }
        } else {
            PolicyOutcome::Deny {
                reason: result
                    .reason
                    .clone()
                    .unwrap_or_else(|| "Policy denied".to_string()),
            }
        };

        let reason = result
            .reason
            .unwrap_or_else(|| "Local policy evaluation".to_string());

        AuthorityDecision {
            result: outcome,
            reason,
            source: DecisionSource::Local,
            confidence: 1.0, // Local decisions are deterministic
            timestamp_ms: now_ms(),
        }
    }

    fn resolve_target(&self, context: &StageContext) -> AuthorityDecision<ResolvedTarget> {
        self.resolve_target_with_feedback(context).decision
    }

    fn resolve_target_with_feedback(&self, context: &StageContext) -> TargetResolution {
        if let Some(resolution) = self.explicit_target_resolution(context) {
            return resolution;
        }

        self.resolve_with_routing_engine(context)
    }

    fn select_model(&self, request: &ModelRequest) -> AuthorityDecision<ModelSelection> {
        // Check if model is available locally
        let local_path = self.find_local_model(&request.model_id);

        let source = if let Some(path) = local_path {
            ModelSource::Local { path }
        } else {
            ModelSource::Registry {
                url: format!("https://api.xybrid.dev/v1/models/{}", request.model_id),
            }
        };

        let is_local = source.is_local();

        AuthorityDecision {
            result: ModelSelection {
                model_id: request.model_id.clone(),
                variant: None,
                source,
            },
            reason: if is_local {
                format!("Model '{}' found locally", request.model_id)
            } else {
                format!(
                    "Model '{}' not found locally, will fetch from registry",
                    request.model_id
                )
            },
            source: DecisionSource::Local,
            confidence: 1.0,
            timestamp_ms: now_ms(),
        }
    }

    fn name(&self) -> &str {
        "local"
    }

    fn record_outcome(&self, outcome: &ExecutionOutcome) {
        if !matches!(outcome.target, ResolvedTarget::Device) {
            return;
        }

        let category = outcome.effective_category();
        let model_id = outcome.effective_model_id().to_string();

        if let OutcomeCategory::AbortedForCloudFallback { reason } = &category {
            self.record_abort_for_hysteresis_default_ttl(&model_id, *reason);
        }

        let Some(signal) = outcome.signal_context else {
            return;
        };
        let key = (model_id, signal);
        if let Ok(mut reliability) = self.reliability.lock() {
            if !reliability.contains_key(&key) && reliability.len() >= MAX_RELIABILITY_KEYS {
                Self::prune_reliability(&mut reliability);
                if reliability.len() >= MAX_RELIABILITY_KEYS {
                    // Use the same smallest-history victim selection as
                    // prune_reliability so eviction stays deterministic
                    // and biased away from hot buckets even on this
                    // last-mile path.
                    let victim = reliability
                        .iter()
                        .min_by_key(|(_, history)| history.len())
                        .map(|(victim_key, _)| victim_key.clone());
                    if let Some(victim) = victim {
                        reliability.remove(&victim);
                    }
                }
            }
            let history = reliability.entry(key).or_default();
            history.push_back(category);
            while history.len() > RELIABILITY_WINDOW {
                history.pop_front();
            }
            Self::prune_reliability(&mut reliability);
        }
    }
}

impl LocalAuthority {
    fn routing_metrics(&self, context: &StageContext) -> crate::context::DeviceMetrics {
        let snapshot = self
            .resource_provider
            .as_ref()
            .map(|provider| provider.current_snapshot(Duration::from_millis(500)))
            .unwrap_or_else(|| {
                context
                    .resource_monitor
                    .current_snapshot(Duration::from_millis(500))
            });
        context.metrics.with_live_snapshot(snapshot)
    }

    fn target_from_route(target: RouteTarget) -> ResolvedTarget {
        match target {
            RouteTarget::Local => ResolvedTarget::Device,
            RouteTarget::Cloud => ResolvedTarget::Cloud {
                provider: "xybrid".to_string(),
            },
            // Carry the bare fallback id; the reverse-direction
            // mapping in resolve_routing_decision (and
            // Orchestrator::resolved_target_to_routing_decision) will
            // re-wrap it as RouteTarget::Fallback. The "fallback:"
            // prefix is added back by RouteTarget::to_json_string /
            // Display, so synthesizing it here produced "fallback:fallback:<id>"
            // when the resolution round-tripped through telemetry.
            RouteTarget::Fallback(id) => ResolvedTarget::Server { endpoint: id },
        }
    }

    fn explicit_target_resolution(&self, context: &StageContext) -> Option<TargetResolution> {
        let explicit = context.explicit_target.as_ref()?;
        let target = match explicit {
            ExecutionTarget::Device => ResolvedTarget::Device,
            ExecutionTarget::Server => ResolvedTarget::Server {
                endpoint: "https://api.xybrid.dev".to_string(),
            },
            ExecutionTarget::Cloud => ResolvedTarget::Cloud {
                provider: "xybrid".to_string(),
            },
            ExecutionTarget::Auto => return None,
        };

        let metrics = self.routing_metrics(context);
        Some(TargetResolution::new(
            AuthorityDecision {
                result: target,
                reason: format!("Explicit target from pipeline YAML: {:?}", explicit),
                source: DecisionSource::Local,
                confidence: 1.0,
                timestamp_ms: now_ms(),
            },
            context.model_id.clone(),
            Some(SignalContext::from_metrics(&metrics)),
        ))
    }

    /// Internal: resolve target using the routing engine.
    fn resolve_with_routing_engine(&self, context: &StageContext) -> TargetResolution {
        let availability = context
            .local_availability
            .clone()
            .unwrap_or_else(|| LocalAvailability::new(self.check_model_exists(&context.model_id)));
        self.resolve_with_routing_engine_and_availability(context, availability)
    }

    fn resolve_with_routing_engine_and_availability(
        &self,
        context: &StageContext,
        availability: LocalAvailability,
    ) -> TargetResolution {
        // Create a minimal envelope for policy check
        let envelope = Envelope::new(context.input_kind.clone());
        let live_metrics = self.routing_metrics(context);
        let signal = SignalContext::from_metrics(&live_metrics);
        let hint = self.reliability_hint(&context.model_id, signal);

        let policy_result =
            self.policy_engine
                .evaluate(&context.stage_id, &envelope, &live_metrics);

        if policy_result.allowed {
            if let Some(reason) = self.active_hysteresis_for(&context.model_id) {
                let decision = AuthorityDecision {
                    result: ResolvedTarget::Cloud {
                        provider: "xybrid".to_string(),
                    },
                    reason: format!(
                        "hysteresis: recent local abort for model '{}' ({})",
                        context.model_id, reason
                    ),
                    source: DecisionSource::Local,
                    confidence: 0.9,
                    timestamp_ms: now_ms(),
                };
                return TargetResolution::new(decision, context.model_id.clone(), Some(signal))
                    .with_reliability_hint(hint);
            }

            if self.history_bias_should_skip_local(&context.model_id, signal) {
                let decision = AuthorityDecision {
                    result: ResolvedTarget::Cloud {
                        provider: "xybrid".to_string(),
                    },
                    reason: format!(
                        "history_bias: recent local failure rate {:.0}% over {} samples",
                        hint.recent_abort_rate * 100.0,
                        hint.sample_size
                    ),
                    source: DecisionSource::Local,
                    confidence: 0.85,
                    timestamp_ms: now_ms(),
                };
                return TargetResolution::new(decision, context.model_id.clone(), Some(signal))
                    .with_reliability_hint(hint);
            }
        }

        // Use the stored routing engine (locked for interior mutability)
        let decision = {
            let mut routing_engine = self.routing_engine.lock().unwrap();
            routing_engine.decide(
                &context.stage_id,
                &live_metrics,
                &policy_result,
                &availability,
            )
        };

        let target = Self::target_from_route(decision.target);
        TargetResolution::new(
            AuthorityDecision {
                result: target,
                reason: decision.reason,
                source: DecisionSource::Local,
                confidence: 0.8, // Heuristic-based, slightly lower confidence
                timestamp_ms: decision.timestamp_ms,
            },
            context.model_id.clone(),
            Some(signal),
        )
        .with_reliability_hint(hint)
    }

    /// Resolve into the routing-engine decision shape for tests and telemetry adapters.
    pub fn resolve_routing_decision(&self, context: &StageContext) -> Option<RoutingDecision> {
        let resolution = self.resolve_target_with_feedback(context);
        let target = match resolution.decision.result {
            ResolvedTarget::Device => RouteTarget::Local,
            ResolvedTarget::Cloud { .. } => RouteTarget::Cloud,
            ResolvedTarget::Server { endpoint } => RouteTarget::Fallback(endpoint),
        };
        Some(RoutingDecision {
            stage: context.stage_id.clone(),
            target,
            reason: resolution.decision.reason,
            timestamp_ms: resolution.decision.timestamp_ms,
            local_reliability_hint: resolution
                .local_reliability_hint
                .unwrap_or(LocalReliabilityHint::EMPTY),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache_provider::CacheProvider;
    use crate::context::DeviceMetrics;
    use crate::device::{MemoryPressure, ResourceMonitor, ResourceSnapshot, ThermalState};
    use crate::ir::EnvelopeKind;
    use std::path::PathBuf;

    fn default_metrics() -> DeviceMetrics {
        DeviceMetrics::default()
    }

    /// YAML policy bundle that denies any text envelope. Used to exercise the
    /// `policy_deny` branch in tests now that the legacy RTT-based default
    /// rule is gone.
    fn deny_all_text_policy() -> String {
        r#"
version: "0.1.0"
deny_cloud_if:
  - input.kind == "text"
signature: "test-deny-all"
"#
        .to_string()
    }

    fn text_envelope(text: &str) -> Envelope {
        Envelope::new(EnvelopeKind::Text(text.to_string()))
    }

    #[derive(Debug)]
    struct FixedResourceProvider(ResourceSnapshot);

    impl ResourceSnapshotProvider for FixedResourceProvider {
        fn current_snapshot(&self, _max_age: Duration) -> ResourceSnapshot {
            self.0
        }
    }

    #[derive(Debug)]
    struct CachedProvider;

    impl CacheProvider for CachedProvider {
        fn is_model_cached(&self, _model_id: &str) -> bool {
            true
        }

        fn get_model_path(&self, model_id: &str) -> Option<PathBuf> {
            Some(PathBuf::from(format!("/tmp/{model_id}")))
        }

        fn cache_dir(&self) -> PathBuf {
            PathBuf::from("/tmp")
        }

        fn name(&self) -> &'static str {
            "cached-test"
        }
    }

    fn text_context() -> StageContext {
        StageContext {
            stage_id: "test-stage".to_string(),
            model_id: "test-model".to_string(),
            input_kind: EnvelopeKind::Text("test".to_string()),
            metrics: default_metrics(),
            resource_monitor: ResourceMonitor::global(),
            explicit_target: None,
            local_availability: None,
            device_class: None,
            device_class_schema_version: None,
        }
    }

    fn signal() -> SignalContext {
        SignalContext {
            memory_pressure: MemoryPressure::Warn,
            thermal_state: ThermalState::Normal,
            cpu_bucket: Some(5),
        }
    }

    #[test]
    fn test_local_authority_default_allows() {
        let authority = LocalAuthority::new();
        let request = PolicyRequest {
            stage_id: "test".to_string(),
            envelope: text_envelope("hello"),
            metrics: default_metrics(),
        };

        let decision = authority.apply_policy(&request);
        assert!(decision.result.is_allowed());
        assert_eq!(decision.source, DecisionSource::Local);
        assert_eq!(decision.confidence, 1.0);
    }

    #[test]
    fn test_local_authority_explicit_device_target() {
        let authority = LocalAuthority::new();
        let context = StageContext {
            stage_id: "test".to_string(),
            model_id: "test-model".to_string(),
            input_kind: EnvelopeKind::Text("test".to_string()),
            metrics: default_metrics(),
            resource_monitor: ResourceMonitor::global(),
            explicit_target: Some(ExecutionTarget::Device),
            local_availability: None,
            device_class: None,
            device_class_schema_version: None,
        };

        let decision = authority.resolve_target(&context);
        assert_eq!(decision.result, ResolvedTarget::Device);
        assert!(decision.reason.contains("Explicit"));
    }

    #[test]
    fn test_local_authority_explicit_cloud_target() {
        let authority = LocalAuthority::new();
        let context = StageContext {
            stage_id: "test".to_string(),
            model_id: "test-model".to_string(),
            input_kind: EnvelopeKind::Text("test".to_string()),
            metrics: default_metrics(),
            resource_monitor: ResourceMonitor::global(),
            explicit_target: Some(ExecutionTarget::Cloud),
            local_availability: None,
            device_class: None,
            device_class_schema_version: None,
        };

        let decision = authority.resolve_target(&context);
        assert!(matches!(decision.result, ResolvedTarget::Cloud { .. }));
    }

    #[test]
    fn caller_local_availability_overrides_cache_provider() {
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        let mut context = text_context();
        context.local_availability = Some(LocalAvailability::new(false));

        let decision = authority.resolve_target(&context);

        assert!(matches!(decision.result, ResolvedTarget::Cloud { .. }));
        assert!(decision.reason.contains("model_unavailable"));
    }

    #[test]
    fn test_local_authority_model_selection_not_found() {
        let authority = LocalAuthority::new();
        let request = ModelRequest {
            model_id: "nonexistent-model-xyz".to_string(),
            task: "test".to_string(),
            constraints: ModelConstraints::default(),
        };

        let decision = authority.select_model(&request);
        assert!(matches!(
            decision.result.source,
            ModelSource::Registry { .. }
        ));
        assert!(decision.reason.contains("not found locally"));
    }

    #[test]
    fn test_local_authority_name() {
        let authority = LocalAuthority::new();
        assert_eq!(authority.name(), "local");
    }

    #[test]
    fn test_find_local_model_sdk_cache_structure() {
        // This test verifies that the model matching logic can find models
        // in the SDK cache even when directory names don't exactly match.
        // E.g., "kokoro-82m" should match "Kokoro-82M-v1.0-ONNX"

        // Check if a model matching "kokoro-82m" exists in the cache
        // (this depends on the user having run the model before)
        let authority = LocalAuthority::new();
        let path = authority.find_local_model("kokoro-82m");

        // If the model is cached, verify it's the right one
        if let Some(p) = &path {
            let p_lower = p.to_lowercase();
            assert!(
                p_lower.contains("kokoro"),
                "Expected path to contain 'kokoro', got: {}",
                p
            );
        }
        // Note: If no model is cached, the test just passes (we can't require cached models in CI)
    }

    #[test]
    fn test_with_custom_cache_provider() {
        use crate::cache_provider::NoopCacheProvider;

        // Test that we can create authority with a custom cache provider
        let provider = Arc::new(NoopCacheProvider);
        let authority = LocalAuthority::with_cache_provider(provider);

        // Model should not be found with noop provider
        let request = ModelRequest {
            model_id: "any-model".to_string(),
            task: "test".to_string(),
            constraints: ModelConstraints::default(),
        };

        let decision = authority.select_model(&request);
        assert!(matches!(
            decision.result.source,
            ModelSource::Registry { .. }
        ));
    }

    #[test]
    fn fake_resource_provider_feeds_routing_metrics() {
        let mut snapshot = ResourceSnapshot::unknown();
        snapshot.memory_pressure = MemoryPressure::Critical;
        snapshot.thermal_state = ThermalState::Normal;
        snapshot.cpu_pct = Some(10.0);
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider))
            .with_resource_provider(Arc::new(FixedResourceProvider(snapshot)));

        let decision = authority.resolve_target(&text_context());

        assert!(matches!(decision.result, ResolvedTarget::Cloud { .. }));
        assert!(decision.reason.contains("stress_memory"));
    }

    #[test]
    fn hysteresis_is_model_scoped_and_expires() {
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        authority.record_abort_for_hysteresis(
            "test-model",
            AbortReason::StressMemory,
            Duration::from_millis(20),
        );

        let decision = authority.resolve_target(&text_context());
        assert!(matches!(decision.result, ResolvedTarget::Cloud { .. }));
        assert!(decision.reason.contains("hysteresis"));

        let mut other = text_context();
        other.model_id = "other-model".to_string();
        let other_decision = authority.resolve_target(&other);
        assert!(!other_decision.reason.contains("hysteresis"));

        std::thread::sleep(Duration::from_millis(30));
        let expired = authority.resolve_target(&text_context());
        assert!(!expired.reason.contains("hysteresis"));
    }

    #[test]
    fn policy_deny_overrides_hysteresis() {
        let mut policy = DefaultPolicyEngine::new();
        policy
            .load_policies(deny_all_text_policy().into_bytes())
            .expect("load deny-all policy");
        let authority = LocalAuthority::with_policy_and_cache(policy, Arc::new(CachedProvider));
        authority.record_abort_for_hysteresis_default_ttl("test-model", AbortReason::StressMemory);

        let decision = authority.resolve_target(&text_context());

        assert_eq!(decision.result, ResolvedTarget::Device);
        assert!(decision.reason.contains("policy_deny"));
    }

    #[test]
    fn device_abort_outcome_enters_hysteresis() {
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        authority.record_outcome(&ExecutionOutcome {
            stage_id: "test-stage".to_string(),
            target: ResolvedTarget::Device,
            latency_ms: 12,
            success: false,
            error: None,
            category: Some(OutcomeCategory::AbortedForCloudFallback {
                reason: AbortReason::StressMemory,
            }),
            model_id: Some("test-model".to_string()),
            signal_context: Some(signal()),
        });

        let decision = authority.resolve_target(&text_context());

        assert!(matches!(decision.result, ResolvedTarget::Cloud { .. }));
        assert!(decision.reason.contains("hysteresis"));
    }

    #[test]
    fn cloud_failures_do_not_bias_local_reliability() {
        let authority =
            LocalAuthority::with_cache_provider(Arc::new(CachedProvider)).with_history_bias_k(3);
        for idx in 0..3 {
            authority.record_outcome(&ExecutionOutcome {
                stage_id: "test-stage".to_string(),
                target: ResolvedTarget::Cloud {
                    provider: "xybrid".to_string(),
                },
                latency_ms: 10,
                success: false,
                error: Some(format!("cloud-failure-{idx}")),
                category: Some(OutcomeCategory::HardFail {
                    reason: "cloud_failed".to_string(),
                }),
                model_id: Some("test-model".to_string()),
                signal_context: Some(signal()),
            });
        }

        let mut snapshot = ResourceSnapshot::unknown();
        snapshot.memory_pressure = MemoryPressure::Warn;
        snapshot.thermal_state = ThermalState::Normal;
        snapshot.cpu_pct = Some(55.0);
        let authority = authority.with_resource_provider(Arc::new(FixedResourceProvider(snapshot)));

        let decision = authority
            .resolve_routing_decision(&text_context())
            .expect("routing decision");

        assert!(!decision.reason.contains("history_bias"));
        assert_eq!(decision.local_reliability_hint.sample_size, 0);
    }

    #[test]
    fn policy_deny_overrides_history_bias() {
        let mut policy = DefaultPolicyEngine::new();
        policy
            .load_policies(deny_all_text_policy().into_bytes())
            .expect("load deny-all policy");
        let authority = LocalAuthority::with_policy_and_cache(policy, Arc::new(CachedProvider))
            .with_history_bias_k(3);
        for idx in 0..3 {
            authority.record_outcome(&ExecutionOutcome {
                stage_id: "test-stage".to_string(),
                target: ResolvedTarget::Device,
                latency_ms: 10,
                success: false,
                error: Some(format!("failure-{idx}")),
                category: Some(OutcomeCategory::HardFail {
                    reason: "local_failed".to_string(),
                }),
                model_id: Some("test-model".to_string()),
                signal_context: Some(signal()),
            });
        }

        let decision = authority.resolve_target(&text_context());

        assert_eq!(decision.result, ResolvedTarget::Device);
        assert!(decision.reason.contains("policy_deny"));
    }

    #[test]
    fn hysteresis_map_stays_bounded() {
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        for idx in 0..(MAX_HYSTERESIS_KEYS + 32) {
            authority.record_abort_for_hysteresis_default_ttl(
                &format!("model-{idx}"),
                AbortReason::StressMemory,
            );
        }

        assert!(
            authority.hysteresis.lock().unwrap().len() <= MAX_HYSTERESIS_KEYS,
            "hysteresis should stay bounded"
        );
    }

    #[test]
    fn reliability_map_stays_bounded() {
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        for idx in 0..(MAX_RELIABILITY_KEYS + 32) {
            authority.record_outcome(&ExecutionOutcome {
                stage_id: "test-stage".to_string(),
                target: ResolvedTarget::Device,
                latency_ms: 10,
                success: false,
                error: Some("local_failed".to_string()),
                category: Some(OutcomeCategory::HardFail {
                    reason: "local_failed".to_string(),
                }),
                model_id: Some(format!("model-{idx}")),
                signal_context: Some(signal()),
            });
        }

        assert!(
            authority.reliability.lock().unwrap().len() <= MAX_RELIABILITY_KEYS,
            "reliability should stay bounded"
        );
    }

    #[test]
    fn reliability_window_evicts_oldest_after_32_entries() {
        // Pin the exact retained FIFO sequence: writing failure-0..32 must
        // leave failure-1..32 in oldest-to-newest order. Asserting length
        // alone (or just the absence of failure-0) would silently accept
        // reversed eviction, duplicate retention, or stable-non-FIFO bugs.
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        for idx in 0..33 {
            authority.record_outcome(&ExecutionOutcome {
                stage_id: "test-stage".to_string(),
                target: ResolvedTarget::Device,
                latency_ms: 10,
                success: false,
                error: Some(format!("failure-{idx}")),
                category: Some(OutcomeCategory::HardFail {
                    reason: format!("failure-{idx}"),
                }),
                model_id: Some("test-model".to_string()),
                signal_context: Some(signal()),
            });
        }

        let history = authority.history_snapshot("test-model", signal());

        assert_eq!(history.len(), RELIABILITY_WINDOW);
        let actual_reasons: Vec<String> = history
            .iter()
            .map(|c| match c {
                OutcomeCategory::HardFail { reason } => reason.clone(),
                other => panic!("expected HardFail, got {other:?}"),
            })
            .collect();
        let expected_reasons: Vec<String> = (1..=RELIABILITY_WINDOW)
            .map(|i| format!("failure-{i}"))
            .collect();
        assert_eq!(
            actual_reasons, expected_reasons,
            "history must contain failure-1..failure-{RELIABILITY_WINDOW} in FIFO order (oldest first)"
        );
    }

    // Helper: record one HardFail under `(model, sig)` and return the
    // resulting snapshot. Keeps the per-dimension isolation tests compact.
    fn record_hard_fail_and_snapshot(
        authority: &LocalAuthority,
        model: &str,
        sig: SignalContext,
        reason: &str,
    ) -> std::collections::VecDeque<OutcomeCategory> {
        authority.record_outcome(&ExecutionOutcome {
            stage_id: "test-stage".to_string(),
            target: ResolvedTarget::Device,
            latency_ms: 10,
            success: false,
            error: Some(reason.to_string()),
            category: Some(OutcomeCategory::HardFail {
                reason: reason.to_string(),
            }),
            model_id: Some(model.to_string()),
            signal_context: Some(sig),
        });
        authority.history_snapshot(model, sig)
    }

    #[test]
    fn reliability_history_is_scoped_by_memory_pressure() {
        // Memory-pressure isolation: same (model, thermal, cpu_bucket) but
        // different memory_pressure must keep histories separate.
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        let mut warn_signal = signal();
        warn_signal.memory_pressure = MemoryPressure::Warn;
        let mut critical_signal = signal();
        critical_signal.memory_pressure = MemoryPressure::Critical;

        let warn_history =
            record_hard_fail_and_snapshot(&authority, "test-model", warn_signal, "warn-failure");
        let critical_history = record_hard_fail_and_snapshot(
            &authority,
            "test-model",
            critical_signal,
            "critical-failure",
        );

        assert_eq!(warn_history.len(), 1);
        assert_eq!(critical_history.len(), 1);
        assert_ne!(warn_history, critical_history);
    }

    #[test]
    fn reliability_history_is_scoped_by_thermal_state() {
        // Thermal-state isolation: same (model, memory_pressure, cpu_bucket)
        // but different thermal_state must keep histories separate. Without
        // this, a `Normal` device's hot history would leak into a `Hot`
        // device's bias decision.
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        let mut normal_signal = signal();
        normal_signal.thermal_state = ThermalState::Normal;
        let mut hot_signal = signal();
        hot_signal.thermal_state = ThermalState::Hot;

        let normal_history =
            record_hard_fail_and_snapshot(&authority, "test-model", normal_signal, "normal-fail");
        let hot_history =
            record_hard_fail_and_snapshot(&authority, "test-model", hot_signal, "hot-fail");

        assert_eq!(normal_history.len(), 1);
        assert_eq!(hot_history.len(), 1);
        assert_ne!(normal_history, hot_history);
    }

    #[test]
    fn reliability_history_is_scoped_by_cpu_bucket() {
        // cpu_bucket isolation: same (model, memory, thermal) but different
        // quantized CPU bucket must keep histories separate. The bucket is
        // the only continuous dimension in SignalContext, so a coarse
        // quantization regression would manifest here.
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));
        let mut low_cpu_signal = signal();
        low_cpu_signal.cpu_bucket = Some(2);
        let mut high_cpu_signal = signal();
        high_cpu_signal.cpu_bucket = Some(9);

        let low_history =
            record_hard_fail_and_snapshot(&authority, "test-model", low_cpu_signal, "low-cpu-fail");
        let high_history = record_hard_fail_and_snapshot(
            &authority,
            "test-model",
            high_cpu_signal,
            "high-cpu-fail",
        );

        assert_eq!(low_history.len(), 1);
        assert_eq!(high_history.len(), 1);
        assert_ne!(low_history, high_history);
    }

    #[test]
    fn reliability_history_is_scoped_by_model_id() {
        // model_id isolation: identical SignalContext but different model
        // IDs must keep histories separate. If the key ever collapsed to
        // SignalContext alone, this would conflate per-model reliability.
        let authority = LocalAuthority::with_cache_provider(Arc::new(CachedProvider));

        let history_a = record_hard_fail_and_snapshot(&authority, "model-a", signal(), "a-fail");
        let history_b = record_hard_fail_and_snapshot(&authority, "model-b", signal(), "b-fail");

        assert_eq!(history_a.len(), 1);
        assert_eq!(history_b.len(), 1);
        assert_ne!(history_a, history_b);
    }

    #[test]
    fn reliability_history_bias_routes_cloud_with_hint() {
        let authority =
            LocalAuthority::with_cache_provider(Arc::new(CachedProvider)).with_history_bias_k(3);
        for idx in 0..3 {
            authority.record_outcome(&ExecutionOutcome {
                stage_id: "test-stage".to_string(),
                target: ResolvedTarget::Device,
                latency_ms: 10,
                success: false,
                error: Some(format!("failure-{idx}")),
                category: Some(OutcomeCategory::HardFail {
                    reason: "local_failed".to_string(),
                }),
                model_id: Some("test-model".to_string()),
                signal_context: Some(signal()),
            });
        }

        let mut snapshot = ResourceSnapshot::unknown();
        snapshot.memory_pressure = MemoryPressure::Warn;
        snapshot.thermal_state = ThermalState::Normal;
        snapshot.cpu_pct = Some(55.0);
        let authority = authority.with_resource_provider(Arc::new(FixedResourceProvider(snapshot)));

        let decision = authority
            .resolve_routing_decision(&text_context())
            .expect("routing decision");

        assert_eq!(decision.target, RouteTarget::Cloud);
        assert!(decision.reason.contains("history_bias"));
        assert_eq!(decision.local_reliability_hint.sample_size, 3);
        assert_eq!(decision.local_reliability_hint.recent_abort_rate, 1.0);
    }

    #[test]
    fn success_reduces_history_bias() {
        let authority =
            LocalAuthority::with_cache_provider(Arc::new(CachedProvider)).with_history_bias_k(3);
        for category in [
            OutcomeCategory::HardFail {
                reason: "a".to_string(),
            },
            OutcomeCategory::HardFail {
                reason: "b".to_string(),
            },
            OutcomeCategory::Success,
        ] {
            authority.record_outcome(&ExecutionOutcome {
                stage_id: "test-stage".to_string(),
                target: ResolvedTarget::Device,
                latency_ms: 10,
                success: matches!(category, OutcomeCategory::Success),
                error: None,
                category: Some(category),
                model_id: Some("test-model".to_string()),
                signal_context: Some(signal()),
            });
        }

        let mut snapshot = ResourceSnapshot::unknown();
        snapshot.memory_pressure = MemoryPressure::Warn;
        snapshot.thermal_state = ThermalState::Normal;
        snapshot.cpu_pct = Some(55.0);
        let authority = authority.with_resource_provider(Arc::new(FixedResourceProvider(snapshot)));
        let decision = authority.resolve_target(&text_context());

        assert!(!decision.reason.contains("history_bias"));
    }

    #[test]
    fn target_from_route_round_trips_fallback_without_prefix_doubling() {
        // Pre-fix, target_from_route synthesized "fallback:<id>" inside the
        // ResolvedTarget::Server endpoint string. The reverse mapping then
        // wrapped the already-prefixed string in RouteTarget::Fallback, and
        // to_json_string re-prepended "fallback:" — emitting
        // "fallback:fallback:<id>". Ensure the symmetric round-trip now
        // produces a single prefix.
        let routed =
            LocalAuthority::target_from_route(RouteTarget::Fallback("model_v2".to_string()));
        let endpoint = match routed {
            ResolvedTarget::Server { endpoint } => endpoint,
            other => panic!("expected Server target, got {other:?}"),
        };
        assert_eq!(endpoint, "model_v2");
        let reverse = match endpoint.as_str() {
            "model_v2" => RouteTarget::Fallback(endpoint.clone()),
            _ => unreachable!(),
        };
        assert_eq!(reverse.to_json_string(), "fallback:model_v2");
        assert_eq!(reverse.to_string(), "fallback:model_v2");
    }

    #[test]
    fn test_model_matching_logic() {
        // Test the matching logic directly without relying on filesystem state
        let test_cases = [
            ("kokoro-82m", "kokoro-82m-v1.0-onnx"), // exact hyphenated
            ("kokoro-82m", "kokoro82mv10onnx"),     // normalized
            ("whisper-tiny", "whisper-tiny"),       // exact match
        ];

        for (query, dir_name) in test_cases {
            let query_lower = query.to_lowercase();
            let query_normalized = query_lower.replace("-", "").replace("_", "");
            let dir_name_lower = dir_name.to_lowercase();
            let dir_name_normalized = dir_name_lower.replace("-", "").replace("_", "");

            let is_match = dir_name_lower.contains(&query_lower)
                || dir_name_normalized.contains(&query_normalized);

            assert!(
                is_match,
                "Expected '{}' to match '{}' but it didn't",
                query, dir_name
            );
        }
    }
}