roboticus-agent 0.11.3

Agent core with ReAct loop, policy engine, injection defense, memory system, and skill loader
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
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
use serde::{Deserialize, Serialize};

pub use roboticus_db::efficiency::{
    RecommendationModelStats as ModelStats, RecommendationUserProfile as UserProfile,
};

// ── Data types ────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RecommendationCategory {
    QueryCrafting,
    ModelSelection,
    SessionManagement,
    MemoryLeverage,
    CostOptimization,
    ToolUsage,
    Configuration,
}

impl RecommendationCategory {
    pub fn label(&self) -> &'static str {
        match self {
            Self::QueryCrafting => "Query Crafting",
            Self::ModelSelection => "Model Selection",
            Self::SessionManagement => "Session Management",
            Self::MemoryLeverage => "Memory Leverage",
            Self::CostOptimization => "Cost Optimization",
            Self::ToolUsage => "Tool Usage",
            Self::Configuration => "Configuration",
        }
    }

    pub fn icon(&self) -> &'static str {
        match self {
            Self::QueryCrafting => "pencil",
            Self::ModelSelection => "cpu",
            Self::SessionManagement => "chat",
            Self::MemoryLeverage => "memory",
            Self::CostOptimization => "dollar",
            Self::ToolUsage => "wrench",
            Self::Configuration => "gear",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
pub enum Priority {
    Low,
    Medium,
    High,
}

impl Priority {
    fn ordinal(&self) -> u8 {
        match self {
            Self::Low => 0,
            Self::Medium => 1,
            Self::High => 2,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Evidence {
    pub metric: String,
    pub value: String,
    pub context: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Impact {
    pub monthly_savings: Option<f64>,
    pub quality_change: Option<String>,
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Recommendation {
    pub category: RecommendationCategory,
    pub priority: Priority,
    pub title: String,
    pub explanation: String,
    pub action: String,
    pub evidence: Vec<Evidence>,
    pub estimated_impact: Option<Impact>,
}

// ── Rule trait ────────────────────────────────────────────────

pub trait RecommendationRule: Send + Sync {
    fn name(&self) -> &str;
    fn category(&self) -> RecommendationCategory;
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation>;
}

// ── Engine ────────────────────────────────────────────────────

pub struct RecommendationEngine {
    rules: Vec<Box<dyn RecommendationRule>>,
}

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

impl RecommendationEngine {
    pub fn new() -> Self {
        Self {
            rules: vec![
                Box::new(SpecificityCorrelation),
                Box::new(FollowUpPatterns),
                Box::new(ParetoOptimalModels),
                Box::new(ComplexityMismatch),
                Box::new(ModelStrengths),
                Box::new(SessionLengthSweet),
                Box::new(StaleSessionCost),
                Box::new(MemoryUnderutilized),
                Box::new(MemoryOverloaded),
                Box::new(SystemPromptROI),
                Box::new(CachingOpportunity),
                Box::new(ToolCostAwareness),
                Box::new(FallbackChainTuning),
                Box::new(HighCostPerTurn),
            ],
        }
    }

    pub fn generate(&self, profile: &UserProfile) -> Vec<Recommendation> {
        let mut recs: Vec<Recommendation> = self
            .rules
            .iter()
            .filter_map(|r| r.evaluate(profile))
            .collect();
        recs.sort_by(|a, b| b.priority.ordinal().cmp(&a.priority.ordinal()));
        recs
    }
}

// ── Query Crafting rules ──────────────────────────────────────

struct SpecificityCorrelation;

impl RecommendationRule for SpecificityCorrelation {
    fn name(&self) -> &str {
        "specificity_correlation"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::QueryCrafting
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 10 {
            return None;
        }
        if profile.avg_tokens_per_turn < 50.0 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::Medium,
                title: "Short queries may reduce response quality".into(),
                explanation: "Your average query is quite short. Longer, more specific prompts \
                    tend to produce higher-quality responses with fewer follow-up turns."
                    .into(),
                action: "Try including context, constraints, and desired format in your queries."
                    .into(),
                evidence: vec![Evidence {
                    metric: "avg_tokens_per_turn".into(),
                    value: format!("{:.0}", profile.avg_tokens_per_turn),
                    context: "tokens per user message (recommended: 80+)".into(),
                }],
                estimated_impact: Some(Impact {
                    monthly_savings: None,
                    quality_change: Some("Potential quality improvement".into()),
                    description: "More specific queries reduce back-and-forth turns".into(),
                }),
            })
        } else {
            None
        }
    }
}

struct FollowUpPatterns;

impl RecommendationRule for FollowUpPatterns {
    fn name(&self) -> &str {
        "follow_up_patterns"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::QueryCrafting
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_sessions < 3 {
            return None;
        }
        if profile.avg_session_length > 20.0 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::Medium,
                title: "Sessions with many turns may indicate unclear initial queries".into(),
                explanation: format!(
                    "Your sessions average {:.0} turns. Quality often degrades after 10-15 turns \
                     due to context window pressure. Starting fresh sessions with clear, complete \
                     instructions often yields better results.",
                    profile.avg_session_length
                ),
                action: "Consider starting new sessions instead of extending long conversations."
                    .into(),
                evidence: vec![Evidence {
                    metric: "avg_session_length".into(),
                    value: format!("{:.1}", profile.avg_session_length),
                    context: "average turns per session".into(),
                }],
                estimated_impact: None,
            })
        } else {
            None
        }
    }
}

// ── Model Selection rules ─────────────────────────────────────

struct ParetoOptimalModels;

impl RecommendationRule for ParetoOptimalModels {
    fn name(&self) -> &str {
        "pareto_optimal_models"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::ModelSelection
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.model_stats.len() < 2 {
            return None;
        }
        let mut dominated: Vec<(String, String)> = Vec::new();
        let models: Vec<(&String, &ModelStats)> = profile.model_stats.iter().collect();
        for (i, (name_a, stats_a)) in models.iter().enumerate() {
            for (name_b, stats_b) in models.iter().skip(i + 1) {
                if stats_b.avg_cost <= stats_a.avg_cost
                    && stats_b.avg_output_density >= stats_a.avg_output_density
                    && (stats_b.avg_cost < stats_a.avg_cost
                        || stats_b.avg_output_density > stats_a.avg_output_density)
                {
                    dominated.push(((*name_a).clone(), (*name_b).clone()));
                } else if stats_a.avg_cost <= stats_b.avg_cost
                    && stats_a.avg_output_density >= stats_b.avg_output_density
                    && (stats_a.avg_cost < stats_b.avg_cost
                        || stats_a.avg_output_density > stats_b.avg_output_density)
                {
                    dominated.push(((*name_b).clone(), (*name_a).clone()));
                }
            }
        }

        if dominated.is_empty() {
            return None;
        }

        let (worse, better) = &dominated[0];
        Some(Recommendation {
            category: self.category(),
            priority: Priority::High,
            title: format!("{worse} is dominated by {better} on cost/quality"),
            explanation: format!(
                "{better} is both cheaper and produces higher output density than {worse}. \
                 Consider consolidating traffic to the dominant model."
            ),
            action: format!("Route {worse} traffic to {better} for better cost-efficiency."),
            evidence: vec![
                Evidence {
                    metric: "dominated_model".into(),
                    value: worse.clone(),
                    context: "higher cost AND lower quality".into(),
                },
                Evidence {
                    metric: "dominant_model".into(),
                    value: better.clone(),
                    context: "lower cost AND higher quality".into(),
                },
            ],
            estimated_impact: profile.model_stats.get(worse).map(|s| Impact {
                monthly_savings: Some(s.avg_cost * s.turns as f64 * 0.3),
                quality_change: Some("quality improvement expected".into()),
                description: "Eliminate dominated model usage".into(),
            }),
        })
    }
}

struct ComplexityMismatch;

impl RecommendationRule for ComplexityMismatch {
    fn name(&self) -> &str {
        "complexity_mismatch"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::ModelSelection
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        let expensive_models: Vec<(&String, &ModelStats)> = profile
            .model_stats
            .iter()
            .filter(|(_, s)| s.avg_cost > 0.02 && s.avg_output_density < 0.15)
            .collect();

        if expensive_models.is_empty() {
            return None;
        }

        let (model, stats) = expensive_models[0];
        Some(Recommendation {
            category: self.category(),
            priority: Priority::High,
            title: format!("{model} may be overkill for simple queries"),
            explanation: format!(
                "{model} costs ${:.4}/turn but has low output density ({:.3}), suggesting \
                 queries may be too simple for this model tier.",
                stats.avg_cost, stats.avg_output_density
            ),
            action: "Route simpler queries to a lighter, cheaper model.".into(),
            evidence: vec![
                Evidence {
                    metric: "avg_cost".into(),
                    value: format!("${:.4}", stats.avg_cost),
                    context: format!("per turn for {model}"),
                },
                Evidence {
                    metric: "avg_output_density".into(),
                    value: format!("{:.3}", stats.avg_output_density),
                    context: "low density suggests simple queries".into(),
                },
            ],
            estimated_impact: Some(Impact {
                monthly_savings: Some(stats.avg_cost * stats.turns as f64 * 0.5),
                quality_change: Some("similar quality at lower cost".into()),
                description: "Switch simple queries to cheaper model".into(),
            }),
        })
    }
}

struct ModelStrengths;

impl RecommendationRule for ModelStrengths {
    fn name(&self) -> &str {
        "model_strengths"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::ModelSelection
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.models_used.len() < 2 || profile.total_turns < 20 {
            return None;
        }

        let mut best_density: Option<(&String, f64)> = None;
        let mut best_cost: Option<(&String, f64)> = None;

        for (name, stats) in &profile.model_stats {
            if stats.turns < 5 {
                continue;
            }
            match &best_density {
                None => best_density = Some((name, stats.avg_output_density)),
                Some((_, d)) if stats.avg_output_density > *d => {
                    best_density = Some((name, stats.avg_output_density));
                }
                _ => {}
            }
            match &best_cost {
                None => best_cost = Some((name, stats.avg_cost)),
                Some((_, c)) if stats.avg_cost < *c => {
                    best_cost = Some((name, stats.avg_cost));
                }
                _ => {}
            }
        }

        if let (Some((quality_model, _)), Some((cost_model, _))) = (&best_density, &best_cost)
            && quality_model != cost_model
        {
            return Some(Recommendation {
                category: self.category(),
                priority: Priority::Low,
                title: "Different models excel at different dimensions".into(),
                explanation: format!(
                    "{} produces the highest output density while {} is the most cost-efficient. \
                     Consider routing complex queries to the quality model and simple ones to \
                     the cost model.",
                    quality_model, cost_model
                ),
                action: "Implement complexity-based routing between models.".into(),
                evidence: vec![
                    Evidence {
                        metric: "best_quality_model".into(),
                        value: (*quality_model).clone(),
                        context: "highest output density".into(),
                    },
                    Evidence {
                        metric: "best_cost_model".into(),
                        value: (*cost_model).clone(),
                        context: "lowest cost per turn".into(),
                    },
                ],
                estimated_impact: None,
            });
        }
        None
    }
}

// ── Session Management rules ──────────────────────────────────

struct SessionLengthSweet;

impl RecommendationRule for SessionLengthSweet {
    fn name(&self) -> &str {
        "session_length_sweet"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::SessionManagement
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_sessions < 3 {
            return None;
        }
        if profile.avg_session_length > 15.0 && profile.avg_session_length <= 20.0 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::Low,
                title: "Sessions approaching optimal length ceiling".into(),
                explanation: format!(
                    "Average session length is {:.0} turns. Research suggests quality peaks around \
                     8-12 turns before context pressure degrades output.",
                    profile.avg_session_length
                ),
                action:
                    "Monitor quality in longer sessions and consider proactive session splitting."
                        .into(),
                evidence: vec![Evidence {
                    metric: "avg_session_length".into(),
                    value: format!("{:.1}", profile.avg_session_length),
                    context: "turns per session (sweet spot: 8-12)".into(),
                }],
                estimated_impact: None,
            })
        } else {
            None
        }
    }
}

struct StaleSessionCost;

impl RecommendationRule for StaleSessionCost {
    fn name(&self) -> &str {
        "stale_session_cost"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::SessionManagement
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_sessions < 5 || profile.avg_session_length <= 25.0 {
            return None;
        }
        let wasted_token_pct = (profile.avg_session_length - 12.0) / profile.avg_session_length;
        let estimated_waste = profile.total_cost * wasted_token_pct * 0.3;

        Some(Recommendation {
            category: self.category(),
            priority: Priority::High,
            title: "Long sessions accumulate expensive history tokens".into(),
            explanation: format!(
                "Sessions averaging {:.0} turns means each new turn carries ~{:.0}% \
                 redundant history context, driving up input token costs.",
                profile.avg_session_length,
                wasted_token_pct * 100.0
            ),
            action: "Enable automatic session archiving after 12-15 turns and start fresh.".into(),
            evidence: vec![
                Evidence {
                    metric: "avg_session_length".into(),
                    value: format!("{:.0}", profile.avg_session_length),
                    context: "turns per session".into(),
                },
                Evidence {
                    metric: "estimated_waste".into(),
                    value: format!("${:.4}", estimated_waste),
                    context: "estimated wasted cost on stale context".into(),
                },
            ],
            estimated_impact: Some(Impact {
                monthly_savings: Some(estimated_waste),
                quality_change: Some("quality may improve with fresh context".into()),
                description: "Reduce input token waste from stale history".into(),
            }),
        })
    }
}

// ── Memory Leverage rules ─────────────────────────────────────

struct MemoryUnderutilized;

impl RecommendationRule for MemoryUnderutilized {
    fn name(&self) -> &str {
        "memory_underutilized"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::MemoryLeverage
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 20 {
            return None;
        }
        if profile.memory_retrieval_rate < 0.2 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::Medium,
                title: "Memory system is underutilized".into(),
                explanation: format!(
                    "Only {:.0}% of turns retrieve stored memories. The memory system can reduce \
                     repetitive context and improve personalization.",
                    profile.memory_retrieval_rate * 100.0
                ),
                action:
                    "Store frequently referenced facts in semantic memory to reduce prompt repetition."
                        .into(),
                evidence: vec![Evidence {
                    metric: "memory_retrieval_rate".into(),
                    value: format!("{:.0}%", profile.memory_retrieval_rate * 100.0),
                    context: "percentage of turns using memory retrieval".into(),
                }],
                estimated_impact: Some(Impact {
                    monthly_savings: None,
                    quality_change: Some("better personalization and consistency".into()),
                    description: "Leverage memory for repeated context".into(),
                }),
            })
        } else {
            None
        }
    }
}

struct MemoryOverloaded;

impl RecommendationRule for MemoryOverloaded {
    fn name(&self) -> &str {
        "memory_overloaded"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::MemoryLeverage
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 20 {
            return None;
        }
        if profile.memory_retrieval_rate > 0.9 && profile.avg_tokens_per_turn > 2000.0 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::Medium,
                title: "Memory tokens may be crowding out conversation history".into(),
                explanation: format!(
                    "Memory is retrieved on {:.0}% of turns with an average of {:.0} tokens/turn. \
                     Excessive memory injection can crowd out useful conversation history.",
                    profile.memory_retrieval_rate * 100.0,
                    profile.avg_tokens_per_turn
                ),
                action:
                    "Review and prune stored memories; increase relevance threshold for retrieval."
                        .into(),
                evidence: vec![
                    Evidence {
                        metric: "memory_retrieval_rate".into(),
                        value: format!("{:.0}%", profile.memory_retrieval_rate * 100.0),
                        context: "memory retrieval rate".into(),
                    },
                    Evidence {
                        metric: "avg_tokens_per_turn".into(),
                        value: format!("{:.0}", profile.avg_tokens_per_turn),
                        context: "high token count may indicate memory bloat".into(),
                    },
                ],
                estimated_impact: Some(Impact {
                    monthly_savings: Some(profile.total_cost * 0.15),
                    quality_change: Some("better balance of memory vs history".into()),
                    description: "Reduce memory token overhead".into(),
                }),
            })
        } else {
            None
        }
    }
}

// ── Cost Optimization rules ───────────────────────────────────

struct SystemPromptROI;

impl RecommendationRule for SystemPromptROI {
    fn name(&self) -> &str {
        "system_prompt_roi"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::CostOptimization
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 10 || profile.avg_tokens_per_turn < 1500.0 {
            return None;
        }
        let system_cost_estimate = profile.total_cost * 0.3;
        Some(Recommendation {
            category: self.category(),
            priority: Priority::Medium,
            title: "Large input tokens suggest heavy system prompt".into(),
            explanation: format!(
                "Average input is {:.0} tokens/turn. If a large system prompt accounts for a \
                 significant portion, consider trimming non-essential instructions.",
                profile.avg_tokens_per_turn
            ),
            action: "Audit your system prompt for redundant instructions. Move static context \
                to memory retrieval."
                .into(),
            evidence: vec![Evidence {
                metric: "avg_tokens_per_turn".into(),
                value: format!("{:.0}", profile.avg_tokens_per_turn),
                context: "tokens per turn (system prompt is re-sent each turn)".into(),
            }],
            estimated_impact: Some(Impact {
                monthly_savings: Some(system_cost_estimate * 0.2),
                quality_change: None,
                description: "Reduce per-turn system prompt overhead".into(),
            }),
        })
    }
}

struct CachingOpportunity;

impl RecommendationRule for CachingOpportunity {
    fn name(&self) -> &str {
        "caching_opportunity"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::CostOptimization
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 10 {
            return None;
        }
        if profile.cache_hit_rate < 0.15 {
            let potential_savings = profile.total_cost * 0.2;
            Some(Recommendation {
                category: self.category(),
                priority: Priority::High,
                title: "Low cache hit rate — significant savings possible".into(),
                explanation: format!(
                    "Cache hit rate is only {:.1}%. Enabling or tuning semantic caching for \
                     repeated/similar queries could save ~20% of inference costs.",
                    profile.cache_hit_rate * 100.0
                ),
                action: "Enable semantic caching and review cache TTL settings.".into(),
                evidence: vec![Evidence {
                    metric: "cache_hit_rate".into(),
                    value: format!("{:.1}%", profile.cache_hit_rate * 100.0),
                    context: "current cache hit rate".into(),
                }],
                estimated_impact: Some(Impact {
                    monthly_savings: Some(potential_savings),
                    quality_change: None,
                    description: "Cache repeated queries to avoid redundant inference".into(),
                }),
            })
        } else {
            None
        }
    }
}

struct ToolCostAwareness;

impl RecommendationRule for ToolCostAwareness {
    fn name(&self) -> &str {
        "tool_cost_awareness"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::CostOptimization
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 10 {
            return None;
        }
        if profile.tool_success_rate < 0.7 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::Medium,
                title: "Tool calls have a high failure rate".into(),
                explanation: format!(
                    "Tool success rate is {:.0}%. Failed tool calls still cost tokens for the \
                     request and response. Improving tool reliability reduces wasted spend.",
                    profile.tool_success_rate * 100.0
                ),
                action:
                    "Review failing tool calls. Consider better error handling or input validation."
                        .into(),
                evidence: vec![Evidence {
                    metric: "tool_success_rate".into(),
                    value: format!("{:.0}%", profile.tool_success_rate * 100.0),
                    context: "tool call success rate".into(),
                }],
                estimated_impact: Some(Impact {
                    monthly_savings: Some(
                        profile.total_cost * (1.0 - profile.tool_success_rate) * 0.1,
                    ),
                    quality_change: Some("fewer errors, smoother interactions".into()),
                    description: "Reduce wasted inference from failed tool calls".into(),
                }),
            })
        } else {
            None
        }
    }
}

// ── Configuration rules ───────────────────────────────────────

struct FallbackChainTuning;

impl RecommendationRule for FallbackChainTuning {
    fn name(&self) -> &str {
        "fallback_chain_tuning"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::Configuration
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.models_used.len() < 2 || profile.total_turns < 20 {
            return None;
        }
        let primary = profile.models_used.first()?;
        let primary_stats = profile.model_stats.get(primary)?;
        let total_non_primary: i64 = profile
            .model_stats
            .iter()
            .filter(|(k, _)| *k != primary)
            .map(|(_, s)| s.turns)
            .sum();

        let fallback_rate = total_non_primary as f64 / profile.total_turns as f64;
        if fallback_rate > 0.3 {
            Some(Recommendation {
                category: self.category(),
                priority: Priority::High,
                title: format!("Primary model ({primary}) falls back {:.0}% of the time", fallback_rate * 100.0),
                explanation: format!(
                    "{:.0}% of turns use fallback models instead of {primary}. This suggests \
                     the primary provider may be unreliable or rate-limited.",
                    fallback_rate * 100.0
                ),
                action: "Check circuit breaker status; consider switching primary model or adding API key budget.".into(),
                evidence: vec![
                    Evidence {
                        metric: "primary_turns".into(),
                        value: format!("{}", primary_stats.turns),
                        context: format!("turns on {primary}"),
                    },
                    Evidence {
                        metric: "fallback_turns".into(),
                        value: format!("{total_non_primary}"),
                        context: "turns on fallback models".into(),
                    },
                ],
                estimated_impact: None,
            })
        } else {
            None
        }
    }
}

struct HighCostPerTurn;

impl RecommendationRule for HighCostPerTurn {
    fn name(&self) -> &str {
        "high_cost_per_turn"
    }
    fn category(&self) -> RecommendationCategory {
        RecommendationCategory::Configuration
    }
    fn evaluate(&self, profile: &UserProfile) -> Option<Recommendation> {
        if profile.total_turns < 5 {
            return None;
        }
        let avg_cost = profile.total_cost / profile.total_turns as f64;
        if avg_cost > 0.05 {
            Some(Recommendation {
                category: self.category(),
                priority: if avg_cost > 0.10 {
                    Priority::High
                } else {
                    Priority::Medium
                },
                title: format!("Average cost per turn is ${:.4}", avg_cost),
                explanation: format!(
                    "At ${:.4}/turn, your inference costs are above the typical threshold. \
                     Over {} turns, this totals ${:.2}.",
                    avg_cost, profile.total_turns, profile.total_cost
                ),
                action: "Review model selection, context window size, and caching settings.".into(),
                evidence: vec![
                    Evidence {
                        metric: "avg_cost_per_turn".into(),
                        value: format!("${:.4}", avg_cost),
                        context: "above $0.05/turn threshold".into(),
                    },
                    Evidence {
                        metric: "total_cost".into(),
                        value: format!("${:.4}", profile.total_cost),
                        context: format!("over {} turns", profile.total_turns),
                    },
                ],
                estimated_impact: Some(Impact {
                    monthly_savings: Some(profile.total_cost * 0.3),
                    quality_change: None,
                    description: "Reduce overall inference spend".into(),
                }),
            })
        } else {
            None
        }
    }
}

// ── LLM-powered deep analysis ──────────────────────────────────

pub struct LlmRecommendationAnalyzer;

impl LlmRecommendationAnalyzer {
    pub fn build_prompt(profile: &UserProfile, heuristic_recs: &[Recommendation]) -> String {
        let mut prompt = String::from(
            "You are an AI usage optimization expert. Analyze the following user profile and \
             heuristic recommendations, then provide deeper, actionable insights.\n\n",
        );

        prompt.push_str(&format!(
            "## User Profile\n\
             - Total sessions: {}\n\
             - Total turns: {}\n\
             - Total cost: ${:.4}\n\
             - Models used: {}\n\
             - Avg session length: {:.1} turns\n\
             - Avg tokens/turn: {:.0}\n\
             - Cache hit rate: {:.1}%\n\
             - Tool success rate: {:.1}%\n\n",
            profile.total_sessions,
            profile.total_turns,
            profile.total_cost,
            profile.models_used.join(", "),
            profile.avg_session_length,
            profile.avg_tokens_per_turn,
            profile.cache_hit_rate * 100.0,
            profile.tool_success_rate * 100.0,
        ));

        prompt.push_str("## Model Breakdown\n");
        for (name, stats) in &profile.model_stats {
            prompt.push_str(&format!(
                "- {name}: {turns} turns, ${cost:.4}/turn, density={density:.3}, cache={cache:.0}%\n",
                turns = stats.turns,
                cost = stats.avg_cost,
                density = stats.avg_output_density,
                cache = stats.cache_hit_rate * 100.0,
            ));
        }

        prompt.push_str("\n## Heuristic Recommendations Already Generated\n");
        for (i, rec) in heuristic_recs.iter().enumerate() {
            prompt.push_str(&format!(
                "{}. [{:?}] {}: {}\n",
                i + 1,
                rec.priority,
                rec.title,
                rec.explanation
            ));
        }

        prompt.push_str(
            "\n## Your Task\n\
             Provide 3-5 additional recommendations that go beyond the heuristics above. \
             Focus on:\n\
             1. Cross-cutting patterns the heuristics missed\n\
             2. Workflow optimizations specific to the model mix\n\
             3. Cost/quality trade-offs with concrete numbers\n\
             4. Configuration changes with expected impact\n\n\
             Format each recommendation as:\n\
             **Title**: ...\n\
             **Priority**: High/Medium/Low\n\
             **Explanation**: ...\n\
             **Action**: ...\n\
             **Expected Impact**: ...\n",
        );

        prompt
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    fn base_profile() -> UserProfile {
        UserProfile {
            total_sessions: 10,
            total_turns: 100,
            total_cost: 1.5,
            avg_quality: Some(0.8),
            grade_coverage: 0.5,
            models_used: vec!["claude-4".into(), "gpt-4".into()],
            model_stats: HashMap::from([
                (
                    "claude-4".into(),
                    ModelStats {
                        turns: 60,
                        avg_cost: 0.02,
                        avg_quality: Some(0.85),
                        cache_hit_rate: 0.3,
                        avg_output_density: 0.25,
                    },
                ),
                (
                    "gpt-4".into(),
                    ModelStats {
                        turns: 40,
                        avg_cost: 0.01,
                        avg_quality: Some(0.75),
                        cache_hit_rate: 0.4,
                        avg_output_density: 0.20,
                    },
                ),
            ]),
            avg_session_length: 10.0,
            avg_tokens_per_turn: 200.0,
            tool_success_rate: 0.9,
            cache_hit_rate: 0.35,
            memory_retrieval_rate: 0.5,
        }
    }

    #[test]
    fn engine_produces_sorted_recommendations() {
        let engine = RecommendationEngine::new();
        let mut profile = base_profile();
        profile.cache_hit_rate = 0.05;
        profile.avg_tokens_per_turn = 30.0;

        let recs = engine.generate(&profile);
        assert!(!recs.is_empty());

        for window in recs.windows(2) {
            assert!(
                window[0].priority.ordinal() >= window[1].priority.ordinal(),
                "recommendations not sorted by priority"
            );
        }
    }

    #[test]
    fn specificity_fires_for_short_queries() {
        let rule = SpecificityCorrelation;
        let mut profile = base_profile();
        profile.avg_tokens_per_turn = 25.0;
        assert!(rule.evaluate(&profile).is_some());

        profile.avg_tokens_per_turn = 150.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn follow_up_fires_for_long_sessions() {
        let rule = FollowUpPatterns;
        let mut profile = base_profile();
        profile.avg_session_length = 25.0;
        assert!(rule.evaluate(&profile).is_some());

        profile.avg_session_length = 5.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn caching_opportunity_fires_for_low_hit_rate() {
        let rule = CachingOpportunity;
        let mut profile = base_profile();
        profile.cache_hit_rate = 0.05;
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some());
        assert_eq!(rec.unwrap().priority, Priority::High);

        profile.cache_hit_rate = 0.5;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn high_cost_fires_above_threshold() {
        let rule = HighCostPerTurn;
        let mut profile = base_profile();
        profile.total_cost = 15.0;
        profile.total_turns = 100;
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some());
        assert_eq!(rec.unwrap().priority, Priority::High);
    }

    #[test]
    fn high_cost_silent_below_threshold() {
        let rule = HighCostPerTurn;
        let mut profile = base_profile();
        profile.total_cost = 1.0;
        profile.total_turns = 100;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn pareto_detects_dominated_model() {
        let rule = ParetoOptimalModels;
        let mut profile = base_profile();
        profile.model_stats.insert(
            "expensive-bad".into(),
            ModelStats {
                turns: 20,
                avg_cost: 0.05,
                avg_quality: None,
                cache_hit_rate: 0.1,
                avg_output_density: 0.10,
            },
        );
        profile.model_stats.insert(
            "cheap-good".into(),
            ModelStats {
                turns: 20,
                avg_cost: 0.01,
                avg_quality: None,
                cache_hit_rate: 0.5,
                avg_output_density: 0.30,
            },
        );
        assert!(rule.evaluate(&profile).is_some());
    }

    #[test]
    fn tool_cost_fires_for_low_success() {
        let rule = ToolCostAwareness;
        let mut profile = base_profile();
        profile.tool_success_rate = 0.5;
        assert!(rule.evaluate(&profile).is_some());

        profile.tool_success_rate = 0.95;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn fallback_fires_for_high_rate() {
        let rule = FallbackChainTuning;
        let mut profile = base_profile();
        profile.model_stats.get_mut("gpt-4").unwrap().turns = 80;
        profile.model_stats.get_mut("claude-4").unwrap().turns = 20;
        profile.total_turns = 100;
        assert!(rule.evaluate(&profile).is_some());
    }

    #[test]
    fn stale_session_fires_for_long_sessions() {
        let rule = StaleSessionCost;
        let mut profile = base_profile();
        profile.avg_session_length = 30.0;
        assert!(rule.evaluate(&profile).is_some());

        profile.avg_session_length = 8.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn memory_underutilized_fires() {
        let rule = MemoryUnderutilized;
        let mut profile = base_profile();
        profile.memory_retrieval_rate = 0.05;
        assert!(rule.evaluate(&profile).is_some());

        profile.memory_retrieval_rate = 0.6;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn llm_prompt_contains_profile_data() {
        let profile = base_profile();
        let recs = RecommendationEngine::new().generate(&profile);
        let prompt = LlmRecommendationAnalyzer::build_prompt(&profile, &recs);
        assert!(prompt.contains("Total sessions: 10"));
        assert!(prompt.contains("claude-4"));
        assert!(prompt.contains("Your Task"));
    }

    #[test]
    fn tool_cost_fires_for_zero_success_rate() {
        let rule = ToolCostAwareness;
        let mut profile = base_profile();
        profile.tool_success_rate = 0.0;
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some(), "0% tool success should trigger the rule");
        let rec = rec.unwrap();
        assert!(rec.explanation.contains("0%"));
    }

    #[test]
    fn tool_cost_silent_for_high_success() {
        let rule = ToolCostAwareness;
        let mut profile = base_profile();
        profile.tool_success_rate = 0.85;
        assert!(
            rule.evaluate(&profile).is_none(),
            "85% success rate should not trigger"
        );
    }

    #[test]
    fn tool_cost_silent_for_insufficient_data() {
        let rule = ToolCostAwareness;
        let mut profile = base_profile();
        profile.total_turns = 5;
        profile.tool_success_rate = 0.0;
        assert!(
            rule.evaluate(&profile).is_none(),
            "should not fire with < 10 turns"
        );
    }

    #[test]
    fn engine_no_recs_for_minimal_profile() {
        let engine = RecommendationEngine::new();
        let profile = UserProfile {
            total_sessions: 1,
            total_turns: 2,
            total_cost: 0.001,
            avg_quality: None,
            grade_coverage: 0.0,
            models_used: vec!["test".into()],
            model_stats: HashMap::from([(
                "test".into(),
                ModelStats {
                    turns: 2,
                    avg_cost: 0.0005,
                    avg_quality: None,
                    cache_hit_rate: 0.0,
                    avg_output_density: 0.3,
                },
            )]),
            avg_session_length: 2.0,
            avg_tokens_per_turn: 100.0,
            tool_success_rate: 1.0,
            cache_hit_rate: 0.5,
            memory_retrieval_rate: 0.5,
        };
        let recs = engine.generate(&profile);
        assert!(recs.is_empty(), "minimal profile should produce no recs");
    }

    // ── Coverage for RecommendationCategory label / icon ─────────

    #[test]
    fn category_label_covers_all_variants() {
        assert_eq!(
            RecommendationCategory::QueryCrafting.label(),
            "Query Crafting"
        );
        assert_eq!(
            RecommendationCategory::ModelSelection.label(),
            "Model Selection"
        );
        assert_eq!(
            RecommendationCategory::SessionManagement.label(),
            "Session Management"
        );
        assert_eq!(
            RecommendationCategory::MemoryLeverage.label(),
            "Memory Leverage"
        );
        assert_eq!(
            RecommendationCategory::CostOptimization.label(),
            "Cost Optimization"
        );
        assert_eq!(RecommendationCategory::ToolUsage.label(), "Tool Usage");
        assert_eq!(
            RecommendationCategory::Configuration.label(),
            "Configuration"
        );
    }

    #[test]
    fn category_icon_covers_all_variants() {
        assert_eq!(RecommendationCategory::QueryCrafting.icon(), "pencil");
        assert_eq!(RecommendationCategory::ModelSelection.icon(), "cpu");
        assert_eq!(RecommendationCategory::SessionManagement.icon(), "chat");
        assert_eq!(RecommendationCategory::MemoryLeverage.icon(), "memory");
        assert_eq!(RecommendationCategory::CostOptimization.icon(), "dollar");
        assert_eq!(RecommendationCategory::ToolUsage.icon(), "wrench");
        assert_eq!(RecommendationCategory::Configuration.icon(), "gear");
    }

    // ── Coverage for SpecificityCorrelation edge cases ────────────

    #[test]
    fn specificity_silent_for_insufficient_data() {
        let rule = SpecificityCorrelation;
        let mut profile = base_profile();
        profile.total_turns = 5;
        profile.avg_tokens_per_turn = 10.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn specificity_name_and_category() {
        let rule = SpecificityCorrelation;
        assert_eq!(rule.name(), "specificity_correlation");
        assert_eq!(rule.category(), RecommendationCategory::QueryCrafting);
    }

    // ── Coverage for FollowUpPatterns edge cases ─────────────────

    #[test]
    fn follow_up_silent_for_insufficient_sessions() {
        let rule = FollowUpPatterns;
        let mut profile = base_profile();
        profile.total_sessions = 2;
        profile.avg_session_length = 30.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn follow_up_name_and_category() {
        let rule = FollowUpPatterns;
        assert_eq!(rule.name(), "follow_up_patterns");
        assert_eq!(rule.category(), RecommendationCategory::QueryCrafting);
    }

    // ── Coverage for ParetoOptimalModels edge cases ──────────────

    #[test]
    fn pareto_silent_for_single_model() {
        let rule = ParetoOptimalModels;
        let mut profile = base_profile();
        profile.model_stats.clear();
        profile.model_stats.insert(
            "only-model".into(),
            ModelStats {
                turns: 50,
                avg_cost: 0.02,
                avg_quality: None,
                cache_hit_rate: 0.3,
                avg_output_density: 0.25,
            },
        );
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn pareto_silent_when_no_domination() {
        let rule = ParetoOptimalModels;
        let mut profile = base_profile();
        profile.model_stats.clear();
        // model-a: cheaper but lower density
        profile.model_stats.insert(
            "model-a".into(),
            ModelStats {
                turns: 20,
                avg_cost: 0.01,
                avg_quality: None,
                cache_hit_rate: 0.3,
                avg_output_density: 0.10,
            },
        );
        // model-b: more expensive but higher density (trade-off, no domination)
        profile.model_stats.insert(
            "model-b".into(),
            ModelStats {
                turns: 20,
                avg_cost: 0.05,
                avg_quality: None,
                cache_hit_rate: 0.3,
                avg_output_density: 0.30,
            },
        );
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn pareto_name_and_category() {
        let rule = ParetoOptimalModels;
        assert_eq!(rule.name(), "pareto_optimal_models");
        assert_eq!(rule.category(), RecommendationCategory::ModelSelection);
    }

    // ── Coverage for ComplexityMismatch ───────────────────────────

    #[test]
    fn complexity_mismatch_fires_for_expensive_low_density() {
        let rule = ComplexityMismatch;
        let mut profile = base_profile();
        profile.model_stats.insert(
            "over-powered".into(),
            ModelStats {
                turns: 30,
                avg_cost: 0.03,
                avg_quality: None,
                cache_hit_rate: 0.2,
                avg_output_density: 0.10,
            },
        );
        let rec = rule.evaluate(&profile);
        assert!(
            rec.is_some(),
            "expensive model with low density should trigger"
        );
        let rec = rec.unwrap();
        assert_eq!(rec.priority, Priority::High);
        assert!(rec.title.contains("over-powered"));
    }

    #[test]
    fn complexity_mismatch_silent_for_cheap_models() {
        let rule = ComplexityMismatch;
        let mut profile = base_profile();
        profile.model_stats.clear();
        profile.model_stats.insert(
            "cheap".into(),
            ModelStats {
                turns: 30,
                avg_cost: 0.005,
                avg_quality: None,
                cache_hit_rate: 0.2,
                avg_output_density: 0.10,
            },
        );
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn complexity_mismatch_name_and_category() {
        let rule = ComplexityMismatch;
        assert_eq!(rule.name(), "complexity_mismatch");
        assert_eq!(rule.category(), RecommendationCategory::ModelSelection);
    }

    // ── Coverage for ModelStrengths ───────────────────────────────

    #[test]
    fn model_strengths_fires_when_different_best_models() {
        let rule = ModelStrengths;
        let mut profile = base_profile();
        profile.total_turns = 50;
        profile.models_used = vec!["quality-model".into(), "cost-model".into()];
        profile.model_stats.clear();
        profile.model_stats.insert(
            "quality-model".into(),
            ModelStats {
                turns: 25,
                avg_cost: 0.05,
                avg_quality: Some(0.9),
                cache_hit_rate: 0.3,
                avg_output_density: 0.40,
            },
        );
        profile.model_stats.insert(
            "cost-model".into(),
            ModelStats {
                turns: 25,
                avg_cost: 0.005,
                avg_quality: Some(0.7),
                cache_hit_rate: 0.3,
                avg_output_density: 0.15,
            },
        );
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some(), "different best models should trigger");
        let rec = rec.unwrap();
        assert_eq!(rec.priority, Priority::Low);
        assert!(rec.explanation.contains("quality-model"));
        assert!(rec.explanation.contains("cost-model"));
    }

    #[test]
    fn model_strengths_silent_for_single_model() {
        let rule = ModelStrengths;
        let mut profile = base_profile();
        profile.models_used = vec!["only-one".into()];
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn model_strengths_silent_for_few_turns() {
        let rule = ModelStrengths;
        let mut profile = base_profile();
        profile.total_turns = 10;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn model_strengths_name_and_category() {
        let rule = ModelStrengths;
        assert_eq!(rule.name(), "model_strengths");
        assert_eq!(rule.category(), RecommendationCategory::ModelSelection);
    }

    // ── Coverage for SessionLengthSweet ───────────────────────────

    #[test]
    fn session_length_sweet_fires_in_range() {
        let rule = SessionLengthSweet;
        let mut profile = base_profile();
        profile.avg_session_length = 18.0;
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some(), "session length 15-20 should trigger");
        assert_eq!(rec.unwrap().priority, Priority::Low);
    }

    #[test]
    fn session_length_sweet_silent_outside_range() {
        let rule = SessionLengthSweet;
        let mut profile = base_profile();
        profile.avg_session_length = 10.0;
        assert!(rule.evaluate(&profile).is_none());

        profile.avg_session_length = 25.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn session_length_sweet_silent_for_few_sessions() {
        let rule = SessionLengthSweet;
        let mut profile = base_profile();
        profile.total_sessions = 2;
        profile.avg_session_length = 18.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn session_length_sweet_name_and_category() {
        let rule = SessionLengthSweet;
        assert_eq!(rule.name(), "session_length_sweet");
        assert_eq!(rule.category(), RecommendationCategory::SessionManagement);
    }

    // ── Coverage for StaleSessionCost ─────────────────────────────

    #[test]
    fn stale_session_name_and_category() {
        let rule = StaleSessionCost;
        assert_eq!(rule.name(), "stale_session_cost");
        assert_eq!(rule.category(), RecommendationCategory::SessionManagement);
    }

    #[test]
    fn stale_session_silent_for_few_sessions() {
        let rule = StaleSessionCost;
        let mut profile = base_profile();
        profile.total_sessions = 3;
        profile.avg_session_length = 30.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    // ── Coverage for MemoryUnderutilized ──────────────────────────

    #[test]
    fn memory_underutilized_silent_for_few_turns() {
        let rule = MemoryUnderutilized;
        let mut profile = base_profile();
        profile.total_turns = 10;
        profile.memory_retrieval_rate = 0.05;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn memory_underutilized_name_and_category() {
        let rule = MemoryUnderutilized;
        assert_eq!(rule.name(), "memory_underutilized");
        assert_eq!(rule.category(), RecommendationCategory::MemoryLeverage);
    }

    // ── Coverage for MemoryOverloaded ─────────────────────────────

    #[test]
    fn memory_overloaded_fires_when_crowding() {
        let rule = MemoryOverloaded;
        let mut profile = base_profile();
        profile.total_turns = 30;
        profile.memory_retrieval_rate = 0.95;
        profile.avg_tokens_per_turn = 3000.0;
        let rec = rule.evaluate(&profile);
        assert!(
            rec.is_some(),
            "high memory retrieval + high tokens should trigger"
        );
        let rec = rec.unwrap();
        assert_eq!(rec.priority, Priority::Medium);
        assert!(rec.explanation.contains("95%"));
    }

    #[test]
    fn memory_overloaded_silent_when_balanced() {
        let rule = MemoryOverloaded;
        let mut profile = base_profile();
        profile.total_turns = 30;
        profile.memory_retrieval_rate = 0.5;
        profile.avg_tokens_per_turn = 500.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn memory_overloaded_silent_for_few_turns() {
        let rule = MemoryOverloaded;
        let mut profile = base_profile();
        profile.total_turns = 10;
        profile.memory_retrieval_rate = 0.95;
        profile.avg_tokens_per_turn = 3000.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn memory_overloaded_name_and_category() {
        let rule = MemoryOverloaded;
        assert_eq!(rule.name(), "memory_overloaded");
        assert_eq!(rule.category(), RecommendationCategory::MemoryLeverage);
    }

    // ── Coverage for SystemPromptROI ──────────────────────────────

    #[test]
    fn system_prompt_roi_fires_for_heavy_prompts() {
        let rule = SystemPromptROI;
        let mut profile = base_profile();
        profile.total_turns = 50;
        profile.avg_tokens_per_turn = 2000.0;
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some(), "high tokens/turn should trigger");
        let rec = rec.unwrap();
        assert_eq!(rec.priority, Priority::Medium);
        assert!(rec.explanation.contains("2000"));
    }

    #[test]
    fn system_prompt_roi_silent_for_low_tokens() {
        let rule = SystemPromptROI;
        let mut profile = base_profile();
        profile.total_turns = 50;
        profile.avg_tokens_per_turn = 500.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn system_prompt_roi_silent_for_few_turns() {
        let rule = SystemPromptROI;
        let mut profile = base_profile();
        profile.total_turns = 5;
        profile.avg_tokens_per_turn = 2000.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn system_prompt_roi_name_and_category() {
        let rule = SystemPromptROI;
        assert_eq!(rule.name(), "system_prompt_roi");
        assert_eq!(rule.category(), RecommendationCategory::CostOptimization);
    }

    // ── Coverage for CachingOpportunity ───────────────────────────

    #[test]
    fn caching_opportunity_name_and_category() {
        let rule = CachingOpportunity;
        assert_eq!(rule.name(), "caching_opportunity");
        assert_eq!(rule.category(), RecommendationCategory::CostOptimization);
    }

    #[test]
    fn caching_opportunity_silent_for_few_turns() {
        let rule = CachingOpportunity;
        let mut profile = base_profile();
        profile.total_turns = 5;
        profile.cache_hit_rate = 0.01;
        assert!(rule.evaluate(&profile).is_none());
    }

    // ── Coverage for ToolCostAwareness ────────────────────────────

    #[test]
    fn tool_cost_name_and_category() {
        let rule = ToolCostAwareness;
        assert_eq!(rule.name(), "tool_cost_awareness");
        assert_eq!(rule.category(), RecommendationCategory::CostOptimization);
    }

    // ── Coverage for FallbackChainTuning ──────────────────────────

    #[test]
    fn fallback_chain_name_and_category() {
        let rule = FallbackChainTuning;
        assert_eq!(rule.name(), "fallback_chain_tuning");
        assert_eq!(rule.category(), RecommendationCategory::Configuration);
    }

    #[test]
    fn fallback_silent_for_single_model() {
        let rule = FallbackChainTuning;
        let mut profile = base_profile();
        profile.models_used = vec!["only-one".into()];
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn fallback_silent_for_few_turns() {
        let rule = FallbackChainTuning;
        let mut profile = base_profile();
        profile.total_turns = 10;
        assert!(rule.evaluate(&profile).is_none());
    }

    #[test]
    fn fallback_silent_for_low_fallback_rate() {
        let rule = FallbackChainTuning;
        let mut profile = base_profile();
        profile.total_turns = 100;
        // 10% fallback rate — below 30% threshold
        profile.model_stats.get_mut("claude-4").unwrap().turns = 90;
        profile.model_stats.get_mut("gpt-4").unwrap().turns = 10;
        assert!(rule.evaluate(&profile).is_none());
    }

    // ── Coverage for HighCostPerTurn ──────────────────────────────

    #[test]
    fn high_cost_name_and_category() {
        let rule = HighCostPerTurn;
        assert_eq!(rule.name(), "high_cost_per_turn");
        assert_eq!(rule.category(), RecommendationCategory::Configuration);
    }

    #[test]
    fn high_cost_medium_priority_between_thresholds() {
        let rule = HighCostPerTurn;
        let mut profile = base_profile();
        // avg_cost = 8.0/100 = 0.08 (above 0.05 but below 0.10 -> Medium)
        profile.total_cost = 8.0;
        profile.total_turns = 100;
        let rec = rule.evaluate(&profile);
        assert!(rec.is_some());
        assert_eq!(rec.unwrap().priority, Priority::Medium);
    }

    #[test]
    fn high_cost_silent_for_few_turns() {
        let rule = HighCostPerTurn;
        let mut profile = base_profile();
        profile.total_turns = 3;
        profile.total_cost = 100.0;
        assert!(rule.evaluate(&profile).is_none());
    }

    // ── Priority ordinal coverage ────────────────────────────────

    #[test]
    fn priority_ordinal_all_variants() {
        assert_eq!(Priority::Low.ordinal(), 0);
        assert_eq!(Priority::Medium.ordinal(), 1);
        assert_eq!(Priority::High.ordinal(), 2);
    }

    // ── Engine default trait ──────────────────────────────────────

    #[test]
    fn engine_default_same_as_new() {
        let engine = RecommendationEngine::default();
        let profile = base_profile();
        let recs = engine.generate(&profile);
        // Just verify it works; same as new()
        let _ = recs;
    }
}