rust-rule-engine 0.9.0

A high-performance rule engine for Rust with plugin system, built-in utilities, GRL support, and advanced pattern matching
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
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
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
# Rust Rule Engine v0.9.0 ๐Ÿฆ€โšก

[![Crates.io](https://img.shields.io/crates/v/rust-rule-engine.svg)](https://crates.io/crates/rust-rule-engine)
[![Documentation](https://docs.rs/rust-rule-engine/badge.svg)](https://docs.rs/rust-rule-engine)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://github.com/KSD-CO/rust-rule-engine/workflows/CI/badge.svg)](https://github.com/KSD-CO/rust-rule-engine/actions)
[![GitHub](https://img.shields.io/badge/GitHub-rust--rule--engine-blue?logo=github)](https://github.com/KSD-CO/rust-rule-engine)

A high-performance rule engine for Rust with **Plugin System**, **Built-in Utilities**, **GRL (Grule Rule Language) support**, and advanced pattern matching capabilities. Designed for production use with comprehensive error handling, type safety, and extensibility.

๐Ÿ”— **[GitHub Repository]https://github.com/KSD-CO/rust-rule-engine** | **[Documentation]https://docs.rs/rust-rule-engine** | **[Crates.io]https://crates.io/crates/rust-rule-engine**

## ๏ฟฝ Table of Contents

- [๐Ÿš€ Key Features]#-key-features
- [๐Ÿ“ฆ Installation]#-installation
- [๐ŸŽฏ Quick Start]#-quick-start
  - [Basic Rule Engine with Built-in Plugins]#basic-rule-engine-with-built-in-plugins
  - [Simple Rule without Plugins]#simple-rule-without-plugins
- [๐Ÿ”Œ Plugin System]#-plugin-system
  - [Built-in Plugins Overview]#built-in-plugins-overview
  - [Creating Custom Plugins]#creating-custom-plugins
- [๐ŸŽฏ Advanced Features]#-advanced-features
  - [Knowledge Base Management]#knowledge-base-management
  - [Complex Data Objects]#complex-data-objects
  - [Method Calls and Functions]#method-calls-and-functions
  - [Error Handling and Debugging]#error-handling-and-debugging
- [๐Ÿ“š Examples]#-examples
- [๐Ÿ”ง Configuration]#-configuration
  - [Engine Configuration]#engine-configuration
  - [Plugin Configuration]#plugin-configuration
- [๐Ÿš€ Performance]#-performance
- [๐Ÿ—บ Roadmap]#-roadmap
- [๐Ÿงฉ Advanced Pattern Matching]#-advanced-pattern-matching-v070
- [๐ŸŽฏ Rule Attributes]#-rule-attributes-v060
- [๐Ÿšจ Advanced Action Handlers]#-advanced-action-handlers-v071
- [๐ŸŒŠ Advanced Workflow Engine]#-advanced-workflow-engine-v080-latest
- [๐Ÿค– AI Integration]#-ai-integration-new
- [๐ŸŽจ Visual Rule Builder]#-visual-rule-builder-new
- [๐ŸŒ REST API with Monitoring]#-rest-api-with-monitoring
- [โšก Performance & Architecture]#-performance--architecture
- [๐Ÿ“‹ Changelog]#-changelog
- [๐ŸŽฏ GRL Rule Language Features]#-grl-rule-language-features
- [๐ŸŒ Distributed & Cloud Features]#-distributed--cloud-features
- [๐Ÿ“‹ API Reference]#-api-reference
- [๐Ÿค Contributing]#-contributing
- [๐Ÿ“„ License]#-license
- [๐Ÿ™ Acknowledgments]#-acknowledgments
- [๐Ÿ“ž Support]#-support

## ๏ฟฝ๐Ÿš€ Key Features

### ๐Ÿ”ฅ **NEW in v0.9.0: Plugin System**
- **Modular Plugin Architecture**: Extensible plugin system with lifecycle management
- **Built-in Plugin Suite**: 44+ actions & 33+ functions for common operations
- **Plugin Health Monitoring**: Real-time health checks and status tracking
- **Hot-reload Support**: Dynamic plugin loading and unloading
- **Custom Plugin Creation**: Easy-to-use RulePlugin trait for custom extensions

### ๐ŸŽฏ **Core Engine Features**
- **GRL Support**: Full Grule-compatible syntax with method calls and object interactions
- **Knowledge Base**: Centralized rule management with salience and priority control
- **Working Memory**: Advanced facts system for complex data relationships
- **Type Safety**: Rust's type system ensures runtime safety and performance
- **High Performance**: Optimized execution with cycle detection and parallel processing
- **Flexible Facts API**: Support for nested objects, arrays, and complex data structures

### ๐Ÿงฉ **Advanced Pattern Matching**
- **EXISTS Pattern**: Check if at least one fact matches condition (`exists(...)`)
- **NOT Pattern**: Check if no facts match condition (`!exists(...)`)
- **FORALL Pattern**: Check if all facts of a type match condition (`forall(...)`)
- **Complex Patterns**: Combine patterns with logical operators (AND, OR, NOT)
- **Drools Compatibility**: ~85% compatible with Drools pattern matching

### ๐ŸŽฏ **Rule Attributes & Workflow**
- **Agenda Groups**: Organize rules into execution phases for workflow control
- **Activation Groups**: Mutually exclusive rule execution with salience priority
- **Lock-on-Active**: Prevent rules from firing multiple times per agenda activation
- **Date Effective/Expires**: Time-based rule activation with DateTime support
- **No-Loop Protection**: Prevent infinite rule self-activation
- **Salience Control**: Priority-based rule execution ordering

### ๐Ÿšจ **Action Handler System**
- **Custom Action Execution**: Register handlers for real business logic
- **Parameter Resolution**: Automatic fact value substitution in parameters
- **External System Integration**: Connect to emails, databases, APIs, services
- **Error Handling**: Graceful failure handling with meaningful messages
- **Facts Integration**: Full access to rule engine fact data within handlers

### ๐ŸŒŠ **Workflow Engine Features**
- **Scheduled Task System**: Time-based task execution with flexible scheduling
- **Workflow State Tracking**: Real-time workflow monitoring and progress tracking
- **Dynamic Rule Activation**: Context-aware rule execution based on workflow state
- **Comprehensive Analytics**: Detailed workflow performance metrics and insights

### ๐Ÿ›  **Built-in Plugin Suite**
- **String Utilities**: 13 actions, 7 functions for text manipulation
- **Math Operations**: 12 actions, 8 functions for calculations
- **Date/Time**: 8 actions, 6 functions for temporal operations
- **Data Validation**: 6 actions, 6 functions for input validation
- **Collections**: 7 actions, 6 functions for array/object manipulation

### ๐Ÿค– **AI Integration**
- **Sentiment Analysis**: Real-time text sentiment evaluation
- **Fraud Detection**: ML-powered fraud scoring and detection
- **Predictive Analytics**: Customer tier prediction and scoring
- **LLM Reasoning**: Large Language Model decision support
- **Real-time ML Scoring**: Dynamic model inference in rules

### ๐ŸŒ **Production Features**
- **REST API**: Complete web API with analytics monitoring
- **Real-time Analytics**: Live performance monitoring and insights
- **Health Checks**: Comprehensive system health monitoring
- **CORS Support**: Cross-origin resource sharing
- **Memory Management**: Automatic cleanup and retention policies
- **Error Handling**: Proper HTTP status codes and error messages

### โšก **Performance & Architecture**
- **Ultra-fast Execution**: Rules execute in microseconds (2-5ยตs)
- **Efficient Parsing**: GRL rules parse in under 2ยตs
- **Low Memory Footprint**: Minimal overhead per rule (~1-2KB)
- **Zero GC Pauses**: No garbage collection overhead
- **Parallel Processing**: Multi-threaded rule execution when safe
- **Dependency Analysis**: AST-based conflict detection and optimization

## ๐Ÿ“ฆ Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
rust-rule-engine = "0.9.0"
```

## ๐ŸŽฏ Quick Start

### Basic Rule Engine with Built-in Plugins

```rust
use rust_rule_engine::*;
use rust_rule_engine::engine::plugin::RulePlugin;
use rust_rule_engine::plugins::*;

fn main() -> Result<()> {
    // Create engine with knowledge base
    let kb = KnowledgeBase::new("Demo");
    let mut engine = RustRuleEngine::new(kb);
    let mut facts = Facts::new();

    // Load built-in plugins
    let string_plugin = StringUtilsPlugin::new();
    let math_plugin = MathUtilsPlugin::new();
    let validation_plugin = ValidationPlugin::new();

    // Register plugins
    string_plugin.register_actions(&mut engine)?;
    string_plugin.register_functions(&mut engine)?;
    math_plugin.register_actions(&mut engine)?;
    math_plugin.register_functions(&mut engine)?;
    validation_plugin.register_actions(&mut engine)?;
    validation_plugin.register_functions(&mut engine)?;

    // Set up data
    facts.set("user.email".to_string(), Value::String("user@example.com".to_string()));
    facts.set("user.age".to_string(), Value::Number(25.0));
    facts.set("order.amount".to_string(), Value::Number(150.0));

    // Define GRL rule with plugin actions
    let rule_content = r#"
    rule "UserValidationAndDiscount" salience 10 {
        when
            isEmail(user.email) == true &&
            inRange(user.age, 18, 65) == true &&
            user.order.amount > 100
        then
            ValidateEmail("user.email", "email_valid");
            ValidateRange("user.age", 18, 65, "age_valid");
            Multiply("order.amount", 0.9, "discounted_amount");
            ToUpperCase("user.status", "display_status");
    }
    "#;

    // Parse and add rule to knowledge base
    let rules = GRLParser::parse_rules(rule_content)?;
    for rule in rules {
        engine.add_rule_to_kb(rule)?;
    }

    // Execute rules
    let result = engine.execute(&facts)?;
    println!("Rules executed: {}", result.rules_executed);
    println!("Email valid: {:?}", facts.get("email_valid"));
    println!("Age valid: {:?}", facts.get("age_valid"));
    println!("Discounted amount: {:?}", facts.get("discounted_amount"));

    Ok(())
}
```

### Simple Rule without Plugins

```rust
use rust_rule_engine::*;

fn main() -> Result<()> {
    let kb = KnowledgeBase::new("SimpleDemo");
    let mut engine = RustRuleEngine::new(kb);
    let mut facts = Facts::new();

    // Set up facts
    facts.set("Customer.Age".to_string(), Value::Integer(25));
    facts.set("Customer.Country".to_string(), Value::String("US".to_string()));
    facts.set("Order.Total".to_string(), Value::Number(150.0));

    // Define GRL rule
    let rule = r#"
    rule "DiscountRule" salience 20 {
        when
            Customer.Age >= 18 && 
            Customer.Country == "US" && 
            Order.Total > 100
        then
            Order.DiscountRate = 0.15;
            Order.FreeShipping = true;
    }
    "#;

    // Parse and execute
    let rules = GRLParser::parse_rules(rule)?;
    for r in rules {
        engine.add_rule_to_kb(r)?;
    }

    let result = engine.execute(&facts)?;
    println!("Discount applied: {:?}", facts.get("Order.DiscountRate"));
    println!("Free shipping: {:?}", facts.get("Order.FreeShipping"));

    Ok(())
}
```

## ๐Ÿ”Œ Plugin System

### Built-in Plugins Overview

The v0.9.0 release includes a comprehensive plugin suite:

#### ๐Ÿ“ String Utilities Plugin
```rust
// Actions: ToUpperCase, ToLowerCase, StringTrim, StringLength, 
//          StringContains, StringReplace, StringSplit, StringJoin
// Functions: concat, repeat, substring, padLeft, padRight

ToUpperCase("input_text", "output_text");
let result = concat("Hello", " World"); // "Hello World"
```

#### ๐Ÿ”ข Math Operations Plugin
```rust
// Actions: Add, Subtract, Multiply, Divide, Modulo, Power, Abs, Round, Ceil, Floor
// Functions: max, min, sqrt, sum, avg, random

Add("num1", "num2", "result");
let maximum = max(10.5, 8.2); // 10.5
```

#### ๐Ÿ“… Date/Time Plugin
```rust
// Actions: CurrentDate, CurrentTime, FormatDate, ParseDate, AddDays, AddHours, DateDiff, IsWeekend
// Functions: now, today, dayOfWeek, dayOfYear, year, month, day

CurrentDate("current_date");
let day = dayOfWeek("2023-10-15"); // Returns day number
```

#### โœ… Validation Plugin
```rust
// Actions: ValidateEmail, ValidatePhone, ValidateUrl, ValidateRegex, ValidateRange, ValidateLength, ValidateNotEmpty, ValidateNumeric
// Functions: isEmail, isPhone, isUrl, isNumeric, isEmpty, inRange

ValidateEmail("user.email", "email_valid");
let valid = isEmail("test@example.com"); // true
```

#### ๐Ÿ“‹ Collection Operations Plugin
```rust
// Actions: ArrayLength, ArrayPush, ArrayPop, ArraySort, ArrayFilter, ArrayMap, ArrayFind, ObjectKeys, ObjectValues, ObjectMerge
// Functions: length, contains, first, last, reverse, join, slice, keys, values

ArrayLength("my_array", "array_length");
let size = length([1, 2, 3, 4]); // 4
```

### Creating Custom Plugins

```rust
use rust_rule_engine::engine::plugin::{RulePlugin, PluginMetadata, PluginState, PluginHealth};

pub struct MyCustomPlugin {
    metadata: PluginMetadata,
}

impl MyCustomPlugin {
    pub fn new() -> Self {
        Self {
            metadata: PluginMetadata {
                name: "my_custom_plugin".to_string(),
                version: "1.0.0".to_string(),
                description: "My custom plugin".to_string(),
                author: "Developer Name".to_string(),
                state: PluginState::Loaded,
                health: PluginHealth::Healthy,
                actions: vec!["MyAction".to_string()],
                functions: vec!["myFunction".to_string()],
                dependencies: vec![],
            },
        }
    }
}

impl RulePlugin for MyCustomPlugin {
    fn get_metadata(&self) -> &PluginMetadata {
        &self.metadata
    }

    fn register_actions(&self, engine: &mut RustRuleEngine) -> Result<()> {
        engine.register_action_handler("MyAction", |params, facts| {
            // Your custom action logic here
            Ok(())
        });
        Ok(())
    }

    fn register_functions(&self, engine: &mut RustRuleEngine) -> Result<()> {
        engine.register_function("myFunction", |args, _facts| {
            // Your custom function logic here
            Ok(Value::String("result".to_string()))
        });
        Ok(())
    }

    fn unload(&mut self) -> Result<()> {
        self.metadata.state = PluginState::Unloaded;
        Ok(())
    }

    fn health_check(&mut self) -> PluginHealth {
        PluginHealth::Healthy
    }
}
```

## ๐ŸŽฏ Advanced Features

### Knowledge Base Management

```rust
let mut kb = KnowledgeBase::new("Advanced");

// Add rules with different salience (priority)
kb.add_rule_from_grl(r#"
rule "HighPriority" salience 100 { when condition then action }
"#)?;

kb.add_rule_from_grl(r#"
rule "LowPriority" salience 10 { when condition then action }
"#)?;

// Rules execute in salience order (highest first)
let mut engine = RustRuleEngine::new(kb);
```

### Complex Data Objects

```rust
use std::collections::HashMap;

let mut facts = Facts::new();

// Nested object structures
let mut customer = HashMap::new();
customer.insert("name".to_string(), Value::String("John Doe".to_string()));
customer.insert("age".to_string(), Value::Integer(30));

let mut address = HashMap::new();
address.insert("country".to_string(), Value::String("US".to_string()));
address.insert("state".to_string(), Value::String("CA".to_string()));

customer.insert("address".to_string(), Value::Object(address));
facts.set("Customer".to_string(), Value::Object(customer));

// Access nested properties in rules
let rule = r#"
rule "LocationRule" {
    when
        Customer.address.country == "US" &&
        Customer.address.state == "CA" &&
        Customer.age >= 21
    then
        Customer.eligible = true;
        Customer.discount = 0.1;
}
"#;
```

### Method Calls and Functions

```rust
// Built-in functions in conditions
let rule = r#"
rule "ValidationRule" {
    when
        isEmail(Customer.email) == true &&
        length(Customer.name) > 2 &&
        inRange(Customer.age, 18, 120) == true
    then
        Customer.validated = true;
}
"#;

// Custom function registration
engine.register_function("customValidation", |args, facts| {
    // Custom validation logic
    Ok(Value::Boolean(true))
});
```

### Error Handling and Debugging

```rust
use rust_rule_engine::errors::{Result, RuleEngineError};

// Comprehensive error handling
match engine.execute(&facts) {
    Ok(result) => {
        println!("Success: {} rules executed", result.rules_executed);
        println!("Execution time: {:?}", result.execution_time);
    },
    Err(RuleEngineError::ParseError { message, line, column }) => {
        eprintln!("Parse error at {}:{} - {}", line, column, message);
    },
    Err(RuleEngineError::EvaluationError { message }) => {
        eprintln!("Evaluation error: {}", message);
    },
    Err(e) => {
        eprintln!("Other error: {}", e);
    }
}
```

## ๐Ÿ“š Examples

The repository includes comprehensive examples:

- **Basic Usage**: `examples/basic_demo.rs`
- **Plugin System**: `examples/builtin_plugins_demo.rs`
- **E-commerce Rules**: `examples/ecommerce.rs`
- **Fraud Detection**: `examples/fraud_detection.rs`
- **GRL Compatibility**: `examples/grule_demo.rs`
- **Streaming Data**: `examples/realtime_trading_stream.rs`

Run examples:
```bash
cargo run --example builtin_plugins_demo
cargo run --example ecommerce
cargo run --example fraud_detection
```

## ๐Ÿ”ง Configuration

### Engine Configuration

```rust
use rust_rule_engine::engine::engine::EngineConfig;

let config = EngineConfig {
    max_cycles: 1000,
    enable_tracing: true,
    parallel_execution: true,
    cycle_detection: true,
};

let engine = RustRuleEngine::with_config(kb, config);
```

### Plugin Configuration

```rust
use rust_rule_engine::engine::plugin::{PluginConfig, PluginManager};

let plugin_config = PluginConfig {
    max_plugins: 50,
    enable_hot_reload: true,
    plugin_timeout_ms: 5000,
    safety_checks: true,
};

let plugin_manager = PluginManager::new(plugin_config);
```

## ๐Ÿš€ Performance

Rust Rule Engine v0.9.0 is designed for high-performance scenarios:

- **Zero-copy**: Efficient memory usage with minimal allocations
- **Parallel Execution**: Multi-threaded rule processing when safe
- **Optimized Parsing**: Fast GRL parsing with minimal overhead
- **Plugin Caching**: Efficient plugin management and reuse
- **Cycle Detection**: Prevents infinite loops in rule chains

## ๐Ÿ—บ Roadmap

### v0.10.0 (Planned)
- [ ] **Advanced Plugin Features**
  - Plugin dependency management
  - Plugin versioning and compatibility
  - Plugin marketplace integration
- [ ] **Performance Enhancements**
  - Rule compilation to bytecode
  - Advanced caching strategies
  - Memory pool optimization
- [ ] **Developer Experience**
  - Visual rule debugger
  - Rule testing framework
  - IDE plugins and syntax highlighting

### v1.0.0 (Future)
- [ ] **Production Features**
  - Distributed rule execution
  - Rule versioning and migration
  - Advanced monitoring and metrics
- [ ] **Enterprise Features**
  - Role-based access control
  - Audit logging
  - Integration with external systems

## ๐Ÿค Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Development Setup

```bash
git clone https://github.com/KSD-CO/rust-rule-engine.git
cd rust-rule-engine
cargo build
cargo test
cargo run --example builtin_plugins_demo
```

### Running Tests

```bash
# Run all tests
cargo test

# Run with coverage
cargo test --features coverage

# Run benchmarks
cargo bench
```

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ™ Acknowledgments

- Inspired by [Grule]https://github.com/hyperjumptech/grule-rule-engine rule engine
- Built with Rust's powerful type system and performance capabilities
- Community feedback and contributions

## ๐Ÿ“ž Support

- ๐Ÿ“š [Documentation]https://docs.rs/rust-rule-engine
- ๐Ÿ› [Issue Tracker]https://github.com/KSD-CO/rust-rule-engine/issues
- ๐Ÿ’ฌ [Discussions]https://github.com/KSD-CO/rust-rule-engine/discussions
- ๐Ÿ“ง Email: tonthatvu.hust@gmail.com

---

**Rust Rule Engine v0.9.0** - Powerful, extensible, and production-ready rule engine for Rust ๐Ÿฆ€โšก
- **๐ŸŒŠ Stream Processing**: Real-time event processing with time windows (optional)
- **๐Ÿ“Š Analytics**: Built-in aggregations and trend analysis
- **๐Ÿšจ Action Handlers**: Custom action execution for external system integration
- **๐Ÿ“ˆ Advanced Analytics**: Production-ready performance monitoring and optimization insights

## ๐ŸŒŠ Advanced Workflow Engine v0.8.0 (Latest!)

The rule engine now features a **comprehensive workflow engine** with agenda group management, scheduled task execution, and real-time workflow state tracking for complex business process automation.

### Workflow Features

- **๐Ÿ“‹ Agenda Group Management**: Organize rules into execution phases with automatic transitions
- **โฐ Scheduled Task System**: Time-based task execution with flexible scheduling
- **๐Ÿ”„ Workflow State Tracking**: Real-time workflow monitoring and progress tracking
- **๐ŸŽฏ Dynamic Rule Activation**: Context-aware rule execution based on workflow state
- **๏ฟฝ Comprehensive Analytics**: Detailed workflow performance metrics and insights

### Workflow Example

```rust
use rust_rule_engine::engine::{RustRuleEngine, EngineConfig};
use rust_rule_engine::engine::knowledge_base::KnowledgeBase;
use rust_rule_engine::parser::grl::GRLParser;
use rust_rule_engine::types::Value;
use rust_rule_engine::Facts;

// Create workflow engine
let config = EngineConfig {
    debug_mode: false,
    max_cycles: 100,
    enable_stats: true,
    ..Default::default()
};
let mut engine = RustRuleEngine::with_config(KnowledgeBase::new("WorkflowDemo"), config);

// Define workflow rules with agenda groups
let workflow_rules = vec![
    r#"
    rule "StartOrderWorkflow" salience 100 agenda-group "start" {
        when Order.Status == "pending"
        then
            log("๐Ÿ”„ Starting order processing workflow");
            ActivateAgendaGroup("validation");
            SetWorkflowData("order-process", status="started");
    }
    "#,
    r#"
    rule "ValidateOrder" salience 90 agenda-group "validation" {
        when Order.Amount > 0 && Inventory.Available == true
        then
            log("โœ… Order validation passed");
            Order.Status = "validated";
            ActivateAgendaGroup("payment");
    }
    "#,
    r#"
    rule "ProcessVIPPayment" salience 80 agenda-group "payment" {
        when Order.Status == "validated" && Customer.VIP == true
        then
            log("๐Ÿ’ณ Processing VIP payment with priority");
            Order.Status = "paid";
            ActivateAgendaGroup("fulfillment");
    }
    "#
];

// Execute workflow with automatic agenda management
let result = engine.execute_workflow(&facts)?;
println!("Workflow completed: {} rules fired in {} cycles", 
         result.rules_fired, result.cycles);
```

## ๐Ÿšจ Advanced Action Handlers v0.7.1

The rule engine now supports advanced custom action execution with **simplified parameter syntax** and **automatic fact resolution**, enabling seamless integration with external systems.

### Action Handler System

Register custom handlers for `ActionType::Custom` actions that can execute real business logic instead of just debug printing.

#### โœจ Simplified Parameter Syntax v0.7.1

```rust
use rust_rule_engine::engine::{RustRuleEngine, EngineConfig};
use rust_rule_engine::types::Value;
use std::collections::HashMap;

// Create engine
let mut engine = RustRuleEngine::with_config(kb, EngineConfig::default());

// Register email handler with indexed parameters
engine.register_action_handler("SendEmail", |params, facts| {
    // Access parameters by index: "0", "1", "2"...
    let to = if let Some(arg) = params.get("0") {
        match arg {
            Value::String(s) => {
                // Automatic fact resolution: Customer.email โ†’ alice@example.com
                if let Some(resolved) = facts.get_nested(s) {
                    resolved.to_string()
                } else {
                    s.clone()
                }
            }
            _ => arg.to_string(),
        }
    } else {
        "unknown@example.com".to_string()
    };
    
    let subject = params.get("1").map(|v| v.to_string()).unwrap_or("No Subject".to_string());
    let body = params.get("2").map(|v| v.to_string()).unwrap_or("No Body".to_string());
    
    // Execute actual email sending logic
    println!("๐Ÿ“ง EMAIL SENT:");
    println!("   To: {}", to);
    println!("   Subject: {}", subject);
    println!("   Body: {}", body);
    
    Ok(())
});

// Register database logger with simplified syntax
engine.register_action_handler("LogToDatabase", |params, facts| {
    let table = params.get("0").map(|v| v.to_string()).unwrap_or("default_table".to_string());
    let event = params.get("1").map(|v| v.to_string()).unwrap_or("unknown_event".to_string());
    
    println!("๐Ÿ—„๏ธ DATABASE LOG:");
    println!("   Table: {}", table);
    println!("   Event: {}", event);
    println!("   Timestamp: {}", chrono::Utc::now().format("%Y-%m-%d %H:%M:%S"));
    
    Ok(())
});
```

#### Parameter Resolution

Action handlers automatically resolve fact references in parameters:

```rust
// In GRL rule:
rule "WelcomeCustomer" {
    when
        Customer.status == "new"
    then
        SendEmail(Customer.email, "Welcome!", Customer.name);
}

// Parameter resolution in action:
// Parameter 0: "Customer.email" โ†’ "john.doe@example.com"
// Parameter 1: "Welcome!" โ†’ "Welcome!"
// Parameter 2: "Customer.name" โ†’ "John Doe"
```

#### GRL Usage with Action Handlers

```grl
rule "VIPCustomerWelcome" salience 20 no-loop {
    when
        Customer.tier == "VIP" && Customer.welcome_sent != true
    then
        SendEmail(Customer.email, "VIP Welcome Package", "Welcome to our VIP program!");
        LogToDatabase("customer_events", "vip_welcome_sent");
        Customer.welcome_sent = true;
}

rule "HighValueOrderAlert" salience 15 no-loop {
    when
        Order.total > 5000 && Order.alert_sent != true
    then
        SendAlert("HIGH", "High-value order requires review");
        ProcessPayment(Order.total, "secure_processing");
        Order.alert_sent = true;
}
```

### Action Handler Examples

See complete examples:
- [Action Handlers Demo]examples/action_handlers_demo.rs - Comprehensive action handler showcase

### Benefits

โœ… **External System Integration**: Connect rules to emails, databases, APIs, services  
โœ… **Real Business Logic**: Execute actual business operations, not just debug prints  
โœ… **Parameter Resolution**: Automatic fact value substitution in action parameters  
โœ… **Facts Integration**: Full access to rule engine fact data within handlers  
โœ… **Error Handling**: Graceful failure handling with meaningful error messages  
โœ… **Performance**: Efficient execution with minimal overhead  
โœ… **Flexibility**: Register any custom business logic as action handlers  
โœ… **Testability**: Mock handlers for unit testing rule behavior  

## ๐Ÿงฉ Advanced Pattern Matching v0.7.0

The rule engine now supports advanced pattern matching capabilities similar to Drools, enabling complex conditional logic with EXISTS, NOT, and FORALL patterns.

### Pattern Types

#### EXISTS Pattern
Check if **at least one** fact matches the condition:

```rust
// Programmatic API
let condition = ConditionGroup::exists(
    ConditionGroup::Single(Condition::new(
        "Customer.tier".to_string(),
        Operator::Equal,
        Value::String("VIP".to_string()),
    ))
);
```

```grl
// GRL Syntax
rule "ActivateVIPService" salience 20 {
    when
        exists(Customer.tier == "VIP")
    then
        System.vipServiceActive = true;
        log("VIP service activated");
}
```

#### NOT Pattern
Check if **no facts** match the condition:

```rust
// Programmatic API
let condition = ConditionGroup::not(
    ConditionGroup::exists(
        ConditionGroup::Single(Condition::new(
            "Order.status".to_string(),
            Operator::Equal,
            Value::String("pending".to_string()),
        ))
    )
);
```

```grl
// GRL Syntax
rule "SendMarketingEmail" salience 15 {
    when
        !exists(Order.status == "pending")
    then
        Marketing.emailSent = true;
        log("Marketing email sent - no pending orders");
}
```

#### FORALL Pattern
Check if **all facts** of a type match the condition:

```rust
// Programmatic API  
let condition = ConditionGroup::forall(
    ConditionGroup::Single(Condition::new(
        "Order.status".to_string(),
        Operator::Equal,
        Value::String("processed".to_string()),
    ))
);
```

```grl
// GRL Syntax
rule "EnableShipping" salience 10 {
    when
        forall(Order.status == "processed")
    then
        Shipping.enabled = true;
        log("All orders processed - shipping enabled");
}
```

#### Combined Patterns
Combine multiple patterns with logical operators:

```grl
rule "ComplexBusinessRule" salience 25 {
    when
        exists(Customer.tier == "VIP") && 
        !exists(Alert.priority == "high") &&
        forall(Order.status == "processed")
    then
        System.premiumModeEnabled = true;
        log("Premium mode activated - all conditions met");
}
```

### Pattern Matching Examples

See complete examples:
- [Pattern Matching Demo]examples/pattern_matching_demo.rs - Programmatic API
- [GRL Pattern Matching Demo]examples/simple_pattern_matching_grl.rs - GRL file syntax
- [Complex Patterns from File]examples/pattern_matching_from_grl.rs - Advanced GRL patterns

### Drools Compatibility

Pattern matching brings ~85% compatibility with Drools rule engine, supporting the core pattern matching features that enable complex business logic modeling.

## ๐ŸŽฏ Rule Attributes v0.6.0

Advanced rule attributes providing **Drools-compatible** workflow control and execution management:

### ๐Ÿ“‹ Agenda Groups - Workflow Control
Organize rules into **execution phases** with agenda group control:

```grl
rule "ValidateCustomer" agenda-group "validation" salience 10 {
    when
        Customer.age >= 18
    then
        Customer.status = "valid";
        log("Customer validated");
}

rule "ProcessPayment" agenda-group "processing" salience 5 {
    when
        Customer.status == "valid"
    then
        Order.status = "processed";
        log("Payment processed");
}
```

```rust
// Control workflow execution
engine.set_agenda_focus("validation");
engine.execute(&facts)?; // Only validation rules fire

engine.set_agenda_focus("processing"); 
engine.execute(&facts)?; // Only processing rules fire
```

### ๐ŸŽฏ Activation Groups - Mutually Exclusive Rules
Ensure **only one rule** from a group fires:

```grl
rule "PremiumDiscount" activation-group "discount" salience 10 {
    when Customer.tier == "premium"
    then Order.discount = 0.20;
}

rule "GoldDiscount" activation-group "discount" salience 8 {
    when Customer.tier == "gold"  
    then Order.discount = 0.15;
}
```

### ๐Ÿ”’ Lock-on-Active - One-time Execution
Prevent rules from firing again until agenda group changes:

```grl
rule "WelcomeEmail" lock-on-active salience 10 {
    when Customer.isNew == true
    then sendWelcomeEmail(Customer);
}
```

### โฐ Date Effective/Expires - Time-based Rules
Create **seasonal** or **time-limited** rules:

```grl
rule "ChristmasDiscount" 
    date-effective "2025-12-01T00:00:00Z"
    date-expires "2025-12-31T23:59:59Z" 
    salience 20 {
    when Order.total > 100
    then Order.seasonalDiscount = 0.25;
}
```

### ๐Ÿ”„ Combined Attributes - Complex Rules
Mix multiple attributes for sophisticated control:

```grl
rule "ComplexPaymentRule"
    agenda-group "processing"
    activation-group "payment"
    lock-on-active
    no-loop
    salience 30 {
    when
        Order.status == "pending" && Payment.method == "credit"
    then
        Order.status = "processed";
        Payment.confirmed = true;
}
```

### ๐Ÿ“Š Programmatic API
Use attributes with the Rust API:

```rust
let rule = Rule::new("MyRule", conditions, actions)
    .with_agenda_group("validation".to_string())
    .with_activation_group("discount".to_string())
    .with_lock_on_active(true)
    .with_date_effective_str("2025-12-01T00:00:00Z")?
    .with_date_expires_str("2025-12-31T23:59:59Z")?;

// Get available groups
let agenda_groups = engine.get_agenda_groups();
let activation_groups = engine.get_activation_groups();

// Workflow control
engine.set_agenda_focus("validation");
engine.execute(&facts)?;
```

## ๐Ÿค– AI Integration (NEW!)

Integrate AI/ML models seamlessly into your rules, similar to **Drools Pragmatic AI**:

### Features
- **๐Ÿค– Sentiment Analysis**: Real-time text sentiment evaluation
- **๐Ÿ›ก๏ธ Fraud Detection**: ML-powered fraud scoring and detection
- **๐Ÿ† Predictive Analytics**: Customer tier prediction and scoring
- **๐Ÿง  LLM Reasoning**: Large Language Model decision support
- **๐Ÿ“Š Real-time ML Scoring**: Dynamic model inference in rules

### Example AI Rules

```grl
rule "AI Customer Service" salience 100 {
    when
        CustomerMessage.type == "complaint"
    then
        analyzeSentiment(CustomerMessage.text);
        set(Ticket.priority, "high");
        logMessage("๐Ÿค– AI analyzing customer sentiment");
}

rule "AI Fraud Detection" salience 90 {
    when
        Transaction.amount > 1000
    then
        detectFraud(Transaction.amount, Transaction.userId);
        set(Transaction.status, "under_review");
        sendNotification("๐Ÿ›ก๏ธ Checking for potential fraud", "security@company.com");
}

rule "AI Tier Prediction" salience 80 {
    when
        Customer.tier == "pending"
    then
        predictTier(Customer.id);
        set(Customer.tierAssignedBy, "AI");
        logMessage("๐Ÿ† AI predicting customer tier");
}
```

### Register AI Functions

```rust
// Register AI-powered functions
engine.register_function("analyzeSentiment", |args, _facts| {
    let text = args[0].as_string().unwrap_or("".to_string());
    
    // Call actual AI API (OpenAI, Anthropic, Hugging Face, etc.)
    let rt = tokio::runtime::Runtime::new().unwrap();
    let sentiment = rt.block_on(async {
        call_openai_sentiment_api(&text).await
    }).unwrap_or_else(|_| "neutral".to_string());
    
    Ok(Value::String(sentiment))
});

engine.register_function("detectFraud", |args, facts| {
    let amount = args[0].as_number().unwrap_or(0.0);
    let user_id = args[1].as_string().unwrap_or("unknown".to_string());
    
    // Call actual ML fraud detection API
    let rt = tokio::runtime::Runtime::new().unwrap();
    let is_fraud = rt.block_on(async {
        call_fraud_detection_api(amount, &user_id, facts).await
    }).unwrap_or_else(|_| false);
    
    Ok(Value::Boolean(is_fraud))
});

engine.register_function("predictTier", |args, facts| {
    let customer_id = args[0].as_string().unwrap_or("unknown".to_string());
    
    // Call actual ML tier prediction API
    let rt = tokio::runtime::Runtime::new().unwrap();
    let predicted_tier = rt.block_on(async {
        call_tier_prediction_api(&customer_id, facts).await
    }).unwrap_or_else(|_| "bronze".to_string());
    
    Ok(Value::String(predicted_tier))
});
```

## ๐Ÿ“‹ Changelog

### v0.8.0 (October 2025) - Advanced Workflow Engine Implementation ๐ŸŒŠ
- **๐ŸŒŠ Advanced Workflow Engine**: Complete workflow management system with comprehensive features
  - **๐Ÿ“‹ Agenda Group Management**: Organize rules into execution phases with automatic focus transitions
  - **โฐ Scheduled Task System**: Time-based task execution with flexible scheduling and conditional triggers
  - **๐Ÿ”„ Workflow State Tracking**: Real-time workflow monitoring with start/complete lifecycle management
  - **๐ŸŽฏ Dynamic Agenda Activation**: Context-aware agenda group activation based on workflow state
  - **๐Ÿ“Š Workflow Analytics**: Detailed performance metrics including execution statistics and task monitoring
  - **๐Ÿš€ Seamless Integration**: Unified API combining rule execution with workflow orchestration
- **๐Ÿ”ง Enhanced Rule Engine**: Improved fact handling and condition evaluation
  - **Facts API Enhancement**: Extended Facts system with workflow data integration
  - **Condition Evaluation**: Optimized condition processing with better error handling
  - **Action Processing**: Enhanced action execution with workflow context awareness
- **๐Ÿงช Comprehensive Demos**: Real-world workflow examples
  - Basic order processing workflow with VIP customer routing
  - Advanced workflow with scheduled tasks and multi-phase execution
  - Complete workflow lifecycle demonstrations with detailed logging
- **๐Ÿ›ก๏ธ Production Ready**: Enhanced error handling and performance optimization for workflow scenarios

### v0.7.1 (October 2025) - Advanced Action Handlers Implementation ๐Ÿšจ
- **๐Ÿšจ Advanced Action Handlers**: Custom action execution system for external integrations
  - **Action Handler Registry**: Register custom handlers for `ActionType::Custom` execution
  - **Parameter Resolution**: Automatic fact value substitution in action parameters
  - **Facts Integration**: Full access to fact data within action handlers
  - **Error Handling**: Graceful failure handling with meaningful error messages
  - **Built-in Handler Examples**: Email, database logging, alerts, payment processing
- **๐Ÿ”ง Enhanced Custom Actions**: Fix `ActionType::Custom` from debug-only to fully functional
  - Previously: `ActionType::Custom` only printed debug messages
  - Now: Executes registered business logic handlers with real functionality
- **โšก Parameter Resolution Engine**: Smart fact reference resolution in action parameters
  - `"Customer.email"` โ†’ resolves to actual email value from facts
  - `"Order.total"` โ†’ resolves to actual order total amount
  - Supports nested fact path resolution with dot notation
- **๐Ÿงช Comprehensive Demo**: Real-world action handler examples
  - Email sending with template parameters
  - Database event logging with fact context
  - Multi-level alert system (INFO, HIGH, CRITICAL)
  - Payment processing with business rule validation
- **๐Ÿ›ก๏ธ No-Loop Protection**: Enhanced rule execution control for action-triggered rules

### v0.7.0 (October 2025) - Advanced Pattern Matching & Drools Compatibility ๐Ÿงฉ
- **๐Ÿงฉ Advanced Pattern Matching**: Complete implementation of EXISTS, NOT, and FORALL patterns
  - **EXISTS pattern**: Check if at least one fact matches condition
  - **NOT pattern**: Check if no facts match condition (using `!exists(...)`)
  - **FORALL pattern**: Check if all facts of a type match condition
  - **Complex patterns**: Combine patterns with logical operators (AND, OR, NOT)
- **๐ŸŽฏ GRL Syntax Support**: Full pattern matching support in GRL files
  - `exists(Customer.tier == "VIP")` syntax for existence checking
  - `!exists(Order.status == "pending")` syntax for non-existence
  - `forall(Order.status == "processed")` syntax for universal quantification
  - Combined patterns: `exists(...) && !exists(...) && forall(...)`
- **๐Ÿ”ง Parser Extensions**: Enhanced GRL parser with pattern matching keywords
  - Recursive pattern parsing with proper parentheses handling
  - Seamless integration with existing logical operators
  - Comprehensive parser tests for all pattern types
- **โšก Pattern Evaluation Engine**: High-performance pattern matching evaluation
  - Smart fact type detection and mapping (e.g., Customer1 โ†’ Customer)
  - Efficient fact iteration and filtering algorithms
  - Full backward compatibility with existing rule engine
- **๐Ÿงช Comprehensive Testing**: Full test coverage for pattern matching features
  - 4 dedicated pattern matcher unit tests (all passing)
  - Real-world business scenario demonstrations
  - GRL file parsing and execution integration tests
  - Multiple example files showcasing pattern matching capabilities

### v0.6.0 (October 2025) - Rule Attributes Enhancement ๐ŸŽฏ
- **๐ŸŽฏ Comprehensive Rule Attributes**: Drools-compatible rule attributes system
  - **๐Ÿ“‹ Agenda Groups**: Structured workflow control with focus management
  - **๐Ÿ”’ Activation Groups**: Mutually exclusive rule execution with salience priority
  - **๐Ÿ”’ Lock-on-Active**: Prevent rules from firing multiple times per agenda activation
  - **โฐ Date Effective/Expires**: Time-based rule activation with DateTime support
  - **๐Ÿ“Š Programmatic API**: Full Rust API for attribute management
- **๐Ÿ”ง Enhanced GRL Parser**: Support for flexible rule attribute syntax in any position
- **๐Ÿงช Comprehensive Testing**: 27/27 unit tests including new agenda management tests
- **๐Ÿ“š Complete Demo**: Full demonstration of all 4 attribute features
- **โšก Performance Optimized**: Efficient agenda focus stack and activation group management

### v0.5.0 (October 2025) - AI Integration ๐Ÿค–
- **๐Ÿค– AI-Powered Rules**: Built-in support for AI/ML model integration
  - Sentiment analysis functions for customer service automation
  - ML-powered fraud detection with real-time risk scoring
  - Predictive analytics for customer tier assignment
  - LLM reasoning for complex business decision support
  - Real-time ML scoring for dynamic pricing and recommendations
- **๐Ÿง  AI Function Registry**: Easy registration and management of AI model functions
- **๐Ÿš€ Production AI Examples**: Complete examples with simulated AI APIs
- **๐Ÿ“Š AI Insights**: Track AI model performance and decision outcomes
- **๐ŸŒ AI-Enhanced REST API**: HTTP endpoints for AI-powered rule execution

### v0.4.1 (October 2025) - Enhanced Parser & Publishing
- **๐Ÿ”ง Enhanced GRL Parser**: Improved parsing with complex nested conditions
  - Support for parentheses grouping: `(age >= 18) && (status == "active")`
  - Better handling of compound boolean expressions
  - Improved error messages and validation
- **๐Ÿ“ฆ Published to Crates.io**: Available as `rust-rule-engine = "0.4.1"`
- **๐Ÿ“š Comprehensive Examples**: Added 40+ examples covering all features
- **๐Ÿ“– Complete Documentation**: Full API documentation and usage guides

### v0.3.1 (October 2025) - REST API with Monitoring
- **๐ŸŒ Production REST API**: Complete web API with advanced analytics integration
  - Comprehensive endpoints for rule execution and monitoring
  - Real-time analytics dashboard with performance insights
  - Health monitoring and system status endpoints
  - CORS support and proper error handling
  - Sample requests and complete API documentation
  - Production-ready demo script for testing

### v0.3.0 (October 2025) - AST-Based Dependency Analysis & Advanced Analytics

## ๐Ÿš€ Quick Start

Add to your `Cargo.toml`:

```toml
[dependencies]
rust-rule-engine = "0.8.0"
chrono = "0.4"  # For date-based rule attributes

# For streaming features (optional)
rust-rule-engine = { version = "0.8.0", features = ["streaming"] }
```

### ๐Ÿ“„ File-Based Rules

Create a rule file `rules/example.grl`:

```grl
rule "AgeCheck" salience 10 {
    when
        User.Age >= 18 && User.Country == "US"
    then
        User.setIsAdult(true);
        User.setCategory("Adult");
        log("User qualified as adult");
}

rule "VIPUpgrade" salience 20 {
    when
        User.IsAdult == true && User.SpendingTotal > 1000.0
    then
        User.setIsVIP(true);
        log("User upgraded to VIP status");
}
```

```rust
use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create engine with rule file
    let mut engine = RuleEngineBuilder::new()
        .with_rule_file("rules/example.grl")?
        .build();

    // Register custom functions
    engine.register_function("User.setIsAdult", |args, _| {
        println!("Setting adult status: {:?}", args[0]);
        Ok(Value::Boolean(true))
    });

    engine.register_function("User.setCategory", |args, _| {
        println!("Setting category: {:?}", args[0]);
        Ok(Value::String(args[0].to_string()))
    });

    // Create facts
    let facts = Facts::new();
    let mut user = HashMap::new();
    user.insert("Age".to_string(), Value::Integer(25));
    user.insert("Country".to_string(), Value::String("US".to_string()));
    user.insert("SpendingTotal".to_string(), Value::Number(1500.0));

    facts.add_value("User", Value::Object(user))?;

    // Execute rules
    let result = engine.execute(&facts)?;
    println!("Rules fired: {}", result.rules_fired);

    Ok(())
}
```

### ๐Ÿ“ Inline String Rules

Define rules directly in your code:

```rust
use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let grl_rules = r#"
        rule "HighValueCustomer" salience 20 {
            when
                Customer.TotalSpent > 1000.0
            then
                sendWelcomeEmail(Customer.Email, "GOLD");
                log("Customer upgraded to GOLD tier");
        }

        rule "LoyaltyBonus" salience 15 {
            when
                Customer.OrderCount >= 10
            then
                applyLoyaltyBonus(Customer.Id, 50.0);
                log("Loyalty bonus applied");
        }
    "#;

    // Create engine with inline rules
    let mut engine = RuleEngineBuilder::new()
        .with_inline_grl(grl_rules)?
        .build();

    // Register custom functions
    engine.register_function("sendWelcomeEmail", |args, _| {
        println!("๐Ÿ“ง Welcome email sent to {:?} for {:?} tier", args[0], args[1]);
        Ok(Value::Boolean(true))
    });

    engine.register_function("applyLoyaltyBonus", |args, _| {
        println!("๐Ÿ’ฐ Loyalty bonus of {:?} applied to customer {:?}", args[1], args[0]);
        Ok(Value::Number(args[1].as_number().unwrap_or(0.0)))
    });

    // Create facts
    let facts = Facts::new();
    let mut customer = HashMap::new();
    customer.insert("TotalSpent".to_string(), Value::Number(1250.0));
    customer.insert("OrderCount".to_string(), Value::Integer(12));
    customer.insert("Email".to_string(), Value::String("john@example.com".to_string()));
    customer.insert("Id".to_string(), Value::String("CUST001".to_string()));

    facts.add_value("Customer", Value::Object(customer))?;

    // Execute rules
    let result = engine.execute(&facts)?;
    println!("Rules fired: {}", result.rules_fired);

    Ok(())
}
```

### ๐ŸŽฏ Rule Attributes Quick Example

Experience the power of Rule Attributes v0.6.0 with workflow control:

```rust
use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let attribute_rules = r#"
        rule "ValidateAge" agenda-group "validation" salience 10 {
            when
                User.age >= 18
            then
                User.status = "valid";
                log("Age validation passed");
        }

        rule "ProcessPayment" agenda-group "processing" salience 10 {
            when
                User.status == "valid"
            then
                Order.status = "processed";
                log("Payment processed");
        }

        rule "PremiumDiscount" activation-group "discount" salience 10 {
            when Customer.tier == "premium"
            then Order.discount = 0.20;
        }

        rule "GoldDiscount" activation-group "discount" salience 8 {
            when Customer.tier == "gold"
            then Order.discount = 0.15;
        }

        rule "WelcomeEmail" lock-on-active salience 15 {
            when Customer.isNew == true
            then sendWelcomeEmail(Customer.email);
        }
    "#;

    // Create engine with attribute rules
    let mut engine = RuleEngineBuilder::new()
        .with_inline_grl(attribute_rules)?
        .build();

    // Create facts
    let facts = Facts::new();
    
    // Add user data
    let mut user = HashMap::new();
    user.insert("age".to_string(), Value::Integer(25));
    user.insert("status".to_string(), Value::String("pending".to_string()));
    facts.add_value("User", Value::Object(user))?;

    let mut customer = HashMap::new();
    customer.insert("tier".to_string(), Value::String("premium".to_string()));
    customer.insert("isNew".to_string(), Value::Boolean(true));
    customer.insert("email".to_string(), Value::String("user@example.com".to_string()));
    facts.add_value("Customer", Value::Object(customer))?;

    let mut order = HashMap::new();
    order.insert("status".to_string(), Value::String("pending".to_string()));
    order.insert("discount".to_string(), Value::Number(0.0));
    facts.add_value("Order", Value::Object(order))?;

    // ๐Ÿ” Phase 1: Validation workflow
    engine.set_agenda_focus("validation");
    let result1 = engine.execute(&facts)?;
    println!("โœ… Validation phase: {} rules fired", result1.rules_fired);

    // โš™๏ธ Phase 2: Processing workflow  
    engine.set_agenda_focus("processing");
    let result2 = engine.execute(&facts)?;
    println!("๐Ÿ”„ Processing phase: {} rules fired", result2.rules_fired);

    // ๐ŸŽฏ Phase 3: Discount (only ONE rule fires due to activation-group)
    engine.set_agenda_focus("MAIN"); // Default group
    let result3 = engine.execute(&facts)?;
    println!("๐Ÿ’ฐ Discount phase: {} rules fired (mutually exclusive)", result3.rules_fired);

    Ok(())
}
```

## ๐ŸŽจ Visual Rule Builder (NEW!)

**Create rules visually with our drag-and-drop interface!**

๐ŸŒ **[Visual Rule Builder](https://visual-rule-builder.amalthea.cloud/)** - Build GRL rules without coding!

### โœจ Features
- **๐ŸŽฏ Drag & Drop Interface**: Intuitive visual rule creation
- **๐Ÿ“ Real-time GRL Generation**: See your rules as GRL code instantly
- **๐Ÿ” Syntax Validation**: Automatic validation and error checking
- **๐Ÿ“‹ Template Library**: Pre-built rule templates for common scenarios
- **๐Ÿ’พ Export & Import**: Save and load your rule configurations
- **๐Ÿš€ One-Click Integration**: Copy-paste generated GRL directly into your Rust projects

### ๐ŸŽฎ Quick Demo

1. **Visit**: [https://visual-rule-builder.amalthea.cloud/]https://visual-rule-builder.amalthea.cloud/
2. **Build**: Drag conditions and actions to create your business logic
3. **Generate**: Get clean, optimized GRL code automatically
4. **Integrate**: Copy the GRL into your Rust Rule Engine project

### ๐Ÿ“š Perfect For
- **๐ŸŽ“ Learning**: Understand rule structure and syntax visually
- **โšก Rapid Prototyping**: Quickly build and test rule logic
- **๐Ÿ‘ฅ Business Users**: Create rules without programming knowledge
- **๐Ÿ”ง Complex Rules**: Visualize intricate business logic flows

### ๐Ÿ’ก Example Workflow

```grl
// Generated from Visual Builder
rule "CustomerUpgrade" salience 20 {
    when
        Customer.totalSpent > 1000.0 && 
        Customer.loyaltyYears >= 2 &&
        !exists(Customer.tier == "VIP")
    then
        Customer.tier = "VIP";
        sendWelcomePackage(Customer.email);
        log("Customer upgraded to VIP status");
}
```

**Try it now**: Build this rule visually in under 2 minutes! ๐Ÿš€

---

## ๐Ÿค– Complete AI Integration Example

Here's a complete example showing how to build an AI-powered business rule system:

```rust
use rust_rule_engine::{RuleEngineBuilder, Value, Facts};
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let ai_rules = r#"
        rule "AI Customer Service" salience 100 {
            when
                CustomerMessage.type == "complaint"
            then
                analyzeSentiment(CustomerMessage.text);
                set(Ticket.priority, "high");
                logMessage("๐Ÿค– AI analyzing customer sentiment");
        }

        rule "AI Fraud Detection" salience 90 {
            when
                Transaction.amount > 1000
            then
                detectFraud(Transaction.amount, Transaction.userId);
                set(Transaction.status, "under_review");
                sendNotification("๐Ÿ›ก๏ธ Checking for potential fraud", "security@company.com");
        }

        rule "AI Tier Prediction" salience 80 {
            when
                Customer.tier == "pending"
            then
                predictTier(Customer.id);
                set(Customer.tierAssignedBy, "AI");
                logMessage("๐Ÿ† AI predicting customer tier");
        }

        rule "LLM Decision Support" salience 70 {
            when
                Customer.needsReview == true
            then
                askLLM("Should we approve this customer for premium tier?", Customer.id);
                set(Customer.reviewedBy, "AI-LLM");
                logMessage("๐Ÿง  LLM analyzing customer for approval");
        }

        rule "ML Dynamic Pricing" salience 60 {
            when
                Product.category == "dynamic" && Customer.tier != "unknown"
            then
                calculateMLPrice(Product.basePrice, Customer.tier, Product.demand);
                set(Product.priceSource, "ML");
                logMessage("๐Ÿ“Š ML calculating dynamic price");
        }
    "#;

    let mut engine = RuleEngineBuilder::new()
        .with_inline_grl(ai_rules)?
        .with_max_cycles(5)
        .build();

    // Register AI functions (in production, these would call real AI APIs)
    engine.register_function("analyzeSentiment", |args, facts| {
        let text = args[0].as_string().unwrap_or("".to_string());
        
        // Simulate sentiment analysis (OpenAI, Anthropic, HuggingFace, etc.)
        let sentiment = if text.contains("terrible") || text.contains("awful") {
            "negative"
        } else if text.contains("love") || text.contains("great") {
            "positive"
        } else {
            "neutral"
        };
        
        // Store result in facts for other rules
        facts.set_value("Analysis.sentiment", Value::String(sentiment.to_string()))?;
        
        println!("๐Ÿค– Sentiment Analysis: '{}' โ†’ {}", text, sentiment);
        Ok(Value::String(sentiment.to_string()))
    });

    engine.register_function("detectFraud", |args, facts| {
        let amount = args[0].as_number().unwrap_or(0.0);
        let user_id = args[1].as_string().unwrap_or("unknown".to_string());
        
        // Simulate ML fraud detection model
        let risk_score = if amount > 5000.0 { 0.95 } else if amount > 2000.0 { 0.75 } else { 0.2 };
        let is_fraud = risk_score > 0.8;
        
        facts.set_value("FraudCheck.riskScore", Value::Number(risk_score))?;
        facts.set_value("FraudCheck.isFraud", Value::Boolean(is_fraud))?;
        
        println!("๐Ÿ›ก๏ธ Fraud Detection: Amount {} for user {} โ†’ Risk: {:.2}, Fraud: {}", 
                amount, user_id, risk_score, is_fraud);
        
        Ok(Value::Boolean(is_fraud))
    });

    engine.register_function("predictTier", |args, facts| {
        let customer_id = args[0].as_string().unwrap_or("unknown".to_string());
        
        // Simulate customer tier prediction model
        let predicted_tiers = ["bronze", "silver", "gold", "platinum"];
        let tier = predicted_tiers[customer_id.len() % predicted_tiers.len()];
        
        facts.set_value("TierPrediction.tier", Value::String(tier.to_string()))?;
        facts.set_value("TierPrediction.confidence", Value::Number(0.87))?;
        
        println!("๐Ÿ† Tier Prediction: Customer {} โ†’ {} tier (87% confidence)", customer_id, tier);
        Ok(Value::String(tier.to_string()))
    });

    engine.register_function("askLLM", |args, facts| {
        let question = args[0].as_string().unwrap_or("".to_string());
        let customer_id = args[1].as_string().unwrap_or("unknown".to_string());
        
        // Simulate LLM reasoning (GPT-4, Claude, etc.)
        let decision = if customer_id.contains("VIP") { "approve" } else { "review_further" };
        let reasoning = format!("Based on customer profile analysis, recommendation: {}", decision);
        
        facts.set_value("LLMDecision.result", Value::String(decision.to_string()))?;
        facts.set_value("LLMDecision.reasoning", Value::String(reasoning.clone()))?;
        
        println!("๐Ÿง  LLM Analysis: {} โ†’ {}", question, reasoning);
        Ok(Value::String(decision.to_string()))
    });

    engine.register_function("calculateMLPrice", |args, facts| {
        let base_price = args[0].as_number().unwrap_or(100.0);
        let tier = args[1].as_string().unwrap_or("bronze".to_string());
        let demand = args[2].as_number().unwrap_or(1.0);
        
        // Simulate ML pricing model
        let tier_multiplier = match tier.as_str() {
            "platinum" => 0.8,
            "gold" => 0.9,
            "silver" => 0.95,
            _ => 1.0,
        };
        
        let dynamic_price = base_price * tier_multiplier * demand;
        
        facts.set_value("Pricing.dynamicPrice", Value::Number(dynamic_price))?;
        facts.set_value("Pricing.discount", Value::Number((1.0 - tier_multiplier) * 100.0))?;
        
        println!("๐Ÿ“Š ML Pricing: Base ${:.2} ร— {} tier ร— {:.1}x demand โ†’ ${:.2}", 
                base_price, tier, demand, dynamic_price);
        
        Ok(Value::Number(dynamic_price))
    });

    // Helper functions
    engine.register_function("set", |args, facts| {
        if args.len() >= 2 {
            let key = args[0].as_string().unwrap_or("unknown".to_string());
            facts.set_value(&key, args[1].clone())?;
        }
        Ok(Value::Boolean(true))
    });

    engine.register_function("logMessage", |args, _| {
        println!("๐Ÿ“ {}", args[0]);
        Ok(Value::Boolean(true))
    });

    engine.register_function("sendNotification", |args, _| {
        println!("๐Ÿ“ง Notification: {} โ†’ {}", args[0], args[1]);
        Ok(Value::Boolean(true))
    });

    // Set up test facts
    let facts = Facts::new();
    
    // Customer service scenario
    let mut customer_message = HashMap::new();
    customer_message.insert("type".to_string(), Value::String("complaint".to_string()));
    customer_message.insert("text".to_string(), Value::String("This service is terrible!".to_string()));
    facts.add_value("CustomerMessage", Value::Object(customer_message))?;

    // Transaction for fraud detection
    let mut transaction = HashMap::new();
    transaction.insert("amount".to_string(), Value::Number(2500.0));
    transaction.insert("userId".to_string(), Value::String("user123".to_string()));
    facts.add_value("Transaction", Value::Object(transaction))?;

    // Customer for tier prediction
    let mut customer = HashMap::new();
    customer.insert("id".to_string(), Value::String("VIP_customer_456".to_string()));
    customer.insert("tier".to_string(), Value::String("pending".to_string()));
    customer.insert("needsReview".to_string(), Value::Boolean(true));
    facts.add_value("Customer", Value::Object(customer))?;

    // Product for dynamic pricing
    let mut product = HashMap::new();
    product.insert("category".to_string(), Value::String("dynamic".to_string()));
    product.insert("basePrice".to_string(), Value::Number(150.0));
    product.insert("demand".to_string(), Value::Number(1.3));
    facts.add_value("Product", Value::Object(product))?;

    let mut ticket = HashMap::new();
    facts.add_value("Ticket", Value::Object(ticket))?;

    // Execute AI-powered rules
    println!("\n๐Ÿš€ Executing AI-Powered Rule Engine...\n");
    let result = engine.execute(&facts)?;
    
    println!("\n๐Ÿ“Š Execution Results:");
    println!("   Rules fired: {}", result.rules_fired);
    println!("   Cycles: {}", result.cycles);
    println!("   Duration: {:?}", result.duration);
    
    Ok(())
}
```

### ๐Ÿ” Dependency Analysis Example

```rust
use rust_rule_engine::dependency::DependencyAnalyzer;

fn analyze_rule_dependencies() -> Result<(), Box<dyn std::error::Error>> {
    let grl_content = r#"
        rule "VIPUpgrade" {
            when Customer.TotalSpent > 1000.0 && Customer.IsVIP == false
            then 
                Customer.setIsVIP(true);
                Customer.setTier("GOLD");
        }
        
        rule "VIPBenefits" {
            when Customer.IsVIP == true
            then
                Order.setDiscountRate(0.15);
                log("VIP discount applied");
        }
    "#;

    let analyzer = DependencyAnalyzer::new();
    let analysis = analyzer.analyze_grl_rules(grl_content)?;
    
    // Show detected dependencies
    for rule in &analysis.rules {
        println!("๐Ÿ“‹ Rule '{}' reads: {:?}", rule.name, rule.reads);
        println!("โœ๏ธ  Rule '{}' writes: {:?}", rule.name, rule.writes);
    }
    
    // Check for conflicts
    let conflicts = analysis.find_conflicts();
    if conflicts.is_empty() {
        println!("โœ… No conflicts detected - rules can execute safely in parallel");
    } else {
        println!("โš ๏ธ  {} conflicts detected", conflicts.len());
    }
    
    Ok(())
}
```

## ๐ŸŽฏ GRL Rule Language Features

### Supported Syntax

```grl
// Basic rule
rule "RuleName" salience 10 {
    when
        Object.Property > 100 &&
        Object.Status == "ACTIVE"
    then
        Object.setCategory("HIGH_VALUE");
        processTransaction(Object.Id, Object.Amount);
        log("Rule executed successfully");
}

// Rule with no-loop protection (prevents infinite self-activation)
rule "ScoreUpdater" no-loop salience 15 {
    when
        Player.score < 100
    then
        set(Player.score, Player.score + 10);
        log("Score updated with no-loop protection");
}
```

### Operators

- **Comparison**: `>`, `>=`, `<`, `<=`, `==`, `!=`
- **Logical**: `&&`, `||` 
- **Value Types**: Numbers, Strings (quoted), Booleans (`true`/`false`)

### Actions

- **Method Calls**: `Object.method(args)`
- **Function Calls**: `functionName(args)`
- **Logging**: `log("message")`

## ๐Ÿ“š Examples

### ๐Ÿ›’ E-commerce Rules

```grl
rule "VIPCustomer" salience 20 {
    when
        Customer.TotalSpent > 5000.0 && Customer.YearsActive >= 2
    then
        Customer.setTier("VIP");
        sendWelcomePackage(Customer.Email, "VIP");
        applyDiscount(Customer.Id, 15.0);
        log("Customer upgraded to VIP");
}

rule "LoyaltyReward" salience 15 {
    when
        Customer.OrderCount >= 50
    then
        addLoyaltyPoints(Customer.Id, 500);
        log("Loyalty reward applied");
}
```

### ๐Ÿš— Vehicle Monitoring

```grl
rule "SpeedLimit" salience 25 {
    when
        Vehicle.Speed > Vehicle.SpeedLimit
    then
        triggerAlert(Vehicle.Id, "SPEED_VIOLATION");
        logViolation(Vehicle.Driver, Vehicle.Speed);
        Vehicle.setStatus("FLAGGED");
}

rule "MaintenanceDue" salience 10 {
    when
        Vehicle.Mileage > Vehicle.NextMaintenance
    then
        scheduleService(Vehicle.Id, Vehicle.Mileage);
        notifyDriver(Vehicle.Driver, "Maintenance due");
}
```

### ๐Ÿงฉ Pattern Matching Examples

```grl
rule "VIPServiceActivation" "Activate VIP service when VIP customer exists" salience 20 {
    when
        exists(Customer.tier == "VIP")
    then
        System.vipServiceActive = true;
        log("VIP service activated - VIP customer detected");
}

rule "MarketingCampaign" "Send marketing when no pending orders" salience 15 {
    when
        !exists(Order.status == "pending")
    then
        Marketing.emailSent = true;
        sendMarketingEmail();
        log("Marketing campaign sent - no pending orders");
}

rule "ShippingEnable" "Enable shipping when all orders processed" salience 10 {
    when
        forall(Order.status == "processed")
    then
        Shipping.enabled = true;
        enableShippingService();
        log("Shipping enabled - all orders processed");
}

rule "ComplexBusinessLogic" "Complex pattern combination" salience 25 {
    when
        exists(Customer.tier == "VIP") && 
        !exists(Alert.priority == "high") &&
        forall(Order.status == "processed")
    then
        System.premiumModeEnabled = true;
        activatePremiumFeatures();
        log("Premium mode activated - all conditions met");
}
```

**Run Pattern Matching Examples:**

```bash
# Programmatic pattern matching demo
cargo run --example pattern_matching_demo

# GRL file-based pattern matching
cargo run --example simple_pattern_matching_grl

# Complex patterns from GRL files  
cargo run --example pattern_matching_from_grl
```

## ๐ŸŒ REST API with Monitoring

The engine provides a production-ready REST API with comprehensive analytics monitoring.

### Quick Start

```bash
# Run the REST API server with full analytics monitoring
cargo run --example rest_api_monitoring

# Or use the demo script for testing
./demo_rest_api.sh
```

### Available Endpoints

**Rule Execution:**
- `POST /api/v1/rules/execute` - Execute rules with provided facts
- `POST /api/v1/rules/batch` - Execute rules in batch mode

**Analytics & Monitoring:**
- `GET /api/v1/analytics/dashboard` - Comprehensive analytics dashboard
- `GET /api/v1/analytics/stats` - Overall performance statistics  
- `GET /api/v1/analytics/recent` - Recent execution activity
- `GET /api/v1/analytics/recommendations` - Performance optimization recommendations
- `GET /api/v1/analytics/rules/{rule_name}` - Rule-specific analytics

**System:**
- `GET /` - API documentation
- `GET /api/v1/health` - Health check
- `GET /api/v1/status` - System status

### Example Requests

**Execute Rules:**
```bash
curl -X POST "http://localhost:3000/api/v1/rules/execute" \
  -H "Content-Type: application/json" \
  -d '{
    "facts": {
      "Customer": {
        "Age": 35,
        "IsNew": false,
        "OrderCount": 75,
        "TotalSpent": 15000.0,
        "YearsActive": 3,
        "Email": "customer@example.com"
      },
      "Order": {
        "Amount": 750.0,
        "CustomerEmail": "customer@example.com"
      }
    }
  }'
```

**Analytics Dashboard:**
```bash
curl "http://localhost:3000/api/v1/analytics/dashboard"
```

**Sample Response:**
```json
{
  "overall_stats": {
    "total_executions": 1250,
    "avg_execution_time_ms": 2.3,
    "success_rate": 99.8,
    "rules_per_second": 435.2,
    "uptime_hours": 24.5
  },
  "top_performing_rules": [
    {
      "name": "VIPCustomerRule",
      "execution_count": 340,
      "avg_duration_ms": 1.8,
      "success_rate": 100.0
    }
  ],
  "recommendations": [
    "Consider caching customer data to improve performance",
    "Rule 'ComplexValidation' shows high execution time"
  ]
}
```

### Production Configuration

The REST API includes:
- **Real-time Analytics**: Live performance monitoring
- **Health Checks**: Comprehensive system health monitoring
- **CORS Support**: Cross-origin resource sharing
- **Error Handling**: Proper HTTP status codes and error messages
- **Sampling**: Configurable analytics sampling for high-volume scenarios
- **Memory Management**: Automatic cleanup and retention policies

## โšก Performance & Architecture

### Benchmarks

Performance benchmarks on a typical development machine:

```text
Simple Rule Execution:
โ€ข Single condition rule:     ~4.5 ยตs per execution
โ€ข With custom function call: ~4.8 ยตs per execution

Complex Rule Execution:
โ€ข Multi-condition rules:     ~2.7 ยตs per execution  
โ€ข 3 rules with conditions:   ~2.8 ยตs per execution

Rule Parsing:
โ€ข Simple GRL rule:          ~1.1 ยตs per parse
โ€ข Medium complexity rule:   ~1.4 ยตs per parse  
โ€ข Complex multi-line rule:  ~2.0 ยตs per parse

Facts Operations:
โ€ข Create complex facts:     ~1.8 ยตs
โ€ข Get nested fact:          ~79 ns
โ€ข Set nested fact:          ~81 ns

Memory Usage:
โ€ข Base engine overhead:     ~10KB
โ€ข Per rule storage:         ~1-2KB  
โ€ข Per fact storage:         ~100-500 bytes
```

*Run benchmarks: `cargo bench`*

**Key Performance Insights:**
- **Ultra-fast execution**: Rules execute in microseconds
- **Efficient parsing**: GRL rules parse in under 2ยตs  
- **Optimized facts**: Nanosecond-level fact operations
- **Low memory footprint**: Minimal overhead per rule
- **Scales linearly**: Performance consistent across rule counts

### ๐Ÿ† **Performance Comparison**

Benchmark comparison with other rule engines:

```text
Language/Engine        Rule Execution    Memory Usage    Startup Time
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Rust (this engine)     2-5ยตs            1-2KB/rule     ~1ms
.NET Rules Engine       15-50ยตs          3-8KB/rule     ~50-100ms
Go Rules Framework      10-30ยตs          2-5KB/rule     ~10-20ms
Java Drools            50-200ยตs          5-15KB/rule    ~200-500ms
Python rule-engine     500-2000ยตs        8-20KB/rule    ~100-300ms
```

**Rust Advantages:**
- **10x faster** than .NET rule engines
- **5x faster** than Go-based rule frameworks  
- **50x faster** than Java Drools
- **400x faster** than Python implementations
- **Zero GC pauses** (unlike .NET/Java/Go)
- **Minimal memory footprint** 
- **Instant startup** time

**Why Rust Wins:**
- No garbage collection overhead
- Zero-cost abstractions
- Direct memory management
- LLVM optimizations
- No runtime reflection costs

### Key Design Decisions

- **GRL-Only**: Removed JSON support for cleaner, focused API
- **Dual Sources**: Support both file-based and inline rule definitions
- **Custom Functions**: Extensible function registry for business logic
- **Builder Pattern**: Fluent API for easy engine configuration
- **Type Safety**: Leverages Rust's type system for runtime safety
- **Zero-Copy**: Efficient string and memory management

## ๐Ÿ” Advanced Dependency Analysis (v0.3.0+)

The rule engine features sophisticated **AST-based dependency analysis** that automatically detects field dependencies and potential conflicts between rules.

### Smart Field Detection

```rust
use rust_rule_engine::{RuleEngineBuilder, dependency::DependencyAnalyzer};

// Automatic field dependency detection
let rules = r#"
    rule "DiscountRule" {
        when Customer.VIP == true && Order.Amount > 100.0
        then 
            Order.setDiscount(0.2);
            Customer.setPoints(Customer.Points + 50);
    }
    
    rule "ShippingRule" {
        when Order.Amount > 50.0
        then
            Order.setFreeShipping(true);
            log("Free shipping applied");
    }
"#;

let analyzer = DependencyAnalyzer::new();
let analysis = analyzer.analyze_grl_rules(rules)?;

// Automatically detected dependencies:
// DiscountRule reads: [Customer.VIP, Order.Amount, Customer.Points]
// DiscountRule writes: [Order.Discount, Customer.Points]
// ShippingRule reads: [Order.Amount]  
// ShippingRule writes: [Order.FreeShipping]
```

### Conflict Detection

```rust
// Detect read-write conflicts between rules
let conflicts = analysis.find_conflicts();
for conflict in conflicts {
    println!("โš ๏ธ  Conflict: {} reads {} while {} writes {}",
        conflict.reader_rule, conflict.field,
        conflict.writer_rule, conflict.field
    );
}

// Smart execution ordering based on dependencies
let execution_order = analysis.suggest_execution_order();
```

### Advanced Features

- **๐ŸŽฏ AST-Based Analysis**: Proper parsing instead of regex pattern matching
- **๐Ÿ”„ Recursive Conditions**: Handles nested condition groups (AND/OR/NOT)
- **๐Ÿง  Function Side-Effects**: Infers field modifications from function calls
- **โšก Zero False Positives**: Accurate dependency detection
- **๐Ÿ“Š Conflict Resolution**: Automatic rule ordering suggestions
- **๐Ÿš€ Parallel Safety**: Enables safe concurrent rule execution

## ๐Ÿ“‹ API Reference

### Core Types

```rust
// Main engine builder
RuleEngineBuilder::new()
    .with_rule_file("path/to/rules.grl")?
    .with_inline_grl("rule content")?
    .with_config(config)
    .build()

// Value types
Value::Integer(42)
Value::Number(3.14)
Value::String("text".to_string())
Value::Boolean(true)
Value::Object(HashMap<String, Value>)

// Facts management
let facts = Facts::new();
facts.add_value("Object", value)?;
facts.get("Object")?;

// Execution results
result.rules_fired       // Number of rules that executed
result.cycle_count       // Number of execution cycles
result.execution_time    // Duration of execution
```

### Function Registration

```rust
engine.register_function("functionName", |args, facts| {
    // args: Vec<Value> - function arguments
    // facts: &Facts - current facts state
    // Return: Result<Value, RuleEngineError>
    
    let param1 = &args[0];
    let param2 = args[1].as_number().unwrap_or(0.0);
    
    // Your custom business logic here
    println!("Function called with: {:?}", args);
    
    Ok(Value::String("Success".to_string()))
});
```

## โšก Parallel Rule Execution

The engine supports parallel execution for improved performance with large rule sets:

```rust
use rust_rule_engine::engine::parallel::{ParallelEngine, ParallelConfig};

// Create parallel engine with custom configuration
let config = ParallelConfig {
    enabled: true,
    max_threads: 4,
};

let mut engine = ParallelEngine::new(config);

// Add rules and facts
engine.add_rule(rule);
engine.insert_fact("User", user_data);

// Execute rules in parallel
let result = engine.execute_parallel(10).await;
println!("Rules fired: {}", result.total_rules_fired);
println!("Execution time: {:?}", result.execution_time);
println!("Parallel speedup: {:.2}x", result.parallel_speedup);
```

### Parallel Execution Examples

```bash
# Simple parallel demo
cargo run --example simple_parallel_demo

# Performance comparison
cargo run --example financial_stress_test
```

## ๐ŸŒ Distributed & Cloud Features

Scale your rule engine across multiple nodes for high-performance distributed processing:

### Architecture Overview

```
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Load Balancer     โ”‚
                    โ”‚   (Route Requests)  โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                               โ”‚
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ”‚                      โ”‚                      โ”‚
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”            โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”            โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚ Node 1  โ”‚            โ”‚ Node 2  โ”‚            โ”‚ Node 3  โ”‚
   โ”‚Validationโ”‚           โ”‚ Pricing โ”‚            โ”‚ Loyalty โ”‚
   โ”‚  Rules  โ”‚            โ”‚  Rules  โ”‚            โ”‚  Rules  โ”‚
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜            โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜            โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
        โ”‚                      โ”‚                      โ”‚
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                               โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Shared Data       โ”‚
                    โ”‚ (Redis/PostgreSQL)  โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

### Performance Benefits

- **โšก 3x Performance**: Parallel processing across specialized nodes
- **๐Ÿ›ก๏ธ Fault Tolerance**: If one node fails, others continue operation
- **๐Ÿ“ˆ Horizontal Scaling**: Add nodes to increase capacity
- **๐ŸŒ Geographic Distribution**: Deploy closer to users for reduced latency

### Quick Demo

```bash
# Compare single vs distributed processing
cargo run --example distributed_concept_demo
```

**Results:**
```
Single Node:    1.4 seconds (sequential)
Distributed:    0.47 seconds (parallel)
โ†’ 3x Performance Improvement!
```

### Implementation Guide

See our comprehensive guides:
- ๐Ÿ“š [Distributed Architecture Guide]docs/distributed_features_guide.md
- ๐Ÿš€ [Real-world Examples]docs/distributed_explained.md
- ๐Ÿ”ง [Implementation Roadmap]docs/distributed_architecture.md

### Cloud Deployment

Deploy on major cloud platforms:

**Kubernetes:**
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: rule-engine-workers
spec:
  replicas: 3
  selector:
    matchLabels:
      app: rule-engine
```

**Docker:**
```dockerfile
FROM rust:alpine
COPY target/release/rust-rule-engine /app/
EXPOSE 8080
CMD ["/app/rust-rule-engine"]
```

### When to Use Distributed Architecture

โœ… **Recommended for:**
- High traffic (>10,000 requests/day)
- Complex rule sets (>500 rules)
- High availability requirements
- Geographic distribution needs

โŒ **Not needed for:**
- Simple applications (<100 rules)
- Low traffic scenarios
- Development/prototyping
- Limited infrastructure budget

## ๐Ÿงช All Examples

### Core Features
```bash
# Basic rule execution
cargo run --example grule_demo

# E-commerce rules
cargo run --example ecommerce

# Custom functions
cargo run --example custom_functions_demo

# Method calls
cargo run --example method_calls_demo
```

### Workflow Engine (v0.8.0)
```bash
# Basic workflow demo with order processing
cargo run --example workflow_engine_demo

# Advanced workflow with scheduled tasks
cargo run --example advanced_workflow_demo
```

### Action Handlers (v0.7.1)
```bash
# Action handlers with programmatic API
cargo run --example action_handlers_demo

# Action handlers from GRL files
cargo run --example action_handlers_grl_demo
```

### Performance & Scaling
```bash
# Parallel processing comparison
cargo run --example simple_parallel_demo

# Financial stress testing
cargo run --example financial_stress_test

# Distributed architecture demo
cargo run --example distributed_concept_demo
```

### Advanced Features
```bash
# Pattern matching (v0.7.0)
cargo run --example pattern_matching_demo
cargo run --example simple_pattern_matching_grl
cargo run --example pattern_matching_from_grl

# REST API with analytics
cargo run --example rest_api_monitoring

# Analytics and monitoring
cargo run --example analytics_demo

# Rule file processing
cargo run --example rule_file_functions_demo

# Advanced dependency analysis
cargo run --example advanced_dependency_demo
```

### Production Examples
```bash
# Fraud detection system
cargo run --example fraud_detection

# Complete speedup demo
cargo run --example complete_speedup_demo

# Debug conditions
cargo run --example debug_conditions
```

## ๐ŸŒŠ Streaming Rule Engine (v0.2.0+)

For real-time event processing, enable the `streaming` feature:
```

## ๐ŸŒŠ Streaming Rule Engine (v0.2.0+)

For real-time rule processing with streaming data:

```rust
use rust_rule_engine::streaming::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut engine = StreamRuleEngine::new();
    
    // Add streaming rules
    engine.add_rule(r#"
    rule "HighVolumeAlert" {
        when
            WindowEventCount > 100 && volumeSum > 1000000
        then
            AlertService.trigger("High volume detected");
    }
    "#).await?;
    
    // Register action handlers
    engine.register_action_handler("AlertService", |action| {
        println!("๐Ÿšจ Alert: {:?}", action.parameters);
    }).await;
    
    // Start processing
    engine.start().await?;
    
    // Send events
    let event = StreamEvent::new("TradeEvent", data, "exchange");
    engine.send_event(event).await?;
    
    Ok(())
}
```

**Streaming Features:**
- **โฐ Time Windows**: Sliding/tumbling window aggregations
- **๐Ÿ“Š Real-time Analytics**: Count, sum, average, min/max over windows  
- **๐ŸŽฏ Pattern Matching**: Event correlation and filtering
- **โšก High Throughput**: Async processing with backpressure handling
- **๐Ÿšจ Action Handlers**: Custom callbacks for rule consequences

### Real-World Integration Examples

#### ๐Ÿ”Œ **Kafka Consumer**
```rust
use rdkafka::consumer::{Consumer, StreamConsumer};

async fn consume_from_kafka(engine: Arc<StreamRuleEngine>) {
    let consumer: StreamConsumer = ClientConfig::new()
        .set("group.id", "trading-group")
        .set("bootstrap.servers", "localhost:9092")
        .create().unwrap();
    
    consumer.subscribe(&["trading-events"]).unwrap();
    
    loop {
        match consumer.recv().await {
            Ok(message) => {
                let event = parse_kafka_message(message);
                engine.send_event(event).await?;
            }
            Err(e) => eprintln!("Kafka error: {}", e),
        }
    }
}
```

#### ๐ŸŒ **WebSocket Stream**
```rust
use tokio_tungstenite::{connect_async, tungstenite::Message};

async fn consume_from_websocket(engine: Arc<StreamRuleEngine>) {
    let (ws_stream, _) = connect_async("wss://api.exchange.com/stream").await?;
    let (_, mut read) = ws_stream.split();
    
    while let Some(msg) = read.next().await {
        match msg? {
            Message::Text(text) => {
                let trade_data: TradeData = serde_json::from_str(&text)?;
                let event = convert_to_stream_event(trade_data);
                engine.send_event(event).await?;
            }
            _ => {}
        }
    }
}
```

#### ๐Ÿ”„ **HTTP API Polling**
```rust
async fn poll_trading_api(engine: Arc<StreamRuleEngine>) {
    let client = reqwest::Client::new();
    let mut interval = interval(Duration::from_secs(1));
    
    loop {
        interval.tick().await;
        
        match client.get("https://api.exchange.com/trades").send().await {
            Ok(response) => {
                let trades: Vec<Trade> = response.json().await?;
                
                for trade in trades {
                    let event = StreamEvent::new(
                        "TradeEvent",
                        trade.to_hashmap(),
                        "exchange_api"
                    );
                    engine.send_event(event).await?;
                }
            }
            Err(e) => eprintln!("API error: {}", e),
        }
    }
}
```

#### ๐Ÿ—„๏ธ **Database Change Streams**
```rust
async fn watch_database_changes(engine: Arc<StreamRuleEngine>) {
    let mut change_stream = db.collection("trades")
        .watch(None, None).await?;
    
    while let Some(change) = change_stream.next().await {
        let change_doc = change?;
        
        if let Some(full_document) = change_doc.full_document {
            let event = StreamEvent::new(
                "DatabaseChange",
                document_to_hashmap(full_document),
                "mongodb"
            );
            engine.send_event(event).await?;
        }
    }
}
```

#### ๐Ÿ“‚ **File Watching**
```rust
use notify::{Watcher, RecursiveMode, watcher};

async fn watch_log_files(engine: Arc<StreamRuleEngine>) {
    let (tx, mut rx) = tokio::sync::mpsc::channel(100);
    
    let mut watcher = watcher(move |res| {
        // Parse log lines into StreamEvents
    }, Duration::from_secs(1))?;
    
    watcher.watch("/var/log/trading", RecursiveMode::Recursive)?;
    
    while let Some(file_event) = rx.recv().await {
        let stream_event = parse_log_event(file_event);
        engine.send_event(stream_event).await?;
    }
}
```

### Use Case Examples

#### ๐Ÿ“ˆ **Financial Trading**
```rust
rule "CircuitBreaker" {
    when
        priceMax > 200.0 || priceMin < 50.0
    then
        MarketService.halt("extreme_movement");
}
```

#### ๐ŸŒก๏ธ **IoT Monitoring**
```rust
rule "OverheatingAlert" {
    when
        temperatureAverage > 80.0 && WindowEventCount > 20
    then
        CoolingSystem.activate();
        AlertService.notify("overheating_detected");
}
```

#### ๐Ÿ›ก๏ธ **Fraud Detection**
```rust
rule "SuspiciousActivity" {
    when
        transactionCountSum > 10 && amountAverage > 1000.0
    then
        SecurityService.flag("potential_fraud");
        AccountService.freeze();
}
```

#### ๐Ÿ“Š **E-commerce Analytics**
```rust
rule "FlashSaleOpportunity" {
    when
        viewCountSum > 1000 && conversionRateAverage < 0.02
    then
        PromotionService.trigger("flash_sale");
        InventoryService.prepare();
}
```

See [docs/STREAMING.md](docs/STREAMING.md) for complete documentation and examples.

## ๐Ÿ“Š Advanced Analytics & Performance Monitoring (v0.3.0+)

Get deep insights into your rule engine performance with built-in analytics and monitoring:

### ๐Ÿ”ง Quick Analytics Setup

```rust
use rust_rule_engine::{RustRuleEngine, AnalyticsConfig, RuleAnalytics};

// Configure analytics for production use
let analytics_config = AnalyticsConfig {
    track_execution_time: true,
    track_memory_usage: true,
    track_success_rate: true,
    sampling_rate: 0.8,  // 80% sampling for high-volume production
    retention_period: Duration::from_secs(30 * 24 * 60 * 60), // 30 days
    max_recent_samples: 100,
};

// Enable analytics
let analytics = RuleAnalytics::new(analytics_config);
engine.enable_analytics(analytics);

// Execute rules - analytics automatically collected
let result = engine.execute(&facts)?;

// Access comprehensive insights
if let Some(analytics) = engine.analytics() {
    let stats = analytics.overall_stats();
    println!("Total executions: {}", stats.total_evaluations);
    println!("Average execution time: {:.2}ms", 
        stats.avg_execution_time.as_secs_f64() * 1000.0);
    println!("Success rate: {:.1}%", stats.success_rate);
    
    // Get optimization recommendations
    let recommendations = analytics.generate_recommendations();
    for rec in recommendations {
        println!("๐Ÿ’ก {}", rec);
    }
}
```

## ๐Ÿ”„ No-Loop Protection

Prevent rules from infinitely triggering themselves - essential for rules that modify their own conditions:

### ๐ŸŽฏ The Problem

```grl
// โŒ Without no-loop: INFINITE LOOP!
rule "ScoreBooster" {
    when
        Player.score < 100
    then
        set(Player.score, Player.score + 10);  // This changes the condition!
}
// Rule keeps firing: 50 โ†’ 60 โ†’ 70 โ†’ 80 โ†’ 90 โ†’ 100 โ†’ STOP (only due to max_cycles)
```

### โœ… The Solution

```grl
// โœ… With no-loop: SAFE!
rule "ScoreBooster" no-loop {
    when
        Player.score < 100
    then
        set(Player.score, Player.score + 10);  // Rule fires once per cycle
}
// Rule fires once: 50 โ†’ 60, then waits for next cycle
```

### ๐Ÿงช Usage Examples

```rust
use rust_rule_engine::*;

// Method 1: Via GRL parsing
let grl = r#"
    rule "SafeUpdater" no-loop salience 10 {
        when Player.level < 5
        then set(Player.level, Player.level + 1);
    }
"#;
let rules = GRLParser::parse_rules(grl)?;

// Method 2: Via API
let rule = Rule::new("SafeUpdater".to_string(), conditions, actions)
    .with_no_loop(true)
    .with_salience(10);

// Method 3: Multiple positions supported
// rule "Name" no-loop salience 10 { ... }  โœ…
// rule "Name" salience 10 no-loop { ... }  โœ…
```

### ๐Ÿ”ฌ How It Works

1. **Per-Cycle Tracking**: Engine tracks which rules fired in current cycle
2. **Skip Logic**: Rules with `no_loop=true` skip if already fired this cycle  
3. **Fresh Start**: Tracking resets at beginning of each new cycle
4. **Drools Compatible**: Matches Drools behavior exactly

### ๐ŸŽฎ Real Example

```rust
fn demo_no_loop() -> Result<()> {
    let grl = r#"
        rule "LevelUp" no-loop {
            when Player.xp >= 100
            then 
                set(Player.level, Player.level + 1);
                set(Player.xp, 0);
                log("Player leveled up!");
        }
    "#;
    
    let rules = GRLParser::parse_rules(grl)?;
    // Rule fires once: level 1โ†’2, xp 150โ†’0
    // Without no-loop: would fire again since xp >= 100 still true initially
}
```

### ๐Ÿ“ˆ Analytics Features

- **โฑ๏ธ Execution Timing**: Microsecond-precision rule performance tracking
- **๐Ÿ“Š Success Rate Monitoring**: Track fired vs evaluated rule ratios  
- **๐Ÿ’พ Memory Usage Estimation**: Optional memory footprint analysis
- **๐ŸŽฏ Performance Rankings**: Identify fastest and slowest rules
- **๐Ÿ”ฎ Smart Recommendations**: AI-powered optimization suggestions
- **๐Ÿ“… Timeline Analysis**: Recent execution history and trends
- **โš™๏ธ Production Sampling**: Configurable sampling rates for high-volume environments
- **๐Ÿ—‚๏ธ Automatic Cleanup**: Configurable data retention policies

### ๐ŸŽ›๏ธ Production Configuration

```rust
// Production configuration with optimized settings
let production_config = AnalyticsConfig::production(); // Built-in production preset

// Or custom configuration
let custom_config = AnalyticsConfig {
    track_execution_time: true,
    track_memory_usage: false,    // Disable for performance
    track_success_rate: true,
    sampling_rate: 0.1,          // 10% sampling for high traffic
    retention_period: Duration::from_secs(7 * 24 * 60 * 60), // 1 week
    max_recent_samples: 50,      // Limit memory usage
};
```

### ๐Ÿ“Š Rich Analytics Dashboard

```rust
// Get comprehensive performance report
let analytics = engine.analytics().unwrap();

// Overall statistics
let stats = analytics.overall_stats();
println!("๐Ÿ“Š Performance Summary:");
println!("  Rules: {}", stats.total_rules);
println!("  Executions: {}", stats.total_evaluations);
println!("  Success Rate: {:.1}%", stats.success_rate);
println!("  Avg Time: {:.2}ms", stats.avg_execution_time.as_secs_f64() * 1000.0);

// Top performing rules
for rule_metrics in analytics.slowest_rules(3) {
    println!("โš ๏ธ Slow Rule: {} ({:.2}ms avg)", 
        rule_metrics.rule_name, 
        rule_metrics.avg_execution_time().as_secs_f64() * 1000.0
    );
}

// Recent activity timeline
for event in analytics.get_recent_events(5) {
    let status = if event.success { "โœ…" } else { "โŒ" };
    println!("{} {} - {:.2}ms", status, event.rule_name, 
        event.duration.as_secs_f64() * 1000.0);
}
```

### ๐Ÿ” Performance Insights

The analytics system provides actionable insights:

- **Slow Rule Detection**: "Consider optimizing 'ComplexValidation' - average execution time is 15.3ms"
- **Low Success Rate Alerts**: "Rule 'RareCondition' has low success rate (12.5%) - review conditions"  
- **Dead Rule Detection**: "Rule 'ObsoleteCheck' never fires despite 156 evaluations - review logic"
- **Memory Usage Warnings**: "Rule 'DataProcessor' uses significant memory - consider optimization"

### ๐Ÿ“š Analytics Examples

Check out the comprehensive analytics demo:

```bash
# Run the analytics demonstration
cargo run --example analytics_demo

# Output includes:
# - Configuration summary
# - Performance rankings  
# - Success rate analysis
# - Optimization recommendations
# - Recent execution timeline
```

**Key Benefits:**
- ๐Ÿš€ **Performance Optimization**: Identify bottlenecks automatically
- ๐Ÿ“ˆ **Production Monitoring**: Real-time insights in live environments  
- ๐Ÿ”ง **Development Debugging**: Detailed execution analysis during development
- ๐Ÿ“Š **Trend Analysis**: Historical performance tracking and regression detection
- โšก **Zero-Overhead Option**: Configurable sampling with minimal performance impact

## ๐Ÿ“‹ Changelog

### v0.3.0 (October 2025) - AST-Based Dependency Analysis & Advanced Analytics
- **๐Ÿ” Revolutionary Dependency Analysis**: Complete rewrite from hard-coded pattern matching to proper AST parsing
- **๐ŸŽฏ Smart Field Detection**: Recursive condition tree traversal for accurate field dependency extraction
- **๐Ÿง  Function Side-Effect Analysis**: Intelligent inference of field modifications from function calls
- **โšก Zero False Positives**: Elimination of brittle string-based detection methods
- **๐Ÿš€ Parallel Processing Foundation**: AST-based analysis enables safe concurrent rule execution
- **๐Ÿ“Š Advanced Conflict Detection**: Real data flow analysis for read-write conflict identification
- **๐Ÿ—๏ธ Production-Ready Safety**: Robust dependency analysis for enterprise-grade rule management
- **๐Ÿ“ˆ Advanced Analytics System**: Comprehensive performance monitoring and optimization insights
  - Real-time execution metrics with microsecond precision
  - Success rate tracking and trend analysis
  - Memory usage estimation and optimization recommendations
  - Production-ready sampling and data retention policies
  - Automated performance optimization suggestions
  - Rich analytics dashboard with timeline analysis
- **๐ŸŒ REST API with Monitoring**: Production-ready web API with full analytics integration
  - Comprehensive REST endpoints for rule execution
  - Real-time analytics dashboard with performance insights
  - Health monitoring and system status endpoints
  - CORS support and proper error handling
  - Sample requests and complete API documentation

### v0.2.x - Core Features & Streaming
- **๐ŸŒŠ Stream Processing**: Real-time event processing with time windows
- **๐Ÿ“Š Rule Templates**: Parameterized rule generation system
- **๐Ÿ”ง Method Calls**: Enhanced object method call support
- **๐Ÿ“„ File-Based Rules**: External `.grl` file support
- **โšก Performance Optimizations**: Microsecond-level rule execution

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ๐Ÿ“ž Support

- ๐Ÿ“š **Documentation**: [docs.rs/rust-rule-engine]https://docs.rs/rust-rule-engine
- ๐Ÿ› **Issues**: [GitHub Issues]https://github.com/KSD-CO/rust-rule-engine/issues
- ๐Ÿ’ฌ **Discussions**: [GitHub Discussions]https://github.com/KSD-CO/rust-rule-engine/discussions

---

**Built with โค๏ธ in Rust** ๐Ÿฆ€