orch-cli 0.88.4

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
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
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
//! Router configuration — loading, defaults, and model map.

use std::collections::HashMap;

/// Minimum healthy agents threshold for graceful degradation.
/// When healthy agents fall below this number, dispatch switches to sequential mode.
pub fn min_healthy_agents_threshold() -> usize {
    crate::config::get("dispatch.min_healthy_agents")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(2)
}

/// Base delay in milliseconds between dispatches in sequential (degraded) mode.
pub fn sequential_dispatch_delay_ms() -> u64 {
    crate::config::get("dispatch.sequential_delay_ms")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(1000)
}

/// Lookback window (in hours) for the pre-emptive agent health check.
///
/// The health check queries `rate_limits` for events within this window.
/// Configurable via `dispatch.health_check_window_hours` (default: 6).
pub fn health_check_window_hours() -> u32 {
    crate::config::get("dispatch.health_check_window_hours")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(crate::engine::cooldown::DEFAULT_HEALTH_CHECK_WINDOW_HOURS)
}

/// Minimum number of rate-limit events within the health check window to
/// consider an agent degraded.
///
/// A single transient 429 error shouldn't mark an agent degraded; we need
/// a pattern of repeated failures to detect genuine degradation. This
/// threshold is compared against the count of rate_limit events in the
/// `rate_limits` table within the health check window.
///
/// IMPORTANT: An agent with `rate_limit_count == 0` is NOT degraded by this
/// criterion — it must meet or exceed the threshold. The threshold should
/// be set to a value >= 2 to avoid false positives when there are no events.
///
/// Configurable via `dispatch.degraded_rate_limit_threshold` (default: 3).
pub fn degraded_rate_limit_threshold() -> i64 {
    crate::config::get("dispatch.degraded_rate_limit_threshold")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(crate::engine::cooldown::DEFAULT_DEGRADED_RATE_LIMIT_THRESHOLD)
}

/// Base delay in milliseconds for exponential backoff between fallback retries.
pub fn retry_base_delay_ms() -> u64 {
    crate::config::get("dispatch.retry_base_delay_ms")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(10_000)
}

/// Maximum delay in milliseconds for exponential backoff between fallback retries.
pub fn retry_max_delay_ms() -> u64 {
    crate::config::get("dispatch.retry_max_delay_ms")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(120_000)
}

/// Upper bound for router LLM timeout (seconds).
///
/// Routing is a short classification step and should fail fast so a single
/// slow model does not stall fallback to other healthy agents.
pub const MAX_ROUTER_TIMEOUT_SECS: u64 = 45;

/// Return the configured base backoff (seconds) for an agent.
///
/// Returns the value of `router.backoff_base.{agent}` if set, otherwise
/// the default BACKOFF_BASE_SECS (5 minutes).
///
/// This lets opencode and other higher-failure-rate agents use a longer
/// initial backoff to reduce wasted retry attempts against consistently
/// failing models.
pub fn get_agent_backoff_base(agent: &str) -> i64 {
    let key = format!("router.backoff_base.{agent}");
    crate::config::get(&key)
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(crate::engine::cooldown::BACKOFF_BASE_SECS)
}

/// Maximum number of tasks to route per tick. Prevents blocking the tick loop
/// when multiple tasks are queued simultaneously (e.g., cron jobs). Each routing
/// operation involves an LLM call taking 10-45 seconds, so routing N tasks
/// sequentially would block for N×LLM-latency seconds.
///
/// Configurable via `router.max_tasks_per_tick` (default: 1).
pub fn max_tasks_per_routing_tick() -> usize {
    crate::config::get("router.max_tasks_per_tick")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(1)
}

/// Default agents to check in PATH.
///
/// All 7 agents are listed, but availability is checked at runtime via
/// `which::which()`. Agents not installed (e.g. kimi, minimax, glm) are
/// automatically skipped during routing. Users can customize this list
/// in their `config.yml` under `agents:`.
pub const DEFAULT_AGENTS: &[&str] = &[
    "claude", "codex", "opencode", "kimi", "minimax", "glm", "grok",
];

/// Router configuration.
#[derive(Debug, Clone)]
pub struct RouterConfig {
    /// Routing mode: "llm", "local", or "round_robin"
    ///
    /// - "llm": Use cloud LLMs for routing (default, supports pool-based routing)
    /// - "local": Use local Ollama model for routing
    /// - "round_robin": Distribute tasks evenly across available agents
    pub mode: String,
    /// Which agent performs routing (default: "claude")
    pub router_agent: String,
    /// Model for routing (default: "haiku")
    pub router_model: String,
    /// Timeout for routing LLM call in seconds
    pub timeout_seconds: u64,
    /// Fallback executor if routing fails
    pub fallback_executor: String,
    /// Configurable agent list (checked against PATH at runtime)
    pub agents: Vec<String>,
    /// Max LLM routing attempts before falling back to round-robin
    pub max_route_attempts: u32,
    /// Default tools allowed
    pub allowed_tools: Vec<String>,
    /// Default skills to always include
    pub default_skills: Vec<String>,
    /// Model map for complexity levels.
    /// Each entry is a pool of models; one is selected randomly (skipping cooled ones) per dispatch.
    /// A single-model pool `vec!["model"]` behaves identically to the old string format.
    pub model_map: HashMap<String, HashMap<String, Vec<String>>>,
    /// Enable weighted round-robin routing based on rate limit capacity.
    /// When true, agents that hit rate limits get fewer tasks.
    pub weighted_round_robin: bool,
    /// Pool of `agent:model` entries to round-robin the router LLM call.
    /// When empty, a single-entry pool is derived from `router_agent:router_model`.
    /// Special value `opencode:free` is expanded at startup via `opencode models`.
    pub pool: Vec<String>,
    /// Fallback `agent:model` when all pool entries are cooled or fail.
    /// When empty, defaults to `router_agent:router_model`.
    pub fallback: String,
    /// Penalty weight applied when the LLM routes a task to itself (the routing agent).
    ///
    /// Range: `0.0` (always redirect away from router agent) to `1.0` (no penalty, default).
    /// When `< 1.0` and the LLM selects its own agent, the router probabilistically
    /// redirects to another available agent, reducing self-routing bias.
    ///
    /// Example: `0.5` means ~50% of self-routed tasks are redirected to another agent.
    pub self_routing_penalty: f64,
    /// Configurable base weights per agent.
    ///
    /// Higher weight = more tasks routed to this agent. Agents without an explicit
    /// weight default to 1.0. The weighted selection normalizes these into
    /// probabilities, so `{claude: 0.6, minimax: 0.03}` means claude gets ~95%
    /// of tasks when both are available.
    ///
    /// Set in `config.yml` under `router.weights`:
    /// ```yaml
    /// router:
    ///   weights:
    ///     claude: 0.6
    ///     codex: 0.2
    ///     opencode: 0.15
    ///     minimax: 0.03
    ///     kimi: 0.02
    /// ```
    pub weights: HashMap<String, f64>,
    /// If an agent's routing weight falls below this threshold, consider it
    /// degraded and skip it during proactive routing decisions. Value in
    /// `0.0..=1.0` where `1.0` means never skip and `0.0` skips only when
    /// weight is exactly zero (practically never). Default: `0.3`.
    pub skip_limited_threshold: f64,
    /// Per-agent base backoff overrides (seconds). Agents not listed use the
    /// default BACKOFF_BASE_SECS (5 minutes). Configure as `router.backoff_base.{agent}`.
    ///
    /// Example: set `router.backoff_base.opencode: 600` for a 10-minute base
    /// instead of the default 5-minute base (useful for agents with higher
    /// failure rates like opencode at 24.8%).
    pub agent_backoff_bases: HashMap<String, i64>,
    /// Maximum number of tasks to route per tick. Prevents blocking the tick loop
    /// when multiple tasks are queued simultaneously (e.g., cron jobs). Each routing
    /// operation involves an LLM call taking 10-45 seconds, so routing N tasks
    /// sequentially would block for N×LLM-latency seconds.
    ///
    /// Configurable via `router.max_tasks_per_tick` (default: 1).
    pub max_tasks_per_tick: usize,
    /// Ollama base URL for local routing (default: "http://localhost:11434").
    pub ollama_url: String,
    /// Ollama model name for routing (default: "qwen2.5-coder:3b-instruct").
    pub ollama_model: String,
    /// Timeout for Ollama HTTP call in seconds (default: 30).
    pub ollama_timeout_seconds: u64,
}

/// Parse an `agent:model` pool entry string, splitting on the first colon.
///
/// Examples:
/// - `"claude:haiku"` → `("claude", "haiku")`
/// - `"opencode:github-copilot/gpt-5-mini"` → `("opencode", "github-copilot/gpt-5-mini")`
/// - `"claude"` → `("claude", "")`
pub fn parse_pool_entry(entry: &str) -> (String, String) {
    if let Some(colon_pos) = entry.find(':') {
        let agent = entry[..colon_pos].to_string();
        let model = entry[colon_pos + 1..].to_string();
        // Normalize trailing slashes in model part (defense-in-depth for bug #1507)
        let model = RouterConfig::normalize_model_identifier(&model);
        (agent, model)
    } else {
        (entry.to_string(), String::new())
    }
}

impl Default for RouterConfig {
    fn default() -> Self {
        Self {
            mode: "round_robin".to_string(),
            router_agent: "claude".to_string(),
            router_model: "haiku".to_string(),
            timeout_seconds: 45,
            fallback_executor: "codex".to_string(),
            agents: DEFAULT_AGENTS.iter().map(|s| s.to_string()).collect(),
            max_route_attempts: 3,
            pool: vec![],
            fallback: String::new(),
            self_routing_penalty: 1.0,
            weights: HashMap::new(),
            allowed_tools: vec![
                "yq".to_string(),
                "jq".to_string(),
                "bash".to_string(),
                "just".to_string(),
                "git".to_string(),
                "rg".to_string(),
                "sed".to_string(),
                "awk".to_string(),
                "python3".to_string(),
                "node".to_string(),
                "npm".to_string(),
                "bun".to_string(),
            ],
            default_skills: vec!["gh".to_string(), "git-worktree".to_string()],
            // model_map is intentionally empty — config.yml is the sole source of truth.
            // Hardcoded models cause "Model not found" failures when the model does not
            // exist for a particular agent (e.g. anthropic/ prefixed models for opencode).
            model_map: HashMap::new(),
            weighted_round_robin: false,
            skip_limited_threshold: 0.3,
            agent_backoff_bases: HashMap::new(),
            max_tasks_per_tick: 1,
            ollama_url: "http://localhost:11434".to_string(),
            ollama_model: "qwen2.5-coder:3b-instruct".to_string(),
            ollama_timeout_seconds: 30,
        }
    }
}

impl RouterConfig {
    /// Load configuration from config files.
    pub fn from_config() -> Self {
        let mut config = Self::default();

        // Try to load from config
        if let Ok(mode) = crate::config::get("router.mode") {
            if mode == "round_robin" || mode == "llm" || mode == "local" {
                config.mode = mode;
            }
        }

        if let Ok(agent) = crate::config::get("router.agent") {
            if !agent.is_empty() {
                config.router_agent = agent;
            }
        }

        if let Ok(model) = crate::config::get("router.model") {
            if !model.is_empty() {
                config.router_model = RouterConfig::normalize_model_identifier(&model);
            }
        }

        if let Ok(timeout) = crate::config::get("router.timeout_seconds") {
            if let Ok(secs) = timeout.parse::<u64>() {
                let clamped = secs.min(MAX_ROUTER_TIMEOUT_SECS);
                if clamped != secs {
                    static TIMEOUT_CLAMP_WARNED: std::sync::OnceLock<()> =
                        std::sync::OnceLock::new();
                    TIMEOUT_CLAMP_WARNED.get_or_init(|| {
                        tracing::warn!(
                            configured_secs = secs,
                            applied_secs = clamped,
                            max_secs = MAX_ROUTER_TIMEOUT_SECS,
                            "router.timeout_seconds is too high; clamping to keep routing responsive"
                        );
                    });
                }
                config.timeout_seconds = clamped;
            }
        }

        if let Ok(fallback) = crate::config::get("router.fallback_executor") {
            if !fallback.is_empty() {
                config.fallback_executor = fallback;
            }
        }

        // Parse agents list from top-level `agents:` config key
        config.agents = crate::engine::configured_agents();

        // Temporary operational toggle: allow disabling agents without editing
        // config files. Controlled by ORCH_EXCLUDE_AGENTS env var (comma-separated
        // list of agent names to exclude from routing). This keeps changes reversible
        // (unset the env var to restore behavior) and avoids editing user config files.
        // Example: ORCH_EXCLUDE_AGENTS=glm,some-other-agent
        let exclude_agents = std::env::var("ORCH_EXCLUDE_AGENTS")
            .map(|v| {
                v.split(',')
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();
        if !exclude_agents.is_empty() {
            let original_len = config.agents.len();
            config.agents.retain(|a| !exclude_agents.contains(a));
            let removed_count = original_len - config.agents.len();
            if removed_count > 0 {
                tracing::warn!(
                    "ORCH_EXCLUDE_AGENTS={}: temporarily removing {} agent(s) from router",
                    exclude_agents.join(","),
                    removed_count
                );
            }
        }

        if let Ok(max_attempts) = crate::config::get("router.max_route_attempts") {
            if let Ok(n) = max_attempts.parse::<u32>() {
                config.max_route_attempts = n;
            }
        }

        // Parse allowed_tools as comma-separated or YAML array
        if let Ok(tools_str) = crate::config::get("router.allowed_tools") {
            if !tools_str.is_empty() && tools_str != "[]" {
                // Try to parse as JSON/YAML array first
                if let Ok(tools_arr) = serde_json::from_str::<Vec<String>>(&tools_str) {
                    config.allowed_tools = tools_arr;
                } else {
                    // Fall back to comma-separated
                    config.allowed_tools = tools_str
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                }
            }
        }

        // Parse weighted_round_robin
        if let Ok(val) = crate::config::get("router.weighted_round_robin") {
            config.weighted_round_robin = val == "true" || val == "1";
        }

        // Parse self_routing_penalty
        if let Ok(val) = crate::config::get("router.self_routing_penalty") {
            if let Ok(penalty) = val.parse::<f64>() {
                config.self_routing_penalty = penalty.clamp(0.0, 1.0);
            }
        }

        // Parse per-agent weights from router.weights.<agent>
        for agent in &config.agents {
            let key = format!("router.weights.{agent}");
            if let Ok(val) = crate::config::get(&key) {
                if let Ok(w) = val.parse::<f64>() {
                    config.weights.insert(agent.clone(), w.max(0.0));
                }
            }
        }

        // Parse per-agent backoff base seconds from router.backoff_base.<agent>
        for agent in &config.agents {
            let key = format!("router.backoff_base.{agent}");
            if let Ok(val) = crate::config::get(&key) {
                if let Ok(secs) = val.parse::<i64>() {
                    config.agent_backoff_bases.insert(agent.clone(), secs);
                }
            }
        }

        // Parse max_tasks_per_tick
        if let Ok(val) = crate::config::get("router.max_tasks_per_tick") {
            if let Ok(n) = val.parse::<usize>() {
                if n > 0 {
                    config.max_tasks_per_tick = n;
                }
            }
        }

        // Parse pool: list of "agent:model" entries.
        // `config::get_list()` returns Ok(vec![]) when the key is missing, so we
        // can't rely on `is_ok()` to indicate presence.
        match crate::config::get_list("router.pool") {
            Ok(pool_list) if !pool_list.is_empty() => {
                config.pool = pool_list;
            }
            _ => {
                // Accept comma-separated string lists: "a,b,c"
                if let Ok(pool_raw) = crate::config::get("router.pool") {
                    let parsed = pool_raw
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect::<Vec<_>>();
                    if !parsed.is_empty() {
                        config.pool = parsed;
                    }
                }
            }
        }

        // Parse fallback: single "agent:model" entry
        if let Ok(fallback) = crate::config::get("router.fallback") {
            if !fallback.is_empty() {
                config.fallback = fallback;
            }
        }

        // Load top-level model shorthand from config (models.{agent}).
        //
        // These candidates apply to every complexity tier by default. More
        // specific model_map.{complexity}.{agent} entries below override the
        // shorthand for that one tier.
        let known_agents = crate::engine::configured_agents();
        let known_complexities = ["simple", "medium", "complex", "review"];
        for agent in &known_agents {
            let key = format!("models.{agent}");
            if let Some(models) = Self::read_model_pool_from_config(&key) {
                for complexity in known_complexities {
                    config
                        .model_map
                        .entry(complexity.to_string())
                        .or_default()
                        .insert(agent.to_string(), models.clone());
                }
            }
        }

        // Load model_map overrides from config (model_map.{complexity}.{agent})
        // Value may be a single string ("model-name") or a JSON array (["m1","m2"]).
        // Iterate over all known complexity tiers regardless of what is in model_map —
        // the Default impl has no hardcoded entries, so iterating over keys() would be a no-op.
        for complexity in known_complexities {
            for agent in &known_agents {
                let key = format!("model_map.{complexity}.{agent}");
                if let Some(models) = Self::read_model_pool_from_config(&key) {
                    config
                        .model_map
                        .entry(complexity.to_string())
                        .or_default()
                        .insert(agent.to_string(), models);
                }
            }
        }

        // Startup config hygiene: warn about and prune opencode model_map entries that
        // the provider catalog does not currently list.  Running this at load time avoids
        // dispatching unavailable models during routing — the dynamic filter in
        // `expanded_model_pool` also catches these, but fails open when discovery returns
        // empty (e.g. during a background cache refresh), allowing stale models through.
        let discovered_opencode =
            crate::engine::runner::agents::opencode::discover_opencode_models();
        if !discovered_opencode.is_empty() {
            let discovered: std::collections::HashSet<String> =
                discovered_opencode.into_iter().collect();
            for complexity in known_complexities {
                if let Some(agent_models) = config.model_map.get(complexity) {
                    if let Some(models) = agent_models.get("opencode") {
                        for model in models {
                            if model != "opencode:free" && !discovered.contains(model) {
                                tracing::warn!(
                                    complexity,
                                    model,
                                    "opencode model from config not present in provider model list; pruning from dispatch pool"
                                );
                            }
                        }
                    }
                }
            }
            let pruned =
                Self::prune_unavailable_opencode_models(&mut config.model_map, &discovered);
            if pruned > 0 {
                tracing::info!(
                    pruned_count = pruned,
                    "model_pruned_unavailable: removed opencode models absent from provider catalog"
                );
            }
        }

        // Parse default_skills
        if let Ok(skills_str) = crate::config::get("router.default_skills") {
            if !skills_str.is_empty() && skills_str != "[]" {
                if let Ok(skills_arr) = serde_json::from_str::<Vec<String>>(&skills_str) {
                    config.default_skills = skills_arr;
                } else {
                    config.default_skills = skills_str
                        .split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect();
                }
            }
        }

        // Parse Ollama-specific config for local routing mode
        if let Ok(url) = crate::config::get("router.ollama_url") {
            if !url.is_empty() {
                config.ollama_url = url;
            }
        }
        if let Ok(model) = crate::config::get("router.ollama_model") {
            if !model.is_empty() {
                config.ollama_model = model;
            }
        }
        if let Ok(timeout) = crate::config::get("router.ollama_timeout_seconds") {
            if let Ok(secs) = timeout.parse::<u64>() {
                if secs > 0 {
                    config.ollama_timeout_seconds = secs;
                }
            }
        }

        config
    }

    /// Return the effective pool — the configured pool, or a single-entry pool from `router_agent:router_model`.
    pub fn effective_pool(&self) -> Vec<String> {
        if !self.pool.is_empty() {
            self.pool.clone()
        } else {
            vec![format!("{}:{}", self.router_agent, self.router_model)]
        }
    }

    /// Return the effective fallback entry — the configured fallback, or `router_agent:router_model`.
    pub fn effective_fallback(&self) -> String {
        if !self.fallback.is_empty() {
            self.fallback.clone()
        } else {
            format!("{}:{}", self.router_agent, self.router_model)
        }
    }

    /// Check if a model identifier looks syntactically valid.
    /// Rejects empty strings, strings ending with slash, and strings with whitespace.
    fn is_valid_model_identifier(model: &str) -> bool {
        if model.is_empty() {
            return false;
        }
        // Reject trailing slash (e.g., "opus/")
        if model.ends_with('/') {
            return false;
        }
        // Reject whitespace
        if model.chars().any(char::is_whitespace) {
            return false;
        }
        // Ensure that if there is a slash, both parts are non-empty
        if let Some(slash_pos) = model.find('/') {
            let before = &model[..slash_pos];
            let after = &model[slash_pos + 1..];
            if before.is_empty() || after.is_empty() {
                return false;
            }
        }
        true
    }

    /// Normalize a model identifier by stripping trailing slashes.
    /// This is a defense-in-depth measure to handle edge cases where
    /// a model string might have been incorrectly formatted.
    pub fn normalize_model_identifier(model: &str) -> String {
        model.trim_end_matches('/').to_string()
    }

    fn read_model_pool_from_config(key: &str) -> Option<Vec<String>> {
        if let Ok(list) = crate::config::get_list(key) {
            if !list.is_empty() {
                return Some(
                    list.iter()
                        .map(|m| RouterConfig::normalize_model_identifier(m))
                        .collect(),
                );
            }
        } else if let Ok(val) = crate::config::get(key) {
            if !val.is_empty() {
                return Some(vec![RouterConfig::normalize_model_identifier(&val)]);
            }
        }

        None
    }

    fn expanded_model_pool(&self, agent: &str, complexity: &str) -> Option<Vec<String>> {
        let pool = self.model_map.get(complexity)?.get(agent)?;
        if pool.is_empty() {
            return Some(Vec::new());
        }

        let mut expanded_pool = Vec::new();
        let mut has_free = false;

        for model in pool {
            // Normalize the model identifier first to handle edge cases like trailing slashes
            let normalized = Self::normalize_model_identifier(model);
            if normalized == "opencode:free" {
                has_free = true;
            } else if Self::is_valid_model_identifier(&normalized) {
                expanded_pool.push(normalized);
            } else {
                tracing::debug!(agent, model, "skipping invalid model identifier in config");
            }
        }

        if has_free {
            expanded_pool
                .extend(crate::engine::runner::agents::opencode::discover_free_opencode_models());
        }

        // Also filter out invalid discovered free models (should be valid but just in case)
        expanded_pool.retain(|m| Self::is_valid_model_identifier(m));

        // For opencode, filter configured entries against the provider model catalog
        // when available. This proactively avoids dispatching non-existent model IDs.
        if agent == "opencode" {
            let discovered = crate::engine::runner::agents::opencode::discover_opencode_models();
            if !discovered.is_empty() {
                let discovered_set: std::collections::HashSet<String> =
                    discovered.into_iter().collect();
                expanded_pool.retain(|m| discovered_set.contains(m));
            }
        }

        Some(expanded_pool)
    }

    pub(crate) fn model_pool_for_complexity(
        &self,
        agent: &str,
        complexity: &str,
    ) -> Option<Vec<String>> {
        self.expanded_model_pool(agent, complexity)
    }

    pub fn has_available_model_for_complexity(&self, agent: &str, complexity: &str) -> bool {
        match self.expanded_model_pool(agent, complexity) {
            None => false,
            Some(pool) => pool
                .iter()
                .any(|model| !crate::engine::cooldown::is_model_in_cooldown(agent, model)),
        }
    }

    /// Get the model for a given agent and complexity level.
    ///
    /// When the complexity tier has a pool of models, selects randomly using
    /// `task_id` as an entropy source and skips models currently in cooldown.
    /// Falls back to `pool[0]` if all models are cooled.
    ///
    /// Backward-compatible: a single-model pool always returns that model.
    pub fn model_for_complexity(
        &self,
        agent: &str,
        complexity: &str,
        task_id: &str,
    ) -> Option<String> {
        let expanded_pool = self.expanded_model_pool(agent, complexity)?;
        if expanded_pool.is_empty() {
            return None;
        }
        // Random starting index — varies per task_id to distribute across the pool
        let start =
            crate::engine::router::selection::simple_hash_index_for(expanded_pool.len(), task_id);
        // Walk the pool from start, skipping cooled and invalid models
        for i in 0..expanded_pool.len() {
            let model = &expanded_pool[(start + i) % expanded_pool.len()];
            // Safety check: skip invalid identifiers (should already be filtered)
            if !Self::is_valid_model_identifier(model) {
                tracing::debug!(
                    agent,
                    model,
                    "invalid model identifier slipped through validation"
                );
                continue;
            }
            if !crate::engine::cooldown::is_model_in_cooldown(agent, model) {
                // Normalize the model identifier to handle edge cases like trailing slashes
                return Some(Self::normalize_model_identifier(model));
            }
        }
        // All models cooled — return None so the caller can fall back to a different agent
        None
    }

    /// Remove `model_map` entries for the `opencode` agent whose identifiers do not
    /// appear in `discovered`.  The sentinel value `"opencode:free"` is never pruned
    /// because it is expanded at routing time and is not dispatched as a literal model ID.
    ///
    /// Returns the total number of model entries removed across all complexity tiers.
    fn prune_unavailable_opencode_models(
        model_map: &mut HashMap<String, HashMap<String, Vec<String>>>,
        discovered: &std::collections::HashSet<String>,
    ) -> usize {
        let mut pruned = 0;
        for agent_models in model_map.values_mut() {
            if let Some(models) = agent_models.get_mut("opencode") {
                let before = models.len();
                models.retain(|m| m == "opencode:free" || discovered.contains(m));
                pruned += before - models.len();
            }
        }
        pruned
    }
}

#[cfg(test)]
mod tests {
    use super::{RouterConfig, MAX_ROUTER_TIMEOUT_SECS};
    use serial_test::serial;
    use std::sync::{Mutex, OnceLock};

    struct CurrentDirGuard {
        original: std::path::PathBuf,
    }

    impl CurrentDirGuard {
        fn set(path: &std::path::Path) -> Self {
            let original = std::env::current_dir().unwrap();
            std::env::set_current_dir(path).unwrap();
            Self { original }
        }
    }

    impl Drop for CurrentDirGuard {
        fn drop(&mut self) {
            std::env::set_current_dir(&self.original).unwrap();
        }
    }

    fn cwd_mutex() -> &'static Mutex<()> {
        static CWD_MUTEX: OnceLock<Mutex<()>> = OnceLock::new();
        CWD_MUTEX.get_or_init(|| Mutex::new(()))
    }

    #[serial(cooldown_state)]
    #[tokio::test]
    async fn model_for_complexity_returns_none_when_all_models_cooled() {
        crate::engine::cooldown::reset_global_state().await;
        let mut config = RouterConfig::default();
        // Inject a two-model pool for a unique agent name to avoid cross-test pollution
        config
            .model_map
            .entry("complex".to_string())
            .or_default()
            .insert(
                "testagent_allcooled".to_string(),
                vec![
                    "cooldown-model-a".to_string(),
                    "cooldown-model-b".to_string(),
                ],
            );

        // Put both models into cooldown
        crate::engine::cooldown::record_model_failure("testagent_allcooled", "cooldown-model-a")
            .await;
        crate::engine::cooldown::record_model_failure("testagent_allcooled", "cooldown-model-b")
            .await;

        let result = config.model_for_complexity("testagent_allcooled", "complex", "task-0");
        assert!(
            result.is_none(),
            "should return None when all models in pool are in cooldown, got {result:?}"
        );
    }

    #[serial(cooldown_state)]
    #[tokio::test]
    async fn model_for_complexity_returns_none_when_single_model_cooled() {
        crate::engine::cooldown::reset_global_state().await;
        let mut config = RouterConfig::default();
        config
            .model_map
            .entry("complex".to_string())
            .or_default()
            .insert(
                "testagent_singlecooled".to_string(),
                vec!["single-cooled-model".to_string()],
            );

        crate::engine::cooldown::record_model_failure(
            "testagent_singlecooled",
            "single-cooled-model",
        )
        .await;

        let result = config.model_for_complexity("testagent_singlecooled", "complex", "task-0");
        assert!(
            result.is_none(),
            "should return None when the only model in pool is in cooldown, got {result:?}"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn model_for_complexity_returns_model_when_not_cooled() {
        let mut config = RouterConfig::default();
        config
            .model_map
            .entry("complex".to_string())
            .or_default()
            .insert(
                "testagent_notcooled".to_string(),
                vec!["healthy-model".to_string()],
            );

        // Ensure no cooldown is active for this specific model
        let result = config.model_for_complexity("testagent_notcooled", "complex", "task-0");
        assert_eq!(
            result.as_deref(),
            Some("healthy-model"),
            "should return the model when it is not in cooldown"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn has_available_model_returns_false_when_no_pool_configured() {
        let mut config = RouterConfig::default();
        // Simulate olm agent with only simple and medium configured (missing complex and review)
        config
            .model_map
            .entry("simple".to_string())
            .or_default()
            .insert("olm".to_string(), vec!["qwen3.5".to_string()]);
        config
            .model_map
            .entry("medium".to_string())
            .or_default()
            .insert("olm".to_string(), vec!["gemma4".to_string()]);
        // Note: complex and review tiers are NOT configured for olm

        // has_available_model_for_complexity should return false when no pool exists
        assert!(
            config.has_available_model_for_complexity("olm", "simple"),
            "should return true when model pool exists and is configured"
        );
        assert!(
            config.has_available_model_for_complexity("olm", "medium"),
            "should return true when model pool exists and is configured"
        );
        assert!(
            !config.has_available_model_for_complexity("olm", "complex"),
            "should return false when no model pool is configured for agent+complexity"
        );
        assert!(
            !config.has_available_model_for_complexity("olm", "review"),
            "should return false when no model pool is configured for agent+complexity"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn default_self_routing_penalty_is_one() {
        let config = RouterConfig::default();
        assert_eq!(
            config.self_routing_penalty, 1.0,
            "default penalty must be 1.0 (no penalty = full self-routing allowed)"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_reads_self_routing_penalty() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".orch.yml"),
            "router:\n  self_routing_penalty: 0.5\n",
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();
        assert_eq!(config.self_routing_penalty, 0.5);
    }

    #[serial(cooldown_state)]
    #[test]
    fn default_config_model_map_is_empty() {
        // model_map must be empty — config.yml is the sole source of truth for models.
        // Hardcoded defaults (especially anthropic/ prefixed opencode models) cause
        // "Model not found" failures when the model does not exist for a given agent.
        let config = RouterConfig::default();
        assert!(
            config.model_map.is_empty(),
            "Default RouterConfig must have no hardcoded models; got {:?}",
            config.model_map
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_reads_router_pool_yaml_array() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".orch.yml"),
            "router:\n  pool:\n    - opencode:free\n    - opencode:github-copilot/gpt-5-mini\n    - kimi:k2p5\n    - claude:haiku\n",
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();

        assert_eq!(
            config.pool,
            vec![
                "opencode:free",
                "opencode:github-copilot/gpt-5-mini",
                "kimi:k2p5",
                "claude:haiku",
            ]
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_clamps_router_timeout_to_max() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".orch.yml"),
            "router:\n  timeout_seconds: 90\n",
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();
        assert_eq!(config.timeout_seconds, MAX_ROUTER_TIMEOUT_SECS);
    }

    #[serial(cooldown_state)]
    #[test]
    fn normalize_model_identifier_strips_trailing_slash() {
        // Bug #1507: model assignment was producing "opus/" instead of "opus"
        assert_eq!(
            RouterConfig::normalize_model_identifier("opus/"),
            "opus",
            "trailing slash should be stripped from model identifier"
        );
        assert_eq!(
            RouterConfig::normalize_model_identifier("sonnet/"),
            "sonnet",
            "trailing slash should be stripped from model identifier"
        );
        assert_eq!(
            RouterConfig::normalize_model_identifier("github-copilot/gpt-5-mini/"),
            "github-copilot/gpt-5-mini",
            "trailing slash should be stripped from model identifier with internal slash"
        );
        // Edge cases: multiple trailing slashes
        assert_eq!(
            RouterConfig::normalize_model_identifier("opus//"),
            "opus",
            "multiple trailing slashes should be stripped"
        );
        // Edge cases: no trailing slash
        assert_eq!(
            RouterConfig::normalize_model_identifier("opus"),
            "opus",
            "model without trailing slash should remain unchanged"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn is_valid_model_identifier_rejects_trailing_slash() {
        // Ensure validation correctly rejects models with trailing slashes
        assert!(
            !RouterConfig::is_valid_model_identifier("opus/"),
            "model with trailing slash should be invalid"
        );
        assert!(
            RouterConfig::is_valid_model_identifier("opus"),
            "model without trailing slash should be valid"
        );
        assert!(
            RouterConfig::is_valid_model_identifier("github-copilot/gpt-5-mini"),
            "model with internal slash should be valid"
        );
        assert!(
            !RouterConfig::is_valid_model_identifier("github-copilot/"),
            "model ending with slash after prefix should be invalid"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_loads_model_map_for_custom_agents() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        // Simulate a config with a custom agent (olm) in both agents and model_map
        std::fs::write(
            dir.path().join(".orch.yml"),
            r#"
agents:
  - claude
  - olm
model_map:
  simple:
    claude: haiku
    olm: qwen3.5
  medium:
    claude: sonnet
    olm: gemma4
  complex:
    claude: opus
    olm: gemma4
"#,
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();

        // olm models should be loaded from the model_map
        assert_eq!(
            config.model_for_complexity("olm", "simple", "test-task"),
            Some("qwen3.5".to_string()),
            "custom agent olm should have simple model from config"
        );
        assert_eq!(
            config.model_for_complexity("olm", "medium", "test-task"),
            Some("gemma4".to_string()),
            "custom agent olm should have medium model from config"
        );
        // claude should also work
        assert_eq!(
            config.model_for_complexity("claude", "simple", "test-task"),
            Some("haiku".to_string()),
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_loads_models_shorthand_for_all_complexities() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".orch.yml"),
            r#"
agents:
  - shorthand
models:
  shorthand:
    - gpt-5.2
    - gpt-5.5
"#,
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();

        for complexity in ["simple", "medium", "complex", "review"] {
            assert_eq!(
                config.model_map[complexity]["shorthand"],
                vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()],
                "models.shorthand should populate {complexity}"
            );
        }
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_loads_single_model_shorthand_for_all_complexities() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".orch.yml"),
            r#"
agents:
  - shorthand
models:
  shorthand: gpt-5.2
"#,
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();

        for complexity in ["simple", "medium", "complex", "review"] {
            assert_eq!(
                config.model_map[complexity]["shorthand"],
                vec!["gpt-5.2".to_string()],
                "models.shorthand should populate {complexity}"
            );
        }
    }

    #[serial(cooldown_state)]
    #[test]
    fn from_config_model_map_overrides_models_shorthand_per_tier() {
        let _lock = cwd_mutex().lock().unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join(".orch.yml"),
            r#"
agents:
  - shorthand
models:
  shorthand:
    - gpt-5.2
    - gpt-5.5
model_map:
  review:
    shorthand: gpt-5.6-review
"#,
        )
        .unwrap();
        let _guard = CurrentDirGuard::set(dir.path());

        let config = RouterConfig::from_config();

        assert_eq!(
            config.model_map["simple"]["shorthand"],
            vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
        );
        assert_eq!(
            config.model_map["medium"]["shorthand"],
            vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
        );
        assert_eq!(
            config.model_map["complex"]["shorthand"],
            vec!["gpt-5.2".to_string(), "gpt-5.5".to_string()]
        );
        assert_eq!(
            config.model_map["review"]["shorthand"],
            vec!["gpt-5.6-review".to_string()]
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn model_for_complexity_normalizes_trailing_slash_from_pool() {
        // Bug #1507: full path test - model identifiers with trailing slashes
        // should be normalized (not dropped) when loading from model_map pool
        let mut config = RouterConfig::default();
        config
            .model_map
            .entry("complex".to_string())
            .or_default()
            .insert(
                "testagent_trailing".to_string(),
                vec![
                    "opus/".to_string(),
                    "sonnet//".to_string(),
                    "github-copilot/gpt-5-mini/".to_string(),
                ],
            );

        // Should return normalized "opus" instead of dropping it as invalid
        let result = config.model_for_complexity("testagent_trailing", "complex", "task-0");
        assert!(
            result.is_some(),
            "should return a model from pool with trailing slashes normalized, got None"
        );
        let model = result.unwrap();
        // The model returned should be one of the normalized versions
        assert!(
            model == "opus" || model == "sonnet" || model == "github-copilot/gpt-5-mini",
            "returned model should be normalized (no trailing slash), got: {}",
            model
        );
        // Verify no trailing slashes in the returned model
        assert!(
            !model.ends_with('/'),
            "returned model should not have trailing slash, got: {}",
            model
        );
    }

    // --- prune_unavailable_opencode_models regression tests (bug #3169) ---

    #[serial(cooldown_state)]
    #[test]
    fn prune_unavailable_opencode_models_removes_missing_models() {
        use std::collections::{HashMap, HashSet};

        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
        model_map.entry("complex".to_string()).or_default().insert(
            "opencode".to_string(),
            vec![
                "available-model".to_string(),
                "unavailable-model".to_string(),
                "opencode:free".to_string(), // sentinel — must survive pruning
            ],
        );

        let mut discovered = HashSet::new();
        discovered.insert("available-model".to_string());
        // "unavailable-model" intentionally absent

        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);

        assert_eq!(pruned, 1, "should prune exactly the one unavailable model");

        let remaining = model_map["complex"]["opencode"].as_slice();
        assert!(
            remaining.contains(&"available-model".to_string()),
            "available model should remain"
        );
        assert!(
            remaining.contains(&"opencode:free".to_string()),
            "opencode:free sentinel should never be pruned"
        );
        assert!(
            !remaining.contains(&"unavailable-model".to_string()),
            "unavailable model should be removed"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn prune_unavailable_opencode_models_noop_when_all_available() {
        use std::collections::{HashMap, HashSet};

        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
        model_map.entry("simple".to_string()).or_default().insert(
            "opencode".to_string(),
            vec!["model-a".to_string(), "model-b".to_string()],
        );

        let discovered: HashSet<String> = ["model-a", "model-b"]
            .iter()
            .map(|s| s.to_string())
            .collect();

        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);

        assert_eq!(pruned, 0, "nothing to prune when all models are available");
        assert_eq!(
            model_map["simple"]["opencode"].len(),
            2,
            "both models should remain"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn prune_unavailable_opencode_models_preserves_non_opencode_agents() {
        use std::collections::{HashMap, HashSet};

        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
        model_map
            .entry("complex".to_string())
            .or_default()
            .insert("claude".to_string(), vec!["some-model".to_string()]);

        // discovered is empty — irrelevant for non-opencode agents
        let discovered: HashSet<String> = HashSet::new();

        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);

        assert_eq!(pruned, 0, "non-opencode agents must not be touched");
        assert_eq!(
            model_map["complex"]["claude"].len(),
            1,
            "claude model should be unchanged"
        );
    }

    #[serial(cooldown_state)]
    #[test]
    fn prune_unavailable_opencode_models_covers_all_complexity_tiers() {
        use std::collections::{HashMap, HashSet};

        let mut model_map: HashMap<String, HashMap<String, Vec<String>>> = HashMap::new();
        for tier in ["simple", "medium", "complex", "review"] {
            model_map
                .entry(tier.to_string())
                .or_default()
                .insert("opencode".to_string(), vec!["gone-model".to_string()]);
        }

        // "gone-model" is not in discovered
        let discovered: HashSet<String> = HashSet::new();

        let pruned = RouterConfig::prune_unavailable_opencode_models(&mut model_map, &discovered);

        assert_eq!(pruned, 4, "should prune one entry per complexity tier");
        for tier in ["simple", "medium", "complex", "review"] {
            assert!(
                model_map[tier]["opencode"].is_empty(),
                "all entries for {} should be removed",
                tier
            );
        }
    }
}