agent-teams 0.1.0

Generic Rust agent teams framework replicating Claude Code Agent Teams architecture with pluggable backends for Claude Code, Codex, and Gemini CLI
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
//! Dynamic backend routing — select the optimal backend for a given task.
//!
//! The [`BackendRouter`] trait decides which [`BackendType`] to use for a given
//! [`SpawnConfig`], based on keyword heuristics, cost, or any custom logic.

use std::collections::HashMap;

use async_trait::async_trait;

use super::{BackendType, SpawnConfig};

/// A router that selects the best backend for a given spawn configuration.
///
/// Implementations can use keyword matching, cost estimation, model capability
/// databases, or even LLM-based classification to make the decision.
#[async_trait]
pub trait BackendRouter: Send + Sync {
    /// Choose the optimal backend for the given config.
    ///
    /// `available` lists the backends that the orchestrator has registered.
    /// Returns `None` if no suitable backend can be found (e.g., `available` is
    /// empty or all backends are filtered out by requirements).
    async fn route(
        &self,
        config: &SpawnConfig,
        available: &[BackendType],
    ) -> Option<BackendType>;
}

// ---------------------------------------------------------------------------
// KeywordRouter
// ---------------------------------------------------------------------------

/// A keyword-based router with configurable rules and a default fallback.
///
/// Rules map keyword patterns (matched case-insensitively against the prompt)
/// to a preferred [`BackendType`]. The first matching rule wins. If no rules
/// match, the `default` backend is used.
///
/// By default, keywords are matched as substrings. Enable [`word_boundary`](Self::word_boundary)
/// to require that keywords appear as whole words (e.g., "test" won't match "testing").
///
/// # Example
///
/// ```rust
/// use agent_teams::backend::router::KeywordRouter;
/// use agent_teams::BackendType;
///
/// let router = KeywordRouter::new(BackendType::ClaudeCode)
///     .word_boundary(true)
///     .rule("review", BackendType::GeminiCli)
///     .rule("analyze", BackendType::GeminiCli)
///     .rule("implement", BackendType::ClaudeCode)
///     .rule("test", BackendType::Codex);
/// ```
#[derive(Debug)]
pub struct KeywordRouter {
    rules: Vec<(String, BackendType)>,
    default: BackendType,
    /// When true, keywords must appear as whole words (bounded by non-alphanumeric chars).
    use_word_boundary: bool,
}

impl KeywordRouter {
    /// Create a new keyword router with a default backend.
    pub fn new(default: BackendType) -> Self {
        Self {
            rules: Vec::new(),
            default,
            use_word_boundary: false,
        }
    }

    /// Enable or disable word-boundary matching.
    ///
    /// When enabled, "test" matches "test this code" but NOT "testing this code".
    /// Default is `false` (substring matching) for backward compatibility.
    pub fn word_boundary(mut self, enable: bool) -> Self {
        self.use_word_boundary = enable;
        self
    }

    /// Add a keyword → backend rule. Keywords are matched case-insensitively
    /// against the `SpawnConfig::prompt` field.
    pub fn rule(mut self, keyword: impl Into<String>, backend: BackendType) -> Self {
        self.rules.push((keyword.into().to_lowercase(), backend));
        self
    }

    /// Add multiple rules from an iterator of `(keyword, backend)` pairs.
    pub fn rules(mut self, rules: impl IntoIterator<Item = (String, BackendType)>) -> Self {
        for (kw, bt) in rules {
            self.rules.push((kw.to_lowercase(), bt));
        }
        self
    }
}

/// Check if `text` contains `word` as a whole word (bounded by non-alphanumeric characters).
///
/// Both `text` and `word` must be valid UTF-8 (guaranteed by `&str`). The boundary
/// check uses [`u8::is_ascii_alphanumeric`], so non-ASCII characters are always
/// treated as word boundaries — this is intentional for prompt-level keyword matching.
fn contains_word(text: &str, word: &str) -> bool {
    if word.is_empty() || text.len() < word.len() {
        return false;
    }
    let text_bytes = text.as_bytes();
    let mut start = 0;
    while start + word.len() <= text.len() {
        match text[start..].find(word) {
            Some(pos) => {
                let abs_pos = start + pos;
                let before_ok =
                    abs_pos == 0 || !text_bytes[abs_pos - 1].is_ascii_alphanumeric();
                let after_pos = abs_pos + word.len();
                let after_ok =
                    after_pos >= text.len() || !text_bytes[after_pos].is_ascii_alphanumeric();
                if before_ok && after_ok {
                    return true;
                }
                // Advance past the current match start to the next character boundary.
                // Using `abs_pos + word.len()` is safe (word is a valid &str so its
                // byte length always lands on a UTF-8 boundary) and also more efficient
                // since a shorter match starting within the current word cannot exist.
                start = abs_pos + word.len();
            }
            None => break,
        }
    }
    false
}

#[async_trait]
impl BackendRouter for KeywordRouter {
    async fn route(
        &self,
        config: &SpawnConfig,
        available: &[BackendType],
    ) -> Option<BackendType> {
        if available.is_empty() {
            return None;
        }

        let prompt_lower = config.prompt.to_lowercase();

        // Find the first matching rule whose backend is available
        for (keyword, backend) in &self.rules {
            let matched = if self.use_word_boundary {
                contains_word(&prompt_lower, keyword.as_str())
            } else {
                prompt_lower.contains(keyword.as_str())
            };
            if matched && available.contains(backend) {
                return Some(*backend);
            }
        }

        // Fall back to default if available, otherwise first available
        if available.contains(&self.default) {
            Some(self.default)
        } else {
            available.first().copied()
        }
    }
}

// ---------------------------------------------------------------------------
// CapabilityRouter
// ---------------------------------------------------------------------------

/// Backend capabilities for making routing decisions.
///
/// Default values represent a generic mid-tier backend (multi-turn, streaming,
/// cost=2, latency=2). Use [`BackendCapability::defaults()`] for pre-configured
/// values for known backends.
#[derive(Debug, Clone)]
pub struct BackendCapability {
    /// Supports multi-turn conversations.
    pub multi_turn: bool,
    /// Supports streaming output.
    pub streaming: bool,
    /// Relative cost (lower is cheaper). Unitless; used for comparison only.
    pub cost_tier: u8,
    /// Relative latency (lower is faster). Unitless; used for comparison only.
    pub latency_tier: u8,
}

impl Default for BackendCapability {
    fn default() -> Self {
        Self {
            multi_turn: true,
            streaming: true,
            cost_tier: 2,
            latency_tier: 2,
        }
    }
}

impl BackendCapability {
    /// Default capabilities for known backends.
    pub fn defaults() -> HashMap<BackendType, BackendCapability> {
        let mut map = HashMap::new();
        map.insert(BackendType::ClaudeCode, BackendCapability {
            multi_turn: true,
            streaming: true,
            cost_tier: 3,   // most capable, highest cost
            latency_tier: 2,
        });
        map.insert(BackendType::Codex, BackendCapability {
            multi_turn: true,
            streaming: true,
            cost_tier: 2,
            latency_tier: 2,
        });
        map.insert(BackendType::GeminiCli, BackendCapability {
            multi_turn: false, // one-shot process per turn
            streaming: true,
            cost_tier: 1,     // cheapest for simple tasks
            latency_tier: 3,  // CLI startup overhead
        });
        map
    }
}

/// A capability-aware router that selects backends based on task requirements.
///
/// Scores each available backend on a weighted combination of cost and latency,
/// with optional requirement filters (e.g., must support multi-turn).
#[derive(Debug)]
pub struct CapabilityRouter {
    capabilities: HashMap<BackendType, BackendCapability>,
    /// If true, only consider multi-turn backends.
    require_multi_turn: bool,
    /// Weight for cost (0.0–1.0). Remainder goes to latency.
    cost_weight: f32,
}

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

impl CapabilityRouter {
    /// Create a capability router with default capability data.
    pub fn new() -> Self {
        Self {
            capabilities: BackendCapability::defaults(),
            require_multi_turn: false,
            cost_weight: 0.5,
        }
    }

    /// Only route to backends that support multi-turn conversations.
    pub fn require_multi_turn(mut self, require: bool) -> Self {
        self.require_multi_turn = require;
        self
    }

    /// Set the cost vs latency weight (0.0 = pure latency, 1.0 = pure cost).
    pub fn cost_weight(mut self, weight: f32) -> Self {
        self.cost_weight = weight.clamp(0.0, 1.0);
        self
    }

    /// Override capability data for a backend.
    pub fn with_capability(mut self, backend: BackendType, cap: BackendCapability) -> Self {
        self.capabilities.insert(backend, cap);
        self
    }
}

#[async_trait]
impl BackendRouter for CapabilityRouter {
    async fn route(
        &self,
        _config: &SpawnConfig,
        available: &[BackendType],
    ) -> Option<BackendType> {
        let latency_weight = 1.0 - self.cost_weight;

        // Score each candidate; backends without capability entries get a neutral default
        available
            .iter()
            .filter(|bt| {
                if let Some(cap) = self.capabilities.get(bt) {
                    !self.require_multi_turn || cap.multi_turn
                } else {
                    // Unknown backends are included with neutral score unless multi-turn is required
                    !self.require_multi_turn
                }
            })
            .min_by(|a, b| {
                let score = |bt: &BackendType| -> f32 {
                    if let Some(cap) = self.capabilities.get(bt) {
                        self.cost_weight * cap.cost_tier as f32
                            + latency_weight * cap.latency_tier as f32
                    } else {
                        // Neutral score for unknown backends (middle tier)
                        self.cost_weight * 2.0 + latency_weight * 2.0
                    }
                };
                score(a)
                    .partial_cmp(&score(b))
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .copied()
    }
}

// ---------------------------------------------------------------------------
// ChainRouter
// ---------------------------------------------------------------------------

/// A composite router that tries multiple routers in sequence.
///
/// The first router to return `Some(backend)` wins. If all routers return
/// `None`, the chain returns `None`.
///
/// This is useful for combining a precise [`KeywordRouter`] with a broader
/// [`CapabilityRouter`] as a fallback:
///
/// ```rust
/// use agent_teams::backend::router::{ChainRouter, KeywordRouter, CapabilityRouter};
/// use agent_teams::BackendType;
///
/// let router = ChainRouter::new()
///     .push(KeywordRouter::new(BackendType::ClaudeCode)
///         .word_boundary(true)
///         .rule("review", BackendType::GeminiCli))
///     .push(CapabilityRouter::new().cost_weight(0.7));
/// ```
pub struct ChainRouter {
    routers: Vec<Box<dyn BackendRouter>>,
}

impl std::fmt::Debug for ChainRouter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChainRouter")
            .field("routers_count", &self.routers.len())
            .finish()
    }
}

impl ChainRouter {
    /// Create an empty chain.
    pub fn new() -> Self {
        Self {
            routers: Vec::new(),
        }
    }

    /// Append a router to the chain.
    pub fn push(mut self, router: impl BackendRouter + 'static) -> Self {
        self.routers.push(Box::new(router));
        self
    }
}

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

#[async_trait]
impl BackendRouter for ChainRouter {
    async fn route(
        &self,
        config: &SpawnConfig,
        available: &[BackendType],
    ) -> Option<BackendType> {
        for router in &self.routers {
            if let Some(bt) = router.route(config, available).await {
                return Some(bt);
            }
        }
        None
    }
}

// ---------------------------------------------------------------------------
// SmartRouter
// ---------------------------------------------------------------------------

/// Prompt complexity level inferred from heuristic analysis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptComplexity {
    /// Short, simple prompts (single sentence, no code).
    Simple,
    /// Medium-length prompts or those containing code snippets.
    Medium,
    /// Long, multi-paragraph prompts with significant code or technical depth.
    Complex,
}

/// A smart router that combines keyword matching, capability scoring, and
/// prompt complexity analysis to select the optimal backend.
///
/// **Routing strategy** (evaluated in order):
///
/// 1. **Priority overrides** — explicit `(keyword, backend)` pairs checked first.
///    If a keyword matches the prompt and the backend is available, it wins immediately.
///
/// 2. **Prompt complexity analysis** — the prompt is scored for length, code presence,
///    and technical depth. Each complexity level maps to a preferred backend.
///
/// 3. **Capability fallback** — an embedded [`CapabilityRouter`] scores remaining
///    candidates on cost/latency when neither keywords nor complexity produce a match.
///
/// # Example
///
/// ```rust
/// use agent_teams::backend::router::SmartRouter;
/// use agent_teams::BackendType;
///
/// let router = SmartRouter::new(BackendType::ClaudeCode)
///     .priority("security audit", BackendType::ClaudeCode)
///     .priority("quick fix", BackendType::Codex)
///     .simple_backend(BackendType::GeminiCli)
///     .complex_backend(BackendType::ClaudeCode)
///     .complexity_threshold(200, 800)
///     .cost_weight(0.6);
/// ```
#[derive(Debug)]
pub struct SmartRouter {
    /// Priority keyword overrides (checked first, word-boundary matching).
    priorities: Vec<(String, BackendType)>,
    /// Backend preferred for simple prompts.
    simple: Option<BackendType>,
    /// Backend preferred for medium-complexity prompts.
    medium: Option<BackendType>,
    /// Backend preferred for complex prompts.
    complex: Option<BackendType>,
    /// Character threshold: prompts shorter than this are `Simple`.
    simple_threshold: usize,
    /// Character threshold: prompts longer than this are `Complex`.
    complex_threshold: usize,
    /// Capability-based fallback router.
    capability: CapabilityRouter,
    /// Default backend (used when nothing else matches).
    default: BackendType,
}

impl SmartRouter {
    /// Create a new smart router with a default backend.
    pub fn new(default: BackendType) -> Self {
        Self {
            priorities: Vec::new(),
            simple: None,
            medium: None,
            complex: None,
            simple_threshold: 200,
            complex_threshold: 800,
            capability: CapabilityRouter::new(),
            default,
        }
    }

    /// Add a priority keyword override.
    ///
    /// Priority keywords use word-boundary matching (same semantics as
    /// [`KeywordRouter::word_boundary(true)`]). The first matching priority wins.
    pub fn priority(mut self, keyword: impl Into<String>, backend: BackendType) -> Self {
        self.priorities.push((keyword.into().to_lowercase(), backend));
        self
    }

    /// Set the preferred backend for simple (short, non-technical) prompts.
    pub fn simple_backend(mut self, backend: BackendType) -> Self {
        self.simple = Some(backend);
        self
    }

    /// Set the preferred backend for medium-complexity prompts.
    pub fn medium_backend(mut self, backend: BackendType) -> Self {
        self.medium = Some(backend);
        self
    }

    /// Set the preferred backend for complex (long, code-heavy) prompts.
    pub fn complex_backend(mut self, backend: BackendType) -> Self {
        self.complex = Some(backend);
        self
    }

    /// Set the character-length thresholds for complexity classification.
    ///
    /// - Prompts shorter than `simple` characters are `Simple`.
    /// - Prompts longer than `complex` characters are `Complex`.
    /// - Everything in between is `Medium`.
    ///
    /// Defaults: `simple = 200`, `complex = 800`.
    ///
    /// # Panics
    ///
    /// Panics in debug mode if `simple >= complex`.
    pub fn complexity_threshold(mut self, simple: usize, complex: usize) -> Self {
        debug_assert!(simple < complex, "simple threshold must be less than complex threshold");
        self.simple_threshold = simple;
        self.complex_threshold = complex;
        self
    }

    /// Set the cost vs latency weight for the capability fallback (0.0–1.0).
    pub fn cost_weight(mut self, weight: f32) -> Self {
        self.capability = self.capability.cost_weight(weight);
        self
    }

    /// Require multi-turn support in the capability fallback.
    pub fn require_multi_turn(mut self, require: bool) -> Self {
        self.capability = self.capability.require_multi_turn(require);
        self
    }

    /// Override capability data for a backend in the fallback scorer.
    pub fn with_capability(mut self, backend: BackendType, cap: BackendCapability) -> Self {
        self.capability = self.capability.with_capability(backend, cap);
        self
    }

    /// Analyze a prompt and return its complexity level.
    pub fn analyze_complexity(&self, prompt: &str) -> PromptComplexity {
        let len = prompt.len();

        // Code indicators: triple-backtick blocks, `fn `, `def `, `class `, `impl `,
        // `struct `, `import `, `#include`, common code patterns
        let has_code = prompt.contains("```")
            || prompt.contains("fn ")
            || prompt.contains("def ")
            || prompt.contains("class ")
            || prompt.contains("impl ")
            || prompt.contains("struct ")
            || prompt.contains("import ")
            || prompt.contains("#include")
            || prompt.contains("function ")
            || prompt.contains("async fn");

        // Multi-paragraph indicator
        let paragraph_count = prompt.split("\n\n").count();

        if len >= self.complex_threshold || (has_code && len >= self.simple_threshold) || paragraph_count >= 4 {
            PromptComplexity::Complex
        } else if len >= self.simple_threshold || has_code || paragraph_count >= 2 {
            PromptComplexity::Medium
        } else {
            PromptComplexity::Simple
        }
    }
}

#[async_trait]
impl BackendRouter for SmartRouter {
    async fn route(
        &self,
        config: &SpawnConfig,
        available: &[BackendType],
    ) -> Option<BackendType> {
        if available.is_empty() {
            return None;
        }

        let prompt_lower = config.prompt.to_lowercase();

        // Phase 1: Priority keyword overrides (word-boundary matching)
        for (keyword, backend) in &self.priorities {
            if contains_word(&prompt_lower, keyword.as_str()) && available.contains(backend) {
                return Some(*backend);
            }
        }

        // Phase 2: Prompt complexity routing
        let complexity = self.analyze_complexity(&config.prompt);
        let preferred = match complexity {
            PromptComplexity::Simple => self.simple,
            PromptComplexity::Medium => self.medium,
            PromptComplexity::Complex => self.complex,
        };
        if let Some(backend) = preferred {
            if available.contains(&backend) {
                return Some(backend);
            }
        }

        // Phase 3: Capability-based fallback
        if let Some(bt) = self.capability.route(config, available).await {
            return Some(bt);
        }

        // Phase 4: Default or first available
        if available.contains(&self.default) {
            Some(self.default)
        } else {
            available.first().copied()
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[tokio::test]
    async fn keyword_router_matches_first_rule() {
        let router = KeywordRouter::new(BackendType::ClaudeCode)
            .rule("review", BackendType::GeminiCli)
            .rule("implement", BackendType::ClaudeCode)
            .rule("test", BackendType::Codex);

        let config = SpawnConfig::new("reviewer", "Please review this code carefully.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        let result = router.route(&config, &available).await;
        assert_eq!(result, Some(BackendType::GeminiCli));
    }

    #[tokio::test]
    async fn keyword_router_falls_back_to_default() {
        let router = KeywordRouter::new(BackendType::Codex)
            .rule("review", BackendType::GeminiCli);

        let config = SpawnConfig::new("worker", "Do something unrelated.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex];

        let result = router.route(&config, &available).await;
        assert_eq!(result, Some(BackendType::Codex));
    }

    #[tokio::test]
    async fn keyword_router_skips_unavailable_backend() {
        let router = KeywordRouter::new(BackendType::ClaudeCode)
            .rule("review", BackendType::GeminiCli);

        let config = SpawnConfig::new("reviewer", "Please review this code.");
        // GeminiCli not available
        let available = vec![BackendType::ClaudeCode, BackendType::Codex];

        let result = router.route(&config, &available).await;
        // Should fall through to default since matched backend not available
        assert_eq!(result, Some(BackendType::ClaudeCode));
    }

    #[tokio::test]
    async fn keyword_router_case_insensitive() {
        let router = KeywordRouter::new(BackendType::ClaudeCode)
            .rule("REVIEW", BackendType::GeminiCli);

        let config = SpawnConfig::new("reviewer", "review this code");
        let available = vec![BackendType::ClaudeCode, BackendType::GeminiCli];

        let result = router.route(&config, &available).await;
        assert_eq!(result, Some(BackendType::GeminiCli));
    }

    #[tokio::test]
    async fn keyword_router_returns_none_for_empty_available() {
        let router = KeywordRouter::new(BackendType::ClaudeCode);
        let config = SpawnConfig::new("worker", "Do something.");
        let result = router.route(&config, &[]).await;
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn capability_router_prefers_cheapest() {
        let router = CapabilityRouter::new()
            .cost_weight(1.0); // pure cost optimization

        let config = SpawnConfig::new("worker", "Do a simple task.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        let result = router.route(&config, &available).await;
        assert_eq!(result, Some(BackendType::GeminiCli)); // cost_tier=1
    }

    #[tokio::test]
    async fn capability_router_multi_turn_requirement() {
        let router = CapabilityRouter::new()
            .require_multi_turn(true)
            .cost_weight(1.0); // cheapest multi-turn

        let config = SpawnConfig::new("worker", "Multi-turn session.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        let result = router.route(&config, &available).await;
        // GeminiCli excluded (not multi-turn), Codex is cheaper than ClaudeCode
        assert_eq!(result, Some(BackendType::Codex));
    }

    #[tokio::test]
    async fn capability_router_prefers_fastest() {
        let router = CapabilityRouter::new()
            .cost_weight(0.0); // pure latency optimization

        let config = SpawnConfig::new("worker", "Quick task.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        let result = router.route(&config, &available).await;
        // ClaudeCode & Codex both latency_tier=2, ClaudeCode wins (first in available list)
        assert_eq!(result, Some(BackendType::ClaudeCode));
    }

    #[tokio::test]
    async fn capability_router_returns_none_for_empty_available() {
        let router = CapabilityRouter::new();
        let config = SpawnConfig::new("worker", "Do something.");
        let result = router.route(&config, &[]).await;
        assert_eq!(result, None);
    }

    // -----------------------------------------------------------------------
    // Word boundary tests
    // -----------------------------------------------------------------------

    #[test]
    fn contains_word_exact_match() {
        assert!(super::contains_word("review this code", "review"));
        assert!(super::contains_word("please review", "review"));
        assert!(super::contains_word("review", "review"));
    }

    #[test]
    fn contains_word_rejects_substring() {
        assert!(!super::contains_word("reviewing this code", "review"));
        assert!(!super::contains_word("code reviewer", "review"));
        assert!(!super::contains_word("prereview step", "review"));
    }

    #[test]
    fn contains_word_with_punctuation() {
        assert!(super::contains_word("please review, thanks", "review"));
        assert!(super::contains_word("review.", "review"));
        assert!(super::contains_word("(review)", "review"));
    }

    #[test]
    fn contains_word_test_vs_testing() {
        assert!(super::contains_word("test this function", "test"));
        assert!(!super::contains_word("testing this function", "test"));
        assert!(!super::contains_word("run the contest", "test"));
    }

    #[test]
    fn contains_word_edge_cases() {
        // Empty text / empty word
        assert!(!super::contains_word("", "review"));
        assert!(!super::contains_word("some text", ""));
        assert!(!super::contains_word("", ""));

        // Single character word
        assert!(super::contains_word("a quick task", "a"));
        assert!(!super::contains_word("analyze this", "a"));

        // Word at very end
        assert!(super::contains_word("do a test", "test"));

        // Multiple occurrences, only later one is a word
        assert!(super::contains_word("testing the test", "test"));

        // Hyphenated context (hyphen is not alphanumeric → boundary)
        assert!(super::contains_word("run unit-test now", "test"));

        // UTF-8 multi-byte: boundary check must not panic
        // "café test" — 'é' is 2 bytes (0xC3 0xA9), acts as word boundary
        assert!(super::contains_word("café test", "test"));
        assert!(super::contains_word("café", "café"));
        // 'é' before keyword — boundary check on multi-byte char must not panic
        assert!(!super::contains_word("acafé", "café"));
        // Non-ASCII word embedded with ASCII neighbors — ensure no mid-char slicing
        assert!(super::contains_word("aéb test éb", "éb"));
    }

    #[tokio::test]
    async fn keyword_router_word_boundary_mode() {
        let router = KeywordRouter::new(BackendType::ClaudeCode)
            .word_boundary(true)
            .rule("test", BackendType::Codex);

        let available = vec![BackendType::ClaudeCode, BackendType::Codex];

        // "test" as a whole word — should match
        let config = SpawnConfig::new("w", "test this function");
        assert_eq!(router.route(&config, &available).await, Some(BackendType::Codex));

        // "testing" contains "test" as substring but not as word — should NOT match
        let config = SpawnConfig::new("w", "testing this function");
        assert_eq!(router.route(&config, &available).await, Some(BackendType::ClaudeCode));
    }

    // -----------------------------------------------------------------------
    // ChainRouter tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn chain_router_first_match_wins() {
        let keyword = KeywordRouter::new(BackendType::ClaudeCode)
            .rule("review", BackendType::GeminiCli);
        let capability = CapabilityRouter::new().cost_weight(1.0);

        let router = ChainRouter::new().push(keyword).push(capability);

        let config = SpawnConfig::new("w", "review this code");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        // Keyword router matches "review" → GeminiCli
        assert_eq!(router.route(&config, &available).await, Some(BackendType::GeminiCli));
    }

    #[tokio::test]
    async fn chain_router_falls_through_to_second() {
        let keyword = KeywordRouter::new(BackendType::ClaudeCode)
            .word_boundary(true)
            .rule("review", BackendType::GeminiCli);
        let capability = CapabilityRouter::new().cost_weight(1.0);

        let router = ChainRouter::new().push(keyword).push(capability);

        // No keyword match → falls through to CapabilityRouter → cheapest = GeminiCli
        let config = SpawnConfig::new("w", "do a simple task");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        // KeywordRouter default is ClaudeCode which IS available, so it returns ClaudeCode
        // Actually, KeywordRouter falls back to its default which is ClaudeCode
        // So the chain stops at the first router that returns Some
        let result = router.route(&config, &available).await;
        assert_eq!(result, Some(BackendType::ClaudeCode));
    }

    #[tokio::test]
    async fn chain_router_empty_returns_none() {
        let router = ChainRouter::new();
        let config = SpawnConfig::new("w", "anything");
        let result = router.route(&config, &[BackendType::ClaudeCode]).await;
        assert_eq!(result, None);
    }

    // -----------------------------------------------------------------------
    // BackendCapability + Debug tests
    // -----------------------------------------------------------------------

    #[test]
    fn backend_capability_default() {
        let cap = BackendCapability::default();
        assert!(cap.multi_turn);
        assert!(cap.streaming);
        assert_eq!(cap.cost_tier, 2);
        assert_eq!(cap.latency_tier, 2);
    }

    #[test]
    fn capability_router_with_custom_capability() {
        let cap = BackendCapability {
            cost_tier: 1,
            ..Default::default()
        };
        assert!(cap.multi_turn);   // from default
        assert_eq!(cap.cost_tier, 1); // overridden
    }

    #[test]
    fn routers_are_debug() {
        let kw = KeywordRouter::new(BackendType::ClaudeCode).rule("test", BackendType::Codex);
        assert!(format!("{kw:?}").contains("KeywordRouter"));

        let cap = CapabilityRouter::new();
        assert!(format!("{cap:?}").contains("CapabilityRouter"));

        let chain = ChainRouter::new().push(KeywordRouter::new(BackendType::ClaudeCode));
        let debug = format!("{chain:?}");
        assert!(debug.contains("ChainRouter"));
        assert!(debug.contains("routers_count"));

        let smart = SmartRouter::new(BackendType::ClaudeCode);
        assert!(format!("{smart:?}").contains("SmartRouter"));
    }

    // -----------------------------------------------------------------------
    // SmartRouter tests
    // -----------------------------------------------------------------------

    #[test]
    fn smart_router_complexity_simple() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        let complexity = router.analyze_complexity("Fix the bug.");
        assert_eq!(complexity, PromptComplexity::Simple);
    }

    #[test]
    fn smart_router_complexity_medium_by_length() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        let prompt = "a".repeat(250); // > 200 chars
        let complexity = router.analyze_complexity(&prompt);
        assert_eq!(complexity, PromptComplexity::Medium);
    }

    #[test]
    fn smart_router_complexity_medium_by_code() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        let complexity = router.analyze_complexity("Please add fn main() here");
        assert_eq!(complexity, PromptComplexity::Medium);
    }

    #[test]
    fn smart_router_complexity_complex_by_length() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        let prompt = "a".repeat(900); // > 800 chars
        let complexity = router.analyze_complexity(&prompt);
        assert_eq!(complexity, PromptComplexity::Complex);
    }

    #[test]
    fn smart_router_complexity_complex_by_code_and_length() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        // Has code indicators AND >= simple_threshold
        let prompt = format!("Please implement this:\n```rust\nfn main() {{}}\n```\n{}", "x".repeat(200));
        let complexity = router.analyze_complexity(&prompt);
        assert_eq!(complexity, PromptComplexity::Complex);
    }

    #[test]
    fn smart_router_complexity_complex_by_paragraphs() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        let prompt = "First paragraph.\n\nSecond paragraph.\n\nThird paragraph.\n\nFourth paragraph.";
        let complexity = router.analyze_complexity(prompt);
        assert_eq!(complexity, PromptComplexity::Complex);
    }

    #[tokio::test]
    async fn smart_router_priority_wins() {
        let router = SmartRouter::new(BackendType::Codex)
            .priority("security audit", BackendType::ClaudeCode)
            .simple_backend(BackendType::GeminiCli);

        let config = SpawnConfig::new("w", "Run a security audit on this module");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        // Priority "security audit" matches → ClaudeCode
        assert_eq!(router.route(&config, &available).await, Some(BackendType::ClaudeCode));
    }

    #[tokio::test]
    async fn smart_router_complexity_routing_simple() {
        let router = SmartRouter::new(BackendType::Codex)
            .simple_backend(BackendType::GeminiCli);

        let config = SpawnConfig::new("w", "Fix the typo.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        // Short prompt → Simple → GeminiCli
        assert_eq!(router.route(&config, &available).await, Some(BackendType::GeminiCli));
    }

    #[tokio::test]
    async fn smart_router_complexity_routing_complex() {
        let router = SmartRouter::new(BackendType::Codex)
            .complex_backend(BackendType::ClaudeCode);

        let long_prompt = "a".repeat(900);
        let config = SpawnConfig::new("w", &long_prompt);
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        // Long prompt → Complex → ClaudeCode
        assert_eq!(router.route(&config, &available).await, Some(BackendType::ClaudeCode));
    }

    #[tokio::test]
    async fn smart_router_falls_back_to_capability() {
        // No priorities, no complexity mappings → falls through to capability router
        let router = SmartRouter::new(BackendType::Codex)
            .cost_weight(1.0); // cheapest wins

        let config = SpawnConfig::new("w", "Do a task.");
        let available = vec![BackendType::ClaudeCode, BackendType::Codex, BackendType::GeminiCli];

        // CapabilityRouter with cost_weight=1.0 picks cheapest → GeminiCli (cost_tier=1)
        assert_eq!(router.route(&config, &available).await, Some(BackendType::GeminiCli));
    }

    #[tokio::test]
    async fn smart_router_priority_skips_unavailable() {
        let router = SmartRouter::new(BackendType::Codex)
            .priority("audit", BackendType::ClaudeCode)
            .simple_backend(BackendType::GeminiCli);

        let config = SpawnConfig::new("w", "Run an audit");
        // ClaudeCode NOT available
        let available = vec![BackendType::Codex, BackendType::GeminiCli];

        // Priority matches but ClaudeCode unavailable → falls to complexity (Simple) → GeminiCli
        assert_eq!(router.route(&config, &available).await, Some(BackendType::GeminiCli));
    }

    #[tokio::test]
    async fn smart_router_returns_none_for_empty() {
        let router = SmartRouter::new(BackendType::ClaudeCode);
        let config = SpawnConfig::new("w", "anything");
        assert_eq!(router.route(&config, &[]).await, None);
    }

    #[tokio::test]
    async fn smart_router_default_fallback() {
        // No priorities, no complexity backends, capability returns None
        // (this shouldn't normally happen, but test the default path)
        let router = SmartRouter::new(BackendType::Codex);

        let config = SpawnConfig::new("w", "Short task.");
        let available = vec![BackendType::Codex];

        // No simple_backend set, capability picks Codex (only option), or default
        assert_eq!(router.route(&config, &available).await, Some(BackendType::Codex));
    }

    #[test]
    fn smart_router_custom_thresholds() {
        let router = SmartRouter::new(BackendType::ClaudeCode)
            .complexity_threshold(50, 300);

        // 60 chars = medium (>50, <300)
        assert_eq!(router.analyze_complexity(&"a".repeat(60)), PromptComplexity::Medium);
        // 30 chars = simple (<50)
        assert_eq!(router.analyze_complexity(&"a".repeat(30)), PromptComplexity::Simple);
        // 400 chars = complex (>300)
        assert_eq!(router.analyze_complexity(&"a".repeat(400)), PromptComplexity::Complex);
    }
}