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
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
use crate::engine::{
agenda::{ActivationGroupManager, AgendaManager},
analytics::RuleAnalytics,
facts::Facts,
knowledge_base::KnowledgeBase,
plugin::{PluginConfig, PluginInfo, PluginManager, PluginStats},
workflow::WorkflowEngine,
};
use crate::errors::{Result, RuleEngineError};
use crate::types::{ActionType, Operator, Value};
use chrono::{DateTime, Utc};
use log::info;
use std::collections::HashMap;
use std::time::{Duration, Instant};
/// Type for custom function implementations
pub type CustomFunction = Box<dyn Fn(&[Value], &Facts) -> Result<Value> + Send + Sync>;
/// Type for custom action handlers
pub type ActionHandler = Box<dyn Fn(&HashMap<String, Value>, &Facts) -> Result<()> + Send + Sync>;
/// Configuration options for the rule engine
#[derive(Debug, Clone)]
pub struct EngineConfig {
/// Maximum number of execution cycles
pub max_cycles: usize,
/// Execution timeout
pub timeout: Option<Duration>,
/// Enable performance statistics collection
pub enable_stats: bool,
/// Enable debug mode with verbose logging
pub debug_mode: bool,
}
impl Default for EngineConfig {
fn default() -> Self {
Self {
max_cycles: 100,
timeout: Some(Duration::from_secs(30)),
enable_stats: true,
debug_mode: false,
}
}
}
/// Result of rule engine execution
#[derive(Debug, Clone)]
pub struct GruleExecutionResult {
/// Number of execution cycles
pub cycle_count: usize,
/// Number of rules evaluated
pub rules_evaluated: usize,
/// Number of rules that fired
pub rules_fired: usize,
/// Total execution time
pub execution_time: Duration,
}
/// Rust Rule Engine - High-performance rule execution engine
pub struct RustRuleEngine {
knowledge_base: KnowledgeBase,
config: EngineConfig,
custom_functions: HashMap<String, CustomFunction>,
action_handlers: HashMap<String, ActionHandler>,
analytics: Option<RuleAnalytics>,
agenda_manager: AgendaManager,
activation_group_manager: ActivationGroupManager,
/// Track rules that have fired globally (for no-loop support)
fired_rules_global: std::collections::HashSet<String>,
/// Workflow engine for rule chaining and sequential execution
workflow_engine: WorkflowEngine,
/// Plugin manager for extensible functionality
plugin_manager: PluginManager,
}
#[allow(dead_code)]
impl RustRuleEngine {
/// Execute all rules and call callback when a rule is fired
pub fn execute_with_callback<F>(
&mut self,
facts: &Facts,
mut on_rule_fired: F,
) -> Result<GruleExecutionResult>
where
F: FnMut(&str, &Facts),
{
use chrono::Utc;
let timestamp = Utc::now();
let start_time = std::time::Instant::now();
let mut cycle_count = 0;
let mut rules_evaluated = 0;
let mut rules_fired = 0;
self.sync_workflow_agenda_activations();
for cycle in 0..self.config.max_cycles {
cycle_count = cycle + 1;
let mut any_rule_fired = false;
let mut fired_rules_in_cycle = std::collections::HashSet::new();
self.activation_group_manager.reset_cycle();
if let Some(timeout) = self.config.timeout {
if start_time.elapsed() > timeout {
return Err(crate::errors::RuleEngineError::EvaluationError {
message: "Execution timeout exceeded".to_string(),
});
}
}
let rule_indices = self.knowledge_base.get_rules_by_salience();
for &rule_index in &rule_indices {
if let Some(rule) = self.knowledge_base.get_rule_by_index(rule_index) {
if !rule.enabled {
continue;
}
if !self.agenda_manager.should_evaluate_rule(&rule) {
continue;
}
if !rule.is_active_at(timestamp) {
continue;
}
if !self.agenda_manager.can_fire_rule(&rule) {
continue;
}
if !self.activation_group_manager.can_fire(&rule) {
continue;
}
if rule.no_loop && self.fired_rules_global.contains(&rule.name) {
continue;
}
rules_evaluated += 1;
let condition_result = self.evaluate_conditions(&rule.conditions, facts)?;
if condition_result {
for action in &rule.actions {
self.execute_action(action, facts)?;
}
rules_fired += 1;
any_rule_fired = true;
fired_rules_in_cycle.insert(rule.name.clone());
if rule.no_loop {
self.fired_rules_global.insert(rule.name.clone());
}
self.agenda_manager.mark_rule_fired(&rule);
self.activation_group_manager.mark_fired(&rule);
on_rule_fired(&rule.name, facts);
}
}
}
if !any_rule_fired {
break;
}
self.sync_workflow_agenda_activations();
}
let execution_time = start_time.elapsed();
Ok(crate::engine::GruleExecutionResult {
cycle_count,
rules_evaluated,
rules_fired,
execution_time,
})
}
/// Create a new RustRuleEngine with default configuration
pub fn new(knowledge_base: KnowledgeBase) -> Self {
Self {
knowledge_base,
config: EngineConfig::default(),
custom_functions: HashMap::new(),
action_handlers: HashMap::new(),
analytics: None,
agenda_manager: AgendaManager::new(),
activation_group_manager: ActivationGroupManager::new(),
fired_rules_global: std::collections::HashSet::new(),
workflow_engine: WorkflowEngine::new(),
plugin_manager: PluginManager::with_default_config(),
}
}
/// Create a new RustRuleEngine with custom configuration
pub fn with_config(knowledge_base: KnowledgeBase, config: EngineConfig) -> Self {
Self {
knowledge_base,
config,
custom_functions: HashMap::new(),
action_handlers: HashMap::new(),
analytics: None,
agenda_manager: AgendaManager::new(),
activation_group_manager: ActivationGroupManager::new(),
fired_rules_global: std::collections::HashSet::new(),
workflow_engine: WorkflowEngine::new(),
plugin_manager: PluginManager::with_default_config(),
}
}
/// Register a custom function
pub fn register_function<F>(&mut self, name: &str, func: F)
where
F: Fn(&[Value], &Facts) -> Result<Value> + Send + Sync + 'static,
{
self.custom_functions
.insert(name.to_string(), Box::new(func));
}
/// Register a custom action handler
pub fn register_action_handler<F>(&mut self, action_type: &str, handler: F)
where
F: Fn(&HashMap<String, Value>, &Facts) -> Result<()> + Send + Sync + 'static,
{
self.action_handlers
.insert(action_type.to_string(), Box::new(handler));
}
/// Enable analytics with custom configuration
pub fn enable_analytics(&mut self, analytics: RuleAnalytics) {
self.analytics = Some(analytics);
}
/// Reset global no-loop tracking (useful for testing or when facts change significantly)
pub fn reset_no_loop_tracking(&mut self) {
self.fired_rules_global.clear();
}
/// Disable analytics
pub fn disable_analytics(&mut self) {
self.analytics = None;
}
/// Get reference to analytics data
pub fn analytics(&self) -> Option<&RuleAnalytics> {
self.analytics.as_ref()
}
/// Enable debug mode for detailed execution logging
pub fn set_debug_mode(&mut self, enabled: bool) {
self.config.debug_mode = enabled;
}
/// Check if a custom function is registered
pub fn has_function(&self, name: &str) -> bool {
self.custom_functions.contains_key(name)
}
/// Check if a custom action handler is registered
pub fn has_action_handler(&self, action_type: &str) -> bool {
self.action_handlers.contains_key(action_type)
}
/// Get ready scheduled tasks
pub fn get_ready_tasks(&mut self) -> Vec<crate::engine::workflow::ScheduledTask> {
self.workflow_engine.get_ready_tasks()
}
/// Execute scheduled tasks that are ready
pub fn execute_scheduled_tasks(&mut self, facts: &Facts) -> Result<()> {
let ready_tasks = self.get_ready_tasks();
for task in ready_tasks {
if let Some(rule) = self.knowledge_base.get_rule(&task.rule_name) {
if self.config.debug_mode {
println!("⚡ Executing scheduled task: {}", task.rule_name);
}
// Execute just this one rule if conditions match
if self.evaluate_conditions(&rule.conditions, facts)? {
for action in &rule.actions {
self.execute_action(action, facts)?;
}
}
}
}
Ok(())
}
/// Activate agenda group
pub fn activate_agenda_group(&mut self, group: String) {
self.workflow_engine.activate_agenda_group(group.clone());
self.agenda_manager.set_focus(&group);
}
/// Get the knowledge base
pub fn knowledge_base(&self) -> &KnowledgeBase {
&self.knowledge_base
}
/// Get mutable reference to knowledge base
pub fn knowledge_base_mut(&mut self) -> &mut KnowledgeBase {
&mut self.knowledge_base
}
/// Sync workflow engine agenda activations with agenda manager
fn sync_workflow_agenda_activations(&mut self) {
// Process any pending agenda activations from workflow engine
while let Some(agenda_group) = self.workflow_engine.get_next_pending_agenda_activation() {
if self.config.debug_mode {
println!("🔄 Syncing workflow agenda activation: {}", agenda_group);
}
self.agenda_manager.set_focus(&agenda_group);
}
}
/// Set focus to a specific agenda group
pub fn set_agenda_focus(&mut self, group: &str) {
self.agenda_manager.set_focus(group);
}
/// Get the currently active agenda group
pub fn get_active_agenda_group(&self) -> &str {
self.agenda_manager.get_active_group()
}
/// Pop the agenda focus stack
pub fn pop_agenda_focus(&mut self) -> Option<String> {
self.agenda_manager.pop_focus()
}
/// Clear all agenda focus and return to MAIN
pub fn clear_agenda_focus(&mut self) {
self.agenda_manager.clear_focus();
}
/// Get all agenda groups that have rules
pub fn get_agenda_groups(&self) -> Vec<String> {
self.agenda_manager
.get_agenda_groups(&self.knowledge_base.get_rules())
}
/// Get all activation groups that have rules
pub fn get_activation_groups(&self) -> Vec<String> {
self.activation_group_manager
.get_activation_groups(&self.knowledge_base.get_rules())
}
// 🔄 Workflow Engine Methods
/// Start a new workflow
pub fn start_workflow(&mut self, workflow_name: Option<String>) -> String {
self.workflow_engine.start_workflow(workflow_name)
}
/// Get workflow statistics
pub fn get_workflow_stats(&self) -> crate::engine::workflow::WorkflowStats {
self.workflow_engine.get_workflow_stats()
}
/// Get workflow state by ID
pub fn get_workflow(
&self,
workflow_id: &str,
) -> Option<&crate::engine::workflow::WorkflowState> {
self.workflow_engine.get_workflow(workflow_id)
}
/// Clean up completed workflows
pub fn cleanup_completed_workflows(&mut self, older_than: Duration) {
self.workflow_engine.cleanup_completed_workflows(older_than);
}
/// Execute workflow step by activating specific agenda group
pub fn execute_workflow_step(
&mut self,
agenda_group: &str,
facts: &Facts,
) -> Result<GruleExecutionResult> {
// Set agenda focus to the specific group
self.set_agenda_focus(agenda_group);
// Execute rules in that group
let result = self.execute(facts)?;
// Process any workflow actions that were triggered
self.process_workflow_actions(facts)?;
Ok(result)
}
/// Execute a complete workflow by processing agenda groups sequentially
pub fn execute_workflow(
&mut self,
agenda_groups: Vec<&str>,
facts: &Facts,
) -> Result<crate::engine::workflow::WorkflowResult> {
let start_time = Instant::now();
let mut total_steps = 0;
if self.config.debug_mode {
println!(
"🔄 Starting workflow execution with {} steps",
agenda_groups.len()
);
}
for (i, group) in agenda_groups.iter().enumerate() {
if self.config.debug_mode {
println!("📋 Executing workflow step {}: {}", i + 1, group);
}
let step_result = self.execute_workflow_step(group, facts)?;
total_steps += 1;
if step_result.rules_fired == 0 {
if self.config.debug_mode {
println!("⏸️ No rules fired in step '{}', stopping workflow", group);
}
break;
}
}
let execution_time = start_time.elapsed();
Ok(crate::engine::workflow::WorkflowResult::success(
total_steps,
execution_time,
))
}
/// Process workflow-related actions and scheduled tasks
fn process_workflow_actions(&mut self, facts: &Facts) -> Result<()> {
// Process agenda group activations
while let Some(group) = self.workflow_engine.get_next_agenda_group() {
self.set_agenda_focus(&group);
}
// Process scheduled tasks
let ready_tasks = self.workflow_engine.get_ready_tasks();
for task in ready_tasks {
if self.config.debug_mode {
println!("⚡ Executing scheduled task: {}", task.rule_name);
}
// Find and execute the specific rule
if let Some(rule) = self.knowledge_base.get_rule(&task.rule_name) {
// Execute just this one rule
if self.evaluate_conditions(&rule.conditions, facts)? {
for action in &rule.actions {
self.execute_action(action, facts)?;
}
}
}
}
Ok(())
}
/// Execute all rules in the knowledge base against the given facts
pub fn execute(&mut self, facts: &Facts) -> Result<GruleExecutionResult> {
self.execute_at_time(facts, Utc::now())
}
/// Execute all rules at a specific timestamp (for date-effective/expires testing)
pub fn execute_at_time(
&mut self,
facts: &Facts,
timestamp: DateTime<Utc>,
) -> Result<GruleExecutionResult> {
let start_time = Instant::now();
let mut cycle_count = 0;
let mut rules_evaluated = 0;
let mut rules_fired = 0;
// Process any pending agenda group activations from workflow engine
self.sync_workflow_agenda_activations();
if self.config.debug_mode {
println!(
"🚀 Starting rule execution with {} rules (agenda group: {})",
self.knowledge_base.rule_count(),
self.agenda_manager.get_active_group()
);
}
for cycle in 0..self.config.max_cycles {
cycle_count = cycle + 1;
let mut any_rule_fired = false;
let mut fired_rules_in_cycle = std::collections::HashSet::new();
// Reset activation groups for each cycle
self.activation_group_manager.reset_cycle();
// Check for timeout
if let Some(timeout) = self.config.timeout {
if start_time.elapsed() > timeout {
return Err(RuleEngineError::EvaluationError {
message: "Execution timeout exceeded".to_string(),
});
}
}
// Get rule indices sorted by salience (highest first) - avoids cloning rules
let rule_indices = self.knowledge_base.get_rules_by_salience();
// Process rules by index to avoid cloning
for &rule_index in &rule_indices {
if let Some(rule) = self.knowledge_base.get_rule_by_index(rule_index) {
if !rule.enabled {
continue;
}
if !self.agenda_manager.should_evaluate_rule(&rule) {
continue;
}
// Check date effective/expires
if !rule.is_active_at(timestamp) {
continue;
}
// Check agenda group constraints (lock-on-active)
if !self.agenda_manager.can_fire_rule(&rule) {
continue;
}
// Check activation group constraints (only one rule per group can fire)
if !self.activation_group_manager.can_fire(&rule) {
continue;
}
// Check no-loop: skip if already fired in this execution cycle
if rule.no_loop && self.fired_rules_global.contains(&rule.name) {
println!("⛔ Skipping '{}' due to no_loop (already fired)", rule.name);
continue;
}
// Debug
if self.config.debug_mode {
println!(
"🔍 Checking rule '{}' (no_loop: {})",
rule.name, rule.no_loop
);
}
let rule_start = std::time::Instant::now();
// Count rule evaluation
rules_evaluated += 1;
// Evaluate rule conditions
let condition_result = self.evaluate_conditions(&rule.conditions, facts)?;
if self.config.debug_mode {
println!(
" Rule '{}' condition result: {}",
rule.name, condition_result
);
}
// If conditions match, fire the rule
if condition_result {
if self.config.debug_mode {
println!(
"🔥 Firing rule '{}' (salience: {})",
rule.name, rule.salience
);
}
// Execute actions
for action in &rule.actions {
self.execute_action(action, facts)?;
}
let rule_duration = rule_start.elapsed();
// Record analytics if enabled
if let Some(analytics) = &mut self.analytics {
analytics.record_execution(
&rule.name,
rule_duration,
true,
true,
None,
0,
);
}
rules_fired += 1;
any_rule_fired = true;
// Track that this rule fired in this cycle (for cycle counting)
fired_rules_in_cycle.insert(rule.name.clone());
// Track that this rule fired globally (for no-loop support)
if rule.no_loop {
self.fired_rules_global.insert(rule.name.clone());
if self.config.debug_mode {
println!(" 🔒 Marked '{}' as fired (no_loop tracking)", rule.name);
}
}
// Mark rule as fired for agenda and activation group management
self.agenda_manager.mark_rule_fired(&rule);
self.activation_group_manager.mark_fired(&rule);
} else {
let rule_duration = rule_start.elapsed();
// Record analytics for failed rules too
if let Some(analytics) = &mut self.analytics {
analytics.record_execution(
&rule.name,
rule_duration,
false,
false,
None,
0,
);
}
}
} // Close if let Some(rule)
}
// If no rules fired in this cycle, we're done
if !any_rule_fired {
break;
}
// Sync any new workflow agenda activations at the end of each cycle
self.sync_workflow_agenda_activations();
}
let execution_time = start_time.elapsed();
Ok(GruleExecutionResult {
cycle_count,
rules_evaluated,
rules_fired,
execution_time,
})
}
/// Evaluate conditions against facts
fn evaluate_conditions(
&self,
conditions: &crate::engine::rule::ConditionGroup,
facts: &Facts,
) -> Result<bool> {
use crate::engine::pattern_matcher::PatternMatcher;
use crate::engine::rule::ConditionGroup;
match conditions {
ConditionGroup::Single(condition) => self.evaluate_single_condition(condition, facts),
ConditionGroup::Compound {
left,
operator,
right,
} => {
let left_result = self.evaluate_conditions(left, facts)?;
let right_result = self.evaluate_conditions(right, facts)?;
match operator {
crate::types::LogicalOperator::And => Ok(left_result && right_result),
crate::types::LogicalOperator::Or => Ok(left_result || right_result),
crate::types::LogicalOperator::Not => Err(RuleEngineError::EvaluationError {
message: "NOT operator should not appear in compound conditions"
.to_string(),
}),
}
}
ConditionGroup::Not(condition) => {
let result = self.evaluate_conditions(condition, facts)?;
Ok(!result)
}
// Pattern matching conditions
ConditionGroup::Exists(condition) => {
Ok(PatternMatcher::evaluate_exists(condition, facts))
}
ConditionGroup::Forall(condition) => {
Ok(PatternMatcher::evaluate_forall(condition, facts))
}
ConditionGroup::Accumulate {
result_var,
source_pattern,
extract_field,
source_conditions,
function,
function_arg,
} => {
// Evaluate accumulate and inject result into facts
self.evaluate_accumulate(
result_var,
source_pattern,
extract_field,
source_conditions,
function,
function_arg,
facts,
)?;
// After injecting result, return true to continue
Ok(true)
}
#[cfg(feature = "streaming")]
ConditionGroup::StreamPattern { .. } => {
// Stream patterns are handled by the streaming engine, not here
// For forward chaining context, return true to allow rule evaluation
Ok(true)
}
}
}
/// Evaluate accumulate condition and inject result into facts
#[allow(clippy::too_many_arguments)]
fn evaluate_accumulate(
&self,
_result_var: &str,
source_pattern: &str,
extract_field: &str,
source_conditions: &[String],
function: &str,
_function_arg: &str,
facts: &Facts,
) -> Result<()> {
use crate::rete::accumulate::*;
// 1. Collect all facts matching the source pattern
let all_facts = facts.get_all_facts();
let mut matching_values = Vec::new();
// Find all facts that match the pattern (e.g., "Order.amount", "Order.status")
let pattern_prefix = format!("{}.", source_pattern);
// Group facts by instance (e.g., Order.1.amount, Order.1.status) - pre-sized for performance
let mut instances: HashMap<String, HashMap<String, Value>> = HashMap::with_capacity(16);
for (key, value) in &all_facts {
if key.starts_with(&pattern_prefix) {
// Extract instance ID if present (e.g., "Order.1.amount" -> "1")
let parts: Vec<&str> = key
.strip_prefix(&pattern_prefix)
.unwrap()
.split('.')
.collect();
if parts.len() >= 2 {
// Has instance ID: Order.1.amount
let instance_id = parts[0];
let field_name = parts[1..].join(".");
instances
.entry(instance_id.to_string())
.or_default()
.insert(field_name, value.clone());
} else if parts.len() == 1 {
// No instance ID: Order.amount (single instance)
instances
.entry("default".to_string())
.or_default()
.insert(parts[0].to_string(), value.clone());
}
}
}
// 2. Filter instances by source conditions
for (_instance_id, instance_facts) in instances {
// Check if this instance matches all source conditions
let mut matches = true;
for condition_str in source_conditions {
// Parse condition: "status == \"completed\""
if !self.evaluate_condition_string(condition_str, &instance_facts) {
matches = false;
break;
}
}
if matches {
// Extract the field value
if let Some(value) = instance_facts.get(extract_field) {
matching_values.push(value.clone());
}
}
}
// 3. Run accumulate function
let result = match function {
"sum" => {
let mut state = SumFunction.init();
for value in &matching_values {
state.accumulate(&self.value_to_fact_value(value));
}
self.fact_value_to_value(&state.get_result())
}
"count" => {
let mut state = CountFunction.init();
for value in &matching_values {
state.accumulate(&self.value_to_fact_value(value));
}
self.fact_value_to_value(&state.get_result())
}
"average" | "avg" => {
let mut state = AverageFunction.init();
for value in &matching_values {
state.accumulate(&self.value_to_fact_value(value));
}
self.fact_value_to_value(&state.get_result())
}
"min" => {
let mut state = MinFunction.init();
for value in &matching_values {
state.accumulate(&self.value_to_fact_value(value));
}
self.fact_value_to_value(&state.get_result())
}
"max" => {
let mut state = MaxFunction.init();
for value in &matching_values {
state.accumulate(&self.value_to_fact_value(value));
}
self.fact_value_to_value(&state.get_result())
}
_ => {
return Err(RuleEngineError::EvaluationError {
message: format!("Unknown accumulate function: {}", function),
});
}
};
// 4. Inject result into facts
// Use pattern.function as key to avoid collision
let result_key = format!("{}.{}", source_pattern, function);
facts.set(&result_key, result);
if self.config.debug_mode {
println!(
" 🧮 Accumulate result: {} = {:?}",
result_key,
facts.get(&result_key)
);
}
Ok(())
}
/// Helper: Convert Value to FactValue
fn value_to_fact_value(&self, value: &Value) -> crate::rete::facts::FactValue {
use crate::rete::facts::FactValue;
match value {
Value::Integer(i) => FactValue::Integer(*i),
Value::Number(n) => FactValue::Float(*n),
Value::String(s) => FactValue::String(s.clone()),
Value::Boolean(b) => FactValue::Boolean(*b),
_ => FactValue::String(value.to_string()),
}
}
/// Helper: Convert FactValue to Value
fn fact_value_to_value(&self, fact_value: &crate::rete::facts::FactValue) -> Value {
use crate::rete::facts::FactValue;
match fact_value {
FactValue::Integer(i) => Value::Integer(*i),
FactValue::Float(f) => Value::Number(*f),
FactValue::String(s) => Value::String(s.clone()),
FactValue::Boolean(b) => Value::Boolean(*b),
FactValue::Array(_) => Value::String(format!("{:?}", fact_value)),
FactValue::Null => Value::String("null".to_string()),
}
}
/// Helper: Evaluate a condition string against facts
fn evaluate_condition_string(&self, condition: &str, facts: &HashMap<String, Value>) -> bool {
// Simple condition parser: "field == value" or "field != value", etc.
let condition = condition.trim();
// Try to parse operator
let operators = ["==", "!=", ">=", "<=", ">", "<"];
for op in &operators {
if let Some(pos) = condition.find(op) {
let field = condition[..pos].trim();
let value_str = condition[pos + op.len()..]
.trim()
.trim_matches('"')
.trim_matches('\'');
if let Some(field_value) = facts.get(field) {
return self.compare_values(field_value, op, value_str);
} else {
return false;
}
}
}
false
}
/// Helper: Compare values
fn compare_values(&self, field_value: &Value, operator: &str, value_str: &str) -> bool {
match field_value {
Value::String(s) => match operator {
"==" => s == value_str,
"!=" => s != value_str,
_ => false,
},
Value::Integer(i) => {
if let Ok(num) = value_str.parse::<i64>() {
match operator {
"==" => *i == num,
"!=" => *i != num,
">" => *i > num,
"<" => *i < num,
">=" => *i >= num,
"<=" => *i <= num,
_ => false,
}
} else {
false
}
}
Value::Number(n) => {
if let Ok(num) = value_str.parse::<f64>() {
match operator {
"==" => (*n - num).abs() < f64::EPSILON,
"!=" => (*n - num).abs() >= f64::EPSILON,
">" => *n > num,
"<" => *n < num,
">=" => *n >= num,
"<=" => *n <= num,
_ => false,
}
} else {
false
}
}
Value::Boolean(b) => {
if let Ok(bool_val) = value_str.parse::<bool>() {
match operator {
"==" => *b == bool_val,
"!=" => *b != bool_val,
_ => false,
}
} else {
false
}
}
_ => false,
}
}
/// Evaluate rule conditions - wrapper for evaluate_conditions for compatibility
fn evaluate_rule_conditions(
&self,
rule: &crate::engine::rule::Rule,
facts: &Facts,
) -> Result<bool> {
self.evaluate_conditions(&rule.conditions, facts)
}
/// Check if a fact object has been retracted
fn is_retracted(&self, object_name: &str, facts: &Facts) -> bool {
let retract_key = format!("_retracted_{}", object_name);
matches!(facts.get(&retract_key), Some(Value::Boolean(true)))
}
/// Evaluate a single condition
fn evaluate_single_condition(
&self,
condition: &crate::engine::rule::Condition,
facts: &Facts,
) -> Result<bool> {
use crate::engine::rule::ConditionExpression;
let result = match &condition.expression {
ConditionExpression::Field(field_name) => {
// Check if the fact object has been retracted
// Extract object name from field (e.g., "Session.expired" -> "Session")
if let Some(object_name) = field_name.split('.').next() {
if self.is_retracted(object_name, facts) {
if self.config.debug_mode {
println!(" 🗑️ Skipping retracted fact: {}", object_name);
}
return Ok(false);
}
}
// Field condition - try nested first, then flat lookup
// If field not found, treat as Null for proper null checking
let field_value = facts
.get_nested(field_name)
.or_else(|| facts.get(field_name))
.unwrap_or(Value::Null);
if self.config.debug_mode {
println!(
" 🔎 Evaluating field condition: {} {} {:?}",
field_name,
format!("{:?}", condition.operator).to_lowercase(),
condition.value
);
println!(" Field value: {:?}", field_value);
}
// condition.operator.evaluate(&value, &condition.value)
// If the condition's right-hand value is a string that names another fact,
// try to resolve that fact and use its value for comparison. This allows
// rules like `L1 > L1Min` where the parser may have stored "L1Min"
// as a string literal.
let rhs = match &condition.value {
crate::types::Value::String(s) => {
// Try nested lookup first, then flat lookup
facts
.get_nested(s)
.or_else(|| facts.get(s))
.unwrap_or(crate::types::Value::String(s.clone()))
}
crate::types::Value::Expression(expr) => {
// Try to evaluate expression - could be a variable reference or arithmetic
match crate::expression::evaluate_expression(expr, facts) {
Ok(evaluated) => evaluated,
Err(_) => {
// If evaluation fails, try as simple variable lookup
facts
.get_nested(expr)
.or_else(|| facts.get(expr))
.unwrap_or(crate::types::Value::Expression(expr.clone()))
}
}
}
_ => condition.value.clone(),
};
if self.config.debug_mode {
println!(" Resolved RHS for comparison: {:?}", rhs);
}
condition.operator.evaluate(&field_value, &rhs)
}
ConditionExpression::FunctionCall { name, args } => {
// Function call condition
if self.config.debug_mode {
println!(
" 🔎 Evaluating function condition: {}({:?}) {} {:?}",
name,
args,
format!("{:?}", condition.operator).to_lowercase(),
condition.value
);
}
if let Some(function) = self.custom_functions.get(name) {
// Resolve arguments from facts
let arg_values: Vec<Value> = args
.iter()
.map(|arg| {
facts
.get_nested(arg)
.or_else(|| facts.get(arg))
.unwrap_or(Value::String(arg.clone()))
})
.collect();
// Call the function
match function(&arg_values, facts) {
Ok(result_value) => {
if self.config.debug_mode {
println!(" Function result: {:?}", result_value);
}
condition.operator.evaluate(&result_value, &condition.value)
}
Err(e) => {
if self.config.debug_mode {
println!(" Function error: {}", e);
}
false
}
}
} else {
if self.config.debug_mode {
println!(" Function '{}' not found", name);
}
false
}
}
ConditionExpression::Test { name, args } => {
// Test CE condition - expects boolean result
if self.config.debug_mode {
println!(" 🧪 Evaluating test CE: test({}({:?}))", name, args);
}
// Check if name is a registered custom function
if let Some(function) = self.custom_functions.get(name) {
// Resolve arguments from facts
let arg_values: Vec<Value> = args
.iter()
.map(|arg| {
let resolved = facts
.get_nested(arg)
.or_else(|| facts.get(arg))
.unwrap_or(Value::String(arg.clone()));
if self.config.debug_mode {
println!(" Resolving arg '{}' -> {:?}", arg, resolved);
}
resolved
})
.collect();
// Call the function
match function(&arg_values, facts) {
Ok(result_value) => {
if self.config.debug_mode {
println!(" Test result: {:?}", result_value);
}
// Test CE expects boolean result directly
match result_value {
Value::Boolean(b) => b,
Value::Integer(i) => i != 0,
Value::Number(f) => f != 0.0,
Value::String(s) => !s.is_empty(),
_ => false,
}
}
Err(e) => {
if self.config.debug_mode {
println!(" Test function error: {}", e);
}
false
}
}
} else {
// Not a custom function - try to evaluate as arithmetic expression
// Format: "User.Age % 3 == 0" where name is the full expression
if self.config.debug_mode {
println!(
" Trying to evaluate '{}' as arithmetic expression",
name
);
}
// Try to parse and evaluate the expression
match self.evaluate_arithmetic_condition(name, facts) {
Ok(result) => {
if self.config.debug_mode {
println!(" Arithmetic expression result: {}", result);
}
result
}
Err(e) => {
if self.config.debug_mode {
println!(" Failed to evaluate expression: {}", e);
println!(" Test function '{}' not found", name);
}
false
}
}
}
}
ConditionExpression::MultiField {
field,
operation,
variable: _,
} => {
// Multi-field operation condition
if self.config.debug_mode {
println!(" 📦 Evaluating multi-field: {}.{}", field, operation);
}
// Get the field value
let field_value = facts.get_nested(field).or_else(|| facts.get(field));
if let Some(value) = field_value {
match operation.as_str() {
"empty" => {
matches!(value, Value::Array(arr) if arr.is_empty())
}
"not_empty" => {
matches!(value, Value::Array(arr) if !arr.is_empty())
}
"count" => {
if let Value::Array(arr) = value {
let count = Value::Integer(arr.len() as i64);
condition.operator.evaluate(&count, &condition.value)
} else {
false
}
}
"contains" => {
// Use existing contains operator
condition.operator.evaluate(&value, &condition.value)
}
_ => {
// Other operations (collect, first, last) not fully supported yet
// Return true to not block rule evaluation
if self.config.debug_mode {
println!(
" ⚠️ Operation '{}' not fully implemented yet",
operation
);
}
true
}
}
} else {
false
}
}
};
if self.config.debug_mode {
println!(" Result: {}", result);
}
Ok(result)
}
/// Execute an action
fn execute_action(&mut self, action: &ActionType, facts: &Facts) -> Result<()> {
match action {
ActionType::Set { field, value } => {
// Evaluate expression if value is an Expression
let evaluated_value = match value {
Value::Expression(expr) => {
// Evaluate the expression with current facts
crate::expression::evaluate_expression(expr, facts)?
}
_ => value.clone(),
};
// Try nested first, then fall back to flat key setting
if facts.set_nested(field, evaluated_value.clone()).is_err() {
// If nested fails, use flat key
facts.set(field, evaluated_value.clone());
}
if self.config.debug_mode {
println!(" ✅ Set {field} = {evaluated_value:?}");
}
}
ActionType::Log { message } => {
println!("📋 LOG: {}", message);
}
ActionType::MethodCall {
object,
method,
args,
} => {
let result = self.execute_method_call(object, method, args, facts)?;
if self.config.debug_mode {
println!(" 🔧 Called {object}.{method}({args:?}) -> {result}");
}
}
ActionType::Retract { object } => {
if self.config.debug_mode {
println!(" 🗑️ Retracted {object}");
}
// Mark fact as retracted in working memory
facts.set(&format!("_retracted_{}", object), Value::Boolean(true));
}
ActionType::Custom {
action_type,
params,
} => {
if let Some(handler) = self.action_handlers.get(action_type) {
if self.config.debug_mode {
println!(
" 🎯 Executing custom action: {action_type} with params: {params:?}"
);
}
// Resolve parameter values from facts
let resolved_params = self.resolve_action_parameters(params, facts)?;
// Execute the registered handler
handler(&resolved_params, facts)?;
} else {
if self.config.debug_mode {
println!(" ⚠️ No handler registered for custom action: {action_type}");
println!(
" Available handlers: {:?}",
self.action_handlers.keys().collect::<Vec<_>>()
);
}
// Return error if no handler found
return Err(RuleEngineError::EvaluationError {
message: format!(
"No action handler registered for '{action_type}'. Use engine.register_action_handler() to add custom action handlers."
),
});
}
}
// 🔄 Workflow Actions
ActionType::ActivateAgendaGroup { group } => {
if self.config.debug_mode {
println!(" 🎯 Activating agenda group: {}", group);
}
// Sync with both workflow engine and agenda manager immediately
self.workflow_engine.activate_agenda_group(group.clone());
self.agenda_manager.set_focus(group);
}
ActionType::ScheduleRule {
rule_name,
delay_ms,
} => {
if self.config.debug_mode {
println!(
" ⏰ Scheduling rule '{}' to execute in {}ms",
rule_name, delay_ms
);
}
self.workflow_engine
.schedule_rule(rule_name.clone(), *delay_ms, None);
}
ActionType::CompleteWorkflow { workflow_name } => {
if self.config.debug_mode {
println!(" ✅ Completing workflow: {}", workflow_name);
}
self.workflow_engine
.complete_workflow(workflow_name.clone());
}
ActionType::SetWorkflowData { key, value } => {
if self.config.debug_mode {
println!(" 💾 Setting workflow data: {} = {:?}", key, value);
}
// For now, we'll use a default workflow ID. Later this could be enhanced
// to track current workflow context
let workflow_id = "default_workflow";
self.workflow_engine
.set_workflow_data(workflow_id, key.clone(), value.clone());
}
ActionType::Append { field, value } => {
// Evaluate expression if value is an Expression
let evaluated_value = match value {
Value::Expression(expr) => crate::expression::evaluate_expression(expr, facts)?,
_ => value.clone(),
};
// Get current array or create new one
let current_value = facts.get(field);
let mut array = match current_value {
Some(Value::Array(arr)) => arr.clone(),
Some(_) => {
// Field exists but is not an array, create new array
if self.config.debug_mode {
println!(" ⚠️ Field {} is not an array, creating new array", field);
}
Vec::new()
}
None => Vec::new(),
};
// Append value
array.push(evaluated_value.clone());
// Set the updated array (try nested first, then flat)
if facts
.set_nested(field, Value::Array(array.clone()))
.is_err()
{
facts.set(field, Value::Array(array.clone()));
}
if self.config.debug_mode {
println!(" ➕ Appended to {}: {:?}", field, evaluated_value);
}
}
}
Ok(())
}
/// Evaluate arithmetic condition like "User.Age % 3 == 0"
fn evaluate_arithmetic_condition(&self, expr: &str, facts: &Facts) -> Result<bool> {
// Parse expression format: "left_expr operator right_value"
// e.g., "User.Age % 3 == 0" or "User.Price * 2 > 100"
let operators = [">=", "<=", "==", "!=", ">", "<"];
let mut split_pos = None;
let mut found_op = "";
for op in &operators {
if let Some(pos) = expr.rfind(op) {
split_pos = Some(pos);
found_op = op;
break;
}
}
if split_pos.is_none() {
return Err(RuleEngineError::EvaluationError {
message: format!("No comparison operator found in expression: {}", expr),
});
}
let pos = split_pos.unwrap();
let left_expr = expr[..pos].trim();
let right_value = expr[pos + found_op.len()..].trim();
// Evaluate left side arithmetic expression
let left_result = crate::expression::evaluate_expression(left_expr, facts)?;
// Parse right value
let right_val = if let Ok(i) = right_value.parse::<i64>() {
Value::Integer(i)
} else if let Ok(f) = right_value.parse::<f64>() {
Value::Number(f)
} else {
// Try to evaluate as expression or get from facts
match crate::expression::evaluate_expression(right_value, facts) {
Ok(v) => v,
Err(_) => Value::String(right_value.to_string()),
}
};
// Compare values
let operator =
Operator::from_str(found_op).ok_or_else(|| RuleEngineError::InvalidOperator {
operator: found_op.to_string(),
})?;
Ok(operator.evaluate(&left_result, &right_val))
}
/// Execute function call
fn execute_function_call(
&self,
function: &str,
args: &[Value],
facts: &Facts,
) -> Result<String> {
let function_lower = function.to_lowercase();
// Handle built-in utility functions
match function_lower.as_str() {
"log" | "print" | "println" => self.handle_log_function(args),
"update" | "refresh" => self.handle_update_function(args),
"now" | "timestamp" => self.handle_timestamp_function(),
"random" => self.handle_random_function(args),
"format" | "sprintf" => self.handle_format_function(args),
"length" | "size" | "count" => self.handle_length_function(args),
"sum" | "add" => self.handle_sum_function(args),
"max" | "maximum" => self.handle_max_function(args),
"min" | "minimum" => self.handle_min_function(args),
"avg" | "average" => self.handle_average_function(args),
"round" => self.handle_round_function(args),
"floor" => self.handle_floor_function(args),
"ceil" | "ceiling" => self.handle_ceil_function(args),
"abs" | "absolute" => self.handle_abs_function(args),
"contains" | "includes" => self.handle_contains_function(args),
"startswith" | "begins_with" => self.handle_starts_with_function(args),
"endswith" | "ends_with" => self.handle_ends_with_function(args),
"lowercase" | "tolower" => self.handle_lowercase_function(args),
"uppercase" | "toupper" => self.handle_uppercase_function(args),
"trim" | "strip" => self.handle_trim_function(args),
"split" => self.handle_split_function(args),
"join" => self.handle_join_function(args),
_ => {
// Try to call custom user-defined function
self.handle_custom_function(function, args, facts)
}
}
}
/// Handle logging functions (log, print, println)
fn handle_log_function(&self, args: &[Value]) -> Result<String> {
let message = if args.is_empty() {
"".to_string()
} else if args.len() == 1 {
args[0].to_string()
} else {
args.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" ")
};
info!("📋 {}", message);
Ok(message)
}
/// Handle update/refresh functions
fn handle_update_function(&self, args: &[Value]) -> Result<String> {
if let Some(arg) = args.first() {
Ok(format!("Updated: {}", arg.to_string()))
} else {
Ok("Updated".to_string())
}
}
/// Handle timestamp function
fn handle_timestamp_function(&self) -> Result<String> {
use std::time::{SystemTime, UNIX_EPOCH};
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| RuleEngineError::EvaluationError {
message: format!("Failed to get timestamp: {}", e),
})?
.as_secs();
Ok(timestamp.to_string())
}
/// Handle random function
fn handle_random_function(&self, args: &[Value]) -> Result<String> {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// Simple pseudo-random based on current time (for deterministic behavior in tests)
let mut hasher = DefaultHasher::new();
std::time::SystemTime::now().hash(&mut hasher);
let random_value = hasher.finish();
if args.is_empty() {
Ok((random_value % 100).to_string()) // 0-99
} else if let Some(Value::Number(max)) = args.first() {
let max_val = *max as u64;
Ok((random_value % max_val).to_string())
} else {
Ok(random_value.to_string())
}
}
/// Handle format function (simple sprintf-like)
fn handle_format_function(&self, args: &[Value]) -> Result<String> {
if args.is_empty() {
return Ok("".to_string());
}
let template = args[0].to_string();
let values: Vec<String> = args[1..].iter().map(|v| v.to_string()).collect();
// Simple placeholder replacement: {0}, {1}, etc.
let mut result = template;
for (i, value) in values.iter().enumerate() {
result = result.replace(&format!("{{{}}}", i), value);
}
Ok(result)
}
/// Handle length/size functions
fn handle_length_function(&self, args: &[Value]) -> Result<String> {
if let Some(arg) = args.first() {
match arg {
Value::String(s) => Ok(s.len().to_string()),
Value::Array(arr) => Ok(arr.len().to_string()),
Value::Object(obj) => Ok(obj.len().to_string()),
_ => Ok("1".to_string()), // Single value has length 1
}
} else {
Ok("0".to_string())
}
}
/// Handle sum function
fn handle_sum_function(&self, args: &[Value]) -> Result<String> {
let sum = args.iter().fold(0.0, |acc, val| match val {
Value::Number(n) => acc + n,
Value::Integer(i) => acc + (*i as f64),
_ => acc,
});
Ok(sum.to_string())
}
/// Handle max function
fn handle_max_function(&self, args: &[Value]) -> Result<String> {
let max = args.iter().fold(f64::NEG_INFINITY, |acc, val| match val {
Value::Number(n) => acc.max(*n),
Value::Integer(i) => acc.max(*i as f64),
_ => acc,
});
Ok(max.to_string())
}
/// Handle min function
fn handle_min_function(&self, args: &[Value]) -> Result<String> {
let min = args.iter().fold(f64::INFINITY, |acc, val| match val {
Value::Number(n) => acc.min(*n),
Value::Integer(i) => acc.min(*i as f64),
_ => acc,
});
Ok(min.to_string())
}
/// Handle average function
fn handle_average_function(&self, args: &[Value]) -> Result<String> {
if args.is_empty() {
return Ok("0".to_string());
}
let (sum, count) = args.iter().fold((0.0, 0), |(sum, count), val| match val {
Value::Number(n) => (sum + n, count + 1),
Value::Integer(i) => (sum + (*i as f64), count + 1),
_ => (sum, count),
});
if count > 0 {
Ok((sum / count as f64).to_string())
} else {
Ok("0".to_string())
}
}
/// Handle mathematical functions
fn handle_round_function(&self, args: &[Value]) -> Result<String> {
if let Some(Value::Number(n)) = args.first() {
Ok(n.round().to_string())
} else if let Some(Value::Integer(i)) = args.first() {
Ok(i.to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "round() requires a numeric argument".to_string(),
})
}
}
fn handle_floor_function(&self, args: &[Value]) -> Result<String> {
if let Some(Value::Number(n)) = args.first() {
Ok(n.floor().to_string())
} else if let Some(Value::Integer(i)) = args.first() {
Ok(i.to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "floor() requires a numeric argument".to_string(),
})
}
}
fn handle_ceil_function(&self, args: &[Value]) -> Result<String> {
if let Some(Value::Number(n)) = args.first() {
Ok(n.ceil().to_string())
} else if let Some(Value::Integer(i)) = args.first() {
Ok(i.to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "ceil() requires a numeric argument".to_string(),
})
}
}
fn handle_abs_function(&self, args: &[Value]) -> Result<String> {
if let Some(Value::Number(n)) = args.first() {
Ok(n.abs().to_string())
} else if let Some(Value::Integer(i)) = args.first() {
Ok(i.abs().to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "abs() requires a numeric argument".to_string(),
})
}
}
/// Handle string functions
fn handle_contains_function(&self, args: &[Value]) -> Result<String> {
if args.len() >= 2 {
let haystack = args[0].to_string();
let needle = args[1].to_string();
Ok(haystack.contains(&needle).to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "contains() requires 2 arguments".to_string(),
})
}
}
fn handle_starts_with_function(&self, args: &[Value]) -> Result<String> {
if args.len() >= 2 {
let text = args[0].to_string();
let prefix = args[1].to_string();
Ok(text.starts_with(&prefix).to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "startswith() requires 2 arguments".to_string(),
})
}
}
fn handle_ends_with_function(&self, args: &[Value]) -> Result<String> {
if args.len() >= 2 {
let text = args[0].to_string();
let suffix = args[1].to_string();
Ok(text.ends_with(&suffix).to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "endswith() requires 2 arguments".to_string(),
})
}
}
fn handle_lowercase_function(&self, args: &[Value]) -> Result<String> {
if let Some(arg) = args.first() {
Ok(arg.to_string().to_lowercase())
} else {
Err(RuleEngineError::EvaluationError {
message: "lowercase() requires 1 argument".to_string(),
})
}
}
fn handle_uppercase_function(&self, args: &[Value]) -> Result<String> {
if let Some(arg) = args.first() {
Ok(arg.to_string().to_uppercase())
} else {
Err(RuleEngineError::EvaluationError {
message: "uppercase() requires 1 argument".to_string(),
})
}
}
fn handle_trim_function(&self, args: &[Value]) -> Result<String> {
if let Some(arg) = args.first() {
Ok(arg.to_string().trim().to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: "trim() requires 1 argument".to_string(),
})
}
}
fn handle_split_function(&self, args: &[Value]) -> Result<String> {
if args.len() >= 2 {
let text = args[0].to_string();
let delimiter = args[1].to_string();
let parts: Vec<String> = text.split(&delimiter).map(|s| s.to_string()).collect();
Ok(format!("{:?}", parts)) // Return as debug string for now
} else {
Err(RuleEngineError::EvaluationError {
message: "split() requires 2 arguments".to_string(),
})
}
}
fn handle_join_function(&self, args: &[Value]) -> Result<String> {
if args.len() >= 2 {
let delimiter = args[0].to_string();
let parts: Vec<String> = args[1..].iter().map(|v| v.to_string()).collect();
Ok(parts.join(&delimiter))
} else {
Err(RuleEngineError::EvaluationError {
message: "join() requires at least 2 arguments".to_string(),
})
}
}
/// Handle custom user-defined functions
fn handle_custom_function(
&self,
function: &str,
args: &[Value],
facts: &Facts,
) -> Result<String> {
// Check if we have a registered custom function
if let Some(custom_func) = self.custom_functions.get(function) {
if self.config.debug_mode {
println!("🎯 Calling registered function: {}({:?})", function, args);
}
match custom_func(args, facts) {
Ok(result) => Ok(result.to_string()),
Err(e) => Err(e),
}
} else {
// Function not found - return error or placeholder
if self.config.debug_mode {
println!("⚠️ Custom function '{}' not registered", function);
}
Err(RuleEngineError::EvaluationError {
message: format!("Function '{}' is not registered. Use engine.register_function() to add custom functions.", function),
})
}
}
/// Execute method call on object
fn execute_method_call(
&self,
object_name: &str,
method: &str,
args: &[Value],
facts: &Facts,
) -> Result<String> {
// Get the object from facts
let Some(object_value) = facts.get(object_name) else {
return Err(RuleEngineError::EvaluationError {
message: format!("Object '{}' not found in facts", object_name),
});
};
let method_lower = method.to_lowercase();
// Handle setter methods (set + property name)
if method_lower.starts_with("set") && args.len() == 1 {
return self.handle_setter_method(object_name, method, &args[0], object_value, facts);
}
// Handle getter methods (get + property name)
if method_lower.starts_with("get") && args.is_empty() {
return self.handle_getter_method(object_name, method, &object_value);
}
// Handle built-in methods
match method_lower.as_str() {
"tostring" => Ok(object_value.to_string()),
"update" => {
facts.add_value(object_name, object_value)?;
Ok(format!("Updated {}", object_name))
}
"reset" => self.handle_reset_method(object_name, object_value, facts),
_ => self.handle_property_access_or_fallback(
object_name,
method,
args.len(),
&object_value,
),
}
}
/// Handle setter method calls (setXxx)
fn handle_setter_method(
&self,
object_name: &str,
method: &str,
new_value: &Value,
mut object_value: Value,
facts: &Facts,
) -> Result<String> {
let property_name = Self::extract_property_name_from_setter(method);
match object_value {
Value::Object(ref mut obj) => {
obj.insert(property_name.clone(), new_value.clone());
facts.add_value(object_name, object_value)?;
Ok(format!(
"Set {} to {}",
property_name,
new_value.to_string()
))
}
_ => Err(RuleEngineError::EvaluationError {
message: format!("Cannot call setter on non-object type: {}", object_name),
}),
}
}
/// Handle getter method calls (getXxx)
fn handle_getter_method(
&self,
object_name: &str,
method: &str,
object_value: &Value,
) -> Result<String> {
let property_name = Self::extract_property_name_from_getter(method);
match object_value {
Value::Object(obj) => {
if let Some(value) = obj.get(&property_name) {
Ok(value.to_string())
} else {
Err(RuleEngineError::EvaluationError {
message: format!(
"Property '{}' not found on object '{}'",
property_name, object_name
),
})
}
}
_ => Err(RuleEngineError::EvaluationError {
message: format!("Cannot call getter on non-object type: {}", object_name),
}),
}
}
/// Handle reset method call
fn handle_reset_method(
&self,
object_name: &str,
mut object_value: Value,
facts: &Facts,
) -> Result<String> {
match object_value {
Value::Object(ref mut obj) => {
obj.clear();
facts.add_value(object_name, object_value)?;
Ok(format!("Reset {}", object_name))
}
_ => Err(RuleEngineError::EvaluationError {
message: format!("Cannot reset non-object type: {}", object_name),
}),
}
}
/// Handle property access or fallback to generic method call
fn handle_property_access_or_fallback(
&self,
object_name: &str,
method: &str,
arg_count: usize,
object_value: &Value,
) -> Result<String> {
if let Value::Object(obj) = object_value {
// Try exact property name match
if let Some(value) = obj.get(method) {
return Ok(value.to_string());
}
// Try capitalized property name
let capitalized_method = Self::capitalize_first_letter(method);
if let Some(value) = obj.get(&capitalized_method) {
return Ok(value.to_string());
}
}
// Fallback to generic response
Ok(format!(
"Called {}.{} with {} args",
object_name, method, arg_count
))
}
/// Extract property name from setter method (setXxx -> Xxx)
fn extract_property_name_from_setter(method: &str) -> String {
let property_name = &method[3..]; // Remove "set" prefix
Self::capitalize_first_letter(property_name)
}
/// Extract property name from getter method (getXxx -> Xxx)
fn extract_property_name_from_getter(method: &str) -> String {
let property_name = &method[3..]; // Remove "get" prefix
Self::capitalize_first_letter(property_name)
}
/// Helper function to capitalize first letter of a string
fn capitalize_first_letter(s: &str) -> String {
if s.is_empty() {
return String::new();
}
let mut chars = s.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
}
/// Resolve action parameters by replacing fact references with actual values
fn resolve_action_parameters(
&self,
params: &HashMap<String, Value>,
facts: &Facts,
) -> Result<HashMap<String, Value>> {
let mut resolved = HashMap::new();
for (key, value) in params {
let resolved_value = match value {
Value::String(s) => {
// Check if string looks like a fact reference (contains dot)
if s.contains('.') {
// Try to get the value from facts
if let Some(fact_value) = facts.get_nested(s) {
fact_value
} else {
// If not found, keep original string
value.clone()
}
} else {
value.clone()
}
}
_ => value.clone(),
};
resolved.insert(key.clone(), resolved_value);
}
Ok(resolved)
}
// 🔌 Plugin System Methods
/// Load a plugin into the engine
pub fn load_plugin(
&mut self,
plugin: std::sync::Arc<dyn crate::engine::plugin::RulePlugin>,
) -> Result<()> {
// First register the plugin actions with this engine
plugin.register_actions(self)?;
plugin.register_functions(self)?;
// Then store it in the plugin manager
self.plugin_manager.load_plugin(plugin)
}
/// Unload a plugin from the engine
pub fn unload_plugin(&mut self, name: &str) -> Result<()> {
self.plugin_manager.unload_plugin(name)
}
/// Hot reload a plugin
pub fn hot_reload_plugin(
&mut self,
name: &str,
new_plugin: std::sync::Arc<dyn crate::engine::plugin::RulePlugin>,
) -> Result<()> {
// Unload old plugin
self.plugin_manager.unload_plugin(name)?;
// Register new plugin actions
new_plugin.register_actions(self)?;
new_plugin.register_functions(self)?;
// Load new plugin
self.plugin_manager.load_plugin(new_plugin)
}
/// Get plugin information
pub fn get_plugin_info(&self, name: &str) -> Option<&crate::engine::plugin::PluginMetadata> {
self.plugin_manager.get_plugin_info(name)
}
/// List all loaded plugins
pub fn list_plugins(&self) -> Vec<PluginInfo> {
self.plugin_manager.list_plugins()
}
/// Get plugin statistics
pub fn get_plugin_stats(&self) -> PluginStats {
self.plugin_manager.get_stats()
}
/// Check health of all plugins
pub fn plugin_health_check(&mut self) -> HashMap<String, crate::engine::plugin::PluginHealth> {
self.plugin_manager.plugin_health_check()
}
/// Configure plugin manager
pub fn configure_plugins(&mut self, config: PluginConfig) {
self.plugin_manager = PluginManager::new(config);
}
}