rust-rule-engine 0.14.0

A high-performance rule engine for Rust with RETE-UL algorithm (2-24x faster), CLIPS-inspired features (Template System, Defglobal, Deffacts, Test CE, Conflict Resolution), GRL support, and ~98% Drools compatibility
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
# Rust Rule Engine v0.14.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/actions/workflows/rust.yml/badge.svg)](https://github.com/KSD-CO/rust-rule-engine/actions)

A high-performance rule engine for Rust with **RETE-UL algorithm**, **CLIPS-inspired features**, **Plugin System**, and **GRL (Grule Rule Language) support**. Designed for production use with good Drools compatibility.

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

---

## โœจ What's New in v0.14.0

๐ŸŽ‰ **MAJOR UPDATE: Fully Automatic Accumulate Functions!**

This release completes the accumulate feature with 100% automatic evaluation across all engine paths!

๐Ÿงฎ **AUTO Accumulate Functions** - Fully automated aggregation in rule conditions!

- **๐Ÿš€ FULLY AUTOMATIC** - No manual calculation needed!
- **๐Ÿ“Š 5 Built-in Functions** - sum, count, average, min, max
- **๐ŸŽฏ GRL Parser Support** - Parse `accumulate()` syntax from .grl files
- **โšก Auto Collection** - Engine automatically collects matching facts
- **๐Ÿ”„ Auto Calculation** - Engine automatically runs aggregate functions
- **๐Ÿ’‰ Auto Injection** - Engine automatically injects results into facts
- **๐ŸŽฏ RETE Integration** - Efficient aggregation with pattern matching
- **๐Ÿ“ˆ Real-time Analytics** - Calculate metrics across multiple facts
- **๐Ÿ’ผ Business Rules** - Revenue totals, order counts, averages
- **โœ… Production Ready** - Battle-tested with e-commerce analytics

**Example - Just Write This in GRL:**
```grl
rule "HighRevenue" {
    when
        accumulate(Order($amt: amount, status == "completed"), sum($amt))
    then
        Alert.send("High revenue!");
}
```

**Engine does ALL of this automatically:**
1. โœ… Collects all Order facts
2. โœ… Filters by `status == "completed"`
3. โœ… Extracts `amount` field
4. โœ… Runs `sum()` function
5. โœ… Injects result into facts
6. โœ… Evaluates rule condition

[**๐Ÿš€ AUTO Accumulate (RECOMMENDED) โ†’**]examples/test_auto_accumulate.rs | [**โšก Native & RETE-UL Demo โ†’**]examples/test_accumulate_rete_ul.rs | [**๐Ÿ“š Manual API Demo โ†’**]examples/accumulate_demo.rs | [**๐Ÿ“– Parser Demo โ†’**]examples/test_accumulate_parser.rs

โšก **Variable-to-Variable Comparison** - Dynamic threshold comparisons!

- **๐Ÿ”„ Compare Variables** - Direct comparison between fact fields (e.g., `Facts.L1 > Facts.L1Min`)
- **๐Ÿ“Š Dynamic Thresholds** - No hardcoded values, change thresholds on-the-fly
- **๐ŸŽฏ RETE-UL Support** - Full integration with incremental engine
- **๐Ÿ“ GRL Syntax** - Natural syntax: `when (Facts.value > Facts.threshold)`
- **โšก Efficient Evaluation** - Leverages RETE's pattern matching
- **๐Ÿ”ง Flexible Rules** - Same rule adapts to different threshold configurations
- **โœ… Production Ready** - Battle-tested with complex eligibility rules

[**See Variable Comparison Demo โ†’**]examples/famicanxi_rete_test.rs | [**Test Variable Comparison โ†’**]examples/test_variable_comparison.rs

### Previous Updates

### v0.13.4
๐Ÿงฎ **Accumulate Functions (Initial Release)** - Aggregation in rule conditions!

- **๐Ÿ“Š 5 Built-in Functions** - sum, count, average, min, max
- **๐ŸŽฏ GRL Parser Support** - Parse `accumulate()` syntax from .grl files
- **๐Ÿ“ˆ Real-time Analytics** - Calculate metrics across multiple facts
- **โš ๏ธ Note:** Required manual injection in v0.13.4 - now fully automatic in v0.14.0!

โšก **Variable-to-Variable Comparison** - Dynamic threshold comparisons!

- **๐Ÿ”„ Compare Variables** - Direct comparison between fact fields
- **๐Ÿ“Š Dynamic Thresholds** - Change thresholds on-the-fly
- **โœ… Production Ready** - Battle-tested

### v0.13.0 (Earlier)
โšก **Conflict Resolution Strategies** - CLIPS/Drools-inspired rule ordering!

- **๐ŸŽฏ 8 Strategies** - Salience, LEX, MEA, Depth, Breadth, Simplicity, Complexity, Random
- **๐Ÿ“Š Priority-Based** - Control rule execution order with salience
- **๐Ÿ• Recency-Based** - Most recent facts fire first (LEX)
- **๐Ÿ” Specificity** - More specific rules fire first (Complexity, MEA)
- **โš™๏ธ Performance** - Simple rules before complex (Simplicity)
- **๐Ÿ”„ Dynamic Switching** - Change strategies at runtime
- **โœ… CLIPS Compatible** - Industry-standard conflict resolution
- **๐Ÿ“ˆ ~98% Drools Parity** - Enhanced compatibility

[**See Conflict Resolution Demo โ†’**]examples/conflict_resolution_demo.rs | [**CLIPS Features Guide โ†’**]CLIPS_INSPIRED_FEATURES.md

### Previous Updates

### v0.12.0
๐Ÿงช **Test CE (Conditional Element)** - CLIPS-inspired arbitrary boolean expressions!

- **๐Ÿ”ฌ Test CE Syntax** - Call arbitrary functions in rule conditions without operators
- **๐Ÿ“ GRL Support** - Parse `test(function(args))` directly from .grl files
- **๐ŸŽฏ Native Engine** - Fully implemented with function registry
- **โšก Truthy Evaluation** - Automatic boolean conversion for all value types
- **๐Ÿ”— Negation Support** - Use `!test()` for negated conditions
- **๐Ÿค Combined Conditions** - Mix test() with regular conditions using AND/OR
- **๐Ÿ“š Multiple Arguments** - Support functions with any number of arguments

[**See Test CE Demo โ†’**](examples/test_ce_comprehensive.rs)

### v0.11.0
๐ŸŽฏ **Deffacts System** - Initial fact definitions (CLIPS feature)!

- **๐Ÿ“ฆ Deffacts** - Pre-defined fact sets for initial state
- **๐Ÿ”„ Reset Support** - Restore original facts with `reset_with_deffacts()`
- **๐Ÿ“‹ Multiple Sets** - Organize initial facts by category
- **โœ… Template Integration** - Type-safe initial facts
- **๐Ÿ—๏ธ Builder API** - Fluent interface for defining deffacts

[**See Deffacts Demo โ†’**](examples/rete_deffacts_demo.rs)

### v0.10.2
๐Ÿ“ง **Metadata Update** - Corrected author email contact information

### v0.10.1

๐Ÿš€ **RETE Performance Optimization + Comprehensive Benchmarks**!

- **โšก RETE Fixed** - Eliminated infinite loop issue, now blazing fast
- **๐Ÿ“Š Benchmarked** - Comprehensive comparison: Traditional vs RETE
- **๐Ÿ”ฅ 2-24x Faster** - RETE shows 2x speedup at 10 rules, 24x at 50+ rules
- **โœ… Production Ready** - Max iterations guard, optimized agenda management
- **๐Ÿ“ˆ Scalability Proven** - ~5ยตs per rule, scales linearly

[**See Benchmark Results โ†’**]BENCHMARK_RESULTS.md

### v0.10.0
- **๐Ÿ”ง Function Calls in WHEN** - Call AI/custom functions directly in rule conditions
- **๐Ÿ“‹ Template System** - Type-safe schema definitions for structured facts
- **๐ŸŒ Defglobal** - Global variables with thread-safe access
- **๐Ÿ“ˆ Drools Compatibility** - ~97% Drools parity

[**See Release Notes โ†’**]RELEASE_v0.10.0.md | [**CLIPS Features Guide โ†’**]CLIPS_INSPIRED_FEATURES.md

---

## ๐Ÿš€ Key Features

### Native Engine
- **GRL Support** - Full Grule-compatible syntax
- **Function Calls in WHEN** - Call functions directly in conditions *(NEW in v0.10.0)*
- **Plugin System** - 44+ actions, 33+ functions
- **Knowledge Base** - Centralized rule management
- **Type Safety** - Rust's compile-time guarantees
- **Production Ready** - REST API, monitoring, health checks

### RETE-UL Engine (Recommended for 50+ rules)
- **๐Ÿš€ High Performance** - Efficient RETE algorithm with incremental updates
- **๐Ÿ”ฅ RETE Algorithm** - Advanced pattern matching with good Drools compatibility
- **๐Ÿงฎ Accumulate Functions** - sum, count, average, min, max aggregations *(v0.13.4)*
- **๐Ÿ”„ Variable Comparison** - Compare fact fields dynamically (L1 > L1Min) *(v0.13.4)*
- **๐Ÿ“‹ Template System** - Type-safe structured facts *(v0.10.0)*
- **๐ŸŒ Defglobal** - Global variables across firings *(v0.10.0)*
- **๐Ÿ“ฆ Deffacts** - Initial fact definitions *(v0.11.0)*
- **๐Ÿงช Test CE** - Arbitrary boolean expressions in rules *(v0.12.0)*
- **โšก Conflict Resolution** - 8 CLIPS strategies (Salience, LEX, MEA, etc.) *(v0.13.0)*
- **๐ŸŽฏ Incremental Updates** - Only re-evaluate affected rules
- **๐Ÿง  Working Memory** - FactHandles with insert/update/retract
- **๐Ÿ”— Variable Binding** - Cross-pattern $var syntax
- **๐Ÿ’พ Memoization** - Efficient caching for repeated evaluations

**Choose Your Engine:**
- **< 10 rules** โ†’ Native Engine (simpler API, plugin support)
- **10-50 rules** โ†’ Either (RETE ~2x faster)
- **50+ rules** โ†’ RETE-UL Engine (2-24x faster, highly recommended)
- **Both needs** โ†’ Hybrid approach

๐Ÿ“Š **Performance at 50 rules**: RETE shows good performance improvements over traditional engine!

๐Ÿ“– [**Engine Comparison Guide โ†’**](ENGINE_COMPARISON.md) | [**Quick Start Guide โ†’**](QUICK_START_ENGINES.md)

---

## ๐Ÿ“ฆ Installation

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

### Optional Features
```toml
# Enable streaming support
rust-rule-engine = { version = "0.13.4", features = ["streaming"] }
```

---

## ๐ŸŽฏ Quick Start

### Option 1: Native Engine (Simple & Plugin-rich)

```rust
use rust_rule_engine::{RustRuleEngine, Facts, Value};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create engine with plugins
    let mut engine = RustRuleEngine::new();
    engine.load_default_plugins()?;

    // Load rules from GRL file
    engine.load_rules_from_file("rules/discount.grl")?;

    // Add facts
    let mut facts = Facts::new();
    facts.set("customer.tier", Value::String("gold".to_string()));
    facts.set("order.amount", Value::Float(1500.0));

    // Execute rules
    engine.execute(&mut facts)?;

    // Get result
    println!("Discount: {}", facts.get("order.discount"));

    Ok(())
}
```

**GRL Rule Example** (`rules/discount.grl`):
```grl
rule "GoldCustomerDiscount" salience 10 {
    when
        customer.tier == "gold" && order.amount > 1000
    then
        order.discount = order.amount * 0.15;
        Log("Applied 15% gold customer discount");
}
```

### Option 2: RETE-UL Engine (High Performance)

```rust
use rust_rule_engine::rete::{
    IncrementalEngine, GrlReteLoader, TypedFacts, FactValue,
    TemplateBuilder, FieldType
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut engine = IncrementalEngine::new();

    // Optional: Define template for type safety
    let order_template = TemplateBuilder::new("Order")
        .required_string("order_id")
        .float_field("amount")
        .float_field("discount")
        .build();
    engine.templates_mut().register(order_template);

    // Load rules from GRL
    GrlReteLoader::load_from_file("rules/discount.grl", &mut engine)?;

    // Insert facts with validation
    let mut order = TypedFacts::new();
    order.set("order_id", FactValue::String("ORD-001".to_string()));
    order.set("amount", FactValue::Float(1500.0));

    let handle = engine.insert_with_template("Order", order)?;

    // Fire rules
    engine.reset();
    let fired = engine.fire_all();
    println!("Fired {} rules", fired.len());

    // Query results
    if let Some(order) = engine.working_memory().get(&handle) {
        println!("Discount: {:?}", order.data.get("discount"));
    }

    Ok(())
}
```

---

## ๐Ÿงฎ NEW: Accumulate Functions (v0.13.4)

**Powerful aggregation capabilities for calculating metrics across multiple facts!**

This feature enables you to perform aggregations (sum, count, average, min, max) directly in your rule conditions, making it easy to build analytics and reporting rules.

### โœจ Built-in Accumulate Functions

```rust
// 5 Ready-to-Use Functions
sum()      // Add up numeric values
count()    // Count matching facts
average()  // Calculate mean
min()      // Find minimum value
max()      // Find maximum value
```

### ๐Ÿ“– Real-World Example: Sales Analytics

**Business Scenario:**
E-commerce platform needs to automatically detect high-value sales periods and trigger inventory allocation.

**Rust Implementation:**
```rust
use rust_rule_engine::rete::accumulate::*;
use rust_rule_engine::rete::FactValue;

// Sample order amounts
let orders = vec![
    FactValue::Float(1500.0),
    FactValue::Float(2500.0),
    FactValue::Float(3200.0),
    FactValue::Float(1800.0),
];

// Calculate total revenue
let sum_fn = SumFunction;
let mut state = sum_fn.init();
for amount in &orders {
    state.accumulate(amount);
}

let total = state.get_result(); // Float(9000.0)

// Business rule: If total > $8000, trigger alert
if let FactValue::Float(revenue) = total {
    if revenue > 8000.0 {
        println!("โœ… High-value sales period detected!");
        println!("   Recommendation: Allocate extra inventory");
    }
}
```

### ๐ŸŽฏ Future GRL Syntax (Coming Soon)

When integrated with GRL parser, you'll be able to write:

```grl
rule "HighSalesAlert" {
    when
        $total: accumulate(
            Order($amount: amount, status == "completed"),
            sum($amount)
        )
        $total > 8000
    then
        Alert.send("High-value sales period!");
        Inventory.allocate_extra();
}

rule "AverageOrderValue" {
    when
        $avg: accumulate(
            Order($amount: amount),
            average($amount)
        )
        $avg > 1000
    then
        Customer.offerPremiumMembership();
}
```

### ๐Ÿ“Š All Accumulate Functions

**1. SUM - Total Revenue**
```rust
let mut sum_state = SumFunction.init();
for order in orders {
    sum_state.accumulate(&order.amount);
}
// Result: Float(total_revenue)
```

**2. COUNT - Number of Orders**
```rust
let mut count_state = CountFunction.init();
for order in orders {
    count_state.accumulate(&order.amount);
}
// Result: Integer(order_count)
```

**3. AVERAGE - Mean Order Value**
```rust
let mut avg_state = AverageFunction.init();
for order in orders {
    avg_state.accumulate(&order.amount);
}
// Result: Float(average_value)
```

**4. MIN - Smallest Order**
```rust
let mut min_state = MinFunction.init();
for order in orders {
    min_state.accumulate(&order.amount);
}
// Result: Float(minimum_value)
```

**5. MAX - Largest Order**
```rust
let mut max_state = MaxFunction.init();
for order in orders {
    max_state.accumulate(&order.amount);
}
// Result: Float(maximum_value)
```

### ๐Ÿ”ง Custom Accumulate Functions

Create your own accumulate functions by implementing the trait:

```rust
use rust_rule_engine::rete::accumulate::*;

// Custom function: Collect all values
pub struct CollectFunction;

impl AccumulateFunction for CollectFunction {
    fn init(&self) -> Box<dyn AccumulateState> {
        Box::new(CollectState { values: Vec::new() })
    }

    fn name(&self) -> &str {
        "collect"
    }

    fn clone_box(&self) -> Box<dyn AccumulateFunction> {
        Box::new(self.clone())
    }
}
```

### ๐Ÿงช Complete Examples

See working examples:
- [accumulate_demo.rs]examples/accumulate_demo.rs - Basic accumulate functions
- [accumulate_rete_integration.rs]examples/accumulate_rete_integration.rs - E-commerce analytics

---

## ๐Ÿ”„ Variable-to-Variable Comparison (v0.13.4)

**The RETE-UL engine now supports comparing variables directly with each other!**

This powerful feature enables dynamic threshold comparisons without hardcoding values in rules, making your rule logic more flexible and reusable.

### โœจ Why Variable Comparison?

**Traditional Approach (Hardcoded):**
```grl
rule "CheckAge" {
    when customer.age > 18  // Hardcoded threshold
    then customer.eligible = true;
}
```

**New Approach (Dynamic):**
```grl
rule "CheckAge" {
    when customer.age > settings.minAge  // Dynamic threshold
    then customer.eligible = true;
}
```

### ๐Ÿ“– Real-World Example: Product Eligibility

**Business Scenario:**
FamiCanxi product requires customers to meet dynamic thresholds for L1 and CM2 scores that can vary based on market conditions.

**GRL Rule** ([famicanxi_rules.grl](examples/famicanxi_rules.grl)):
```grl
rule "FamiCanxi Product Eligibility Rule" salience 50 {
  when
    (Facts.L1 > Facts.L1Min) &&
    (Facts.CM2 > Facts.Cm2Min) &&
    (Facts.productCode == 1)
  then
    Facts.levelApprove = 1;
}
```

**RETE-UL Implementation:**
```rust
use rust_rule_engine::rete::{GrlReteLoader, IncrementalEngine, TypedFacts};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut engine = IncrementalEngine::new();

    // Load rule with variable comparisons
    GrlReteLoader::load_from_file("examples/famicanxi_rules.grl", &mut engine)?;

    // Insert facts with dynamic thresholds
    let mut facts = TypedFacts::new();
    facts.set("L1", 100i64);        // Customer score
    facts.set("L1Min", 50i64);      // Dynamic threshold (can change per request)
    facts.set("CM2", 80i64);        // Customer CM2 score
    facts.set("Cm2Min", 60i64);     // Dynamic threshold
    facts.set("productCode", 1i64);

    engine.insert("Facts".to_string(), facts);
    engine.reset();

    let fired = engine.fire_all();
    println!("Rules fired: {}", fired.len()); // Output: Rules fired: 1

    Ok(())
}
```

### ๐ŸŽฏ Key Benefits

1. **Dynamic Business Rules** - Change thresholds without modifying rule code
2. **A/B Testing** - Test different threshold configurations easily
3. **Multi-Tenant Support** - Different thresholds per customer/region
4. **Configuration-Driven** - Rules adapt to configuration changes
5. **Reduced Code Duplication** - One rule handles multiple scenarios

### ๐Ÿ“Š Supported Comparisons

```grl
// Numeric comparisons
Facts.value > Facts.threshold
Facts.value >= Facts.minimum
Facts.value < Facts.maximum
Facts.value <= Facts.limit
Facts.value == Facts.target
Facts.value != Facts.excluded

// Mixed: variable with constant
Facts.value > Facts.threshold && Facts.status == "active"

// Multiple variable comparisons
(Facts.minValue < Facts.value) && (Facts.value < Facts.maxValue)
```

### ๐Ÿงช Test Examples

See complete working examples:
- [famicanxi_rete_test.rs]examples/famicanxi_rete_test.rs - RETE-UL engine with variable comparison
- [famicanxi_grl_test.rs]examples/famicanxi_grl_test.rs - Standard engine with GRL
- [test_variable_comparison.rs]examples/test_variable_comparison.rs - Comprehensive test suite

---

## ๐Ÿ”ง Function Calls in WHEN Clause

**v0.10.0 introduces the ability to call functions directly in rule conditions!**

### โœจ Before (Rule Chaining)
```grl
rule "Step1: Call AI" {
    when Customer.needsCheck == true
    then set(Customer.sentiment, aiSentiment(Customer.feedback));
}

rule "Step2: Check Result" {
    when Customer.sentiment == "negative"
    then Alert("Negative feedback detected!");
}
```

### โœจ After (Direct Function Calls)
```grl
rule "Check Sentiment" {
    when aiSentiment(Customer.feedback) == "negative"
    then Alert("Negative feedback detected!");
}
```

### ๐Ÿ“– Use Cases

**AI/ML Integration:**
```grl
rule "Fraud Detection" {
    when aiFraud(Transaction.amount, Transaction.userId) == true
    then set(Transaction.status, "blocked");
}
```

**Business Logic:**
```grl
rule "Credit Check" {
    when creditScore(Customer.id) > 750
    then set(Customer.tier, "premium");
}
```

**Data Validation:**
```grl
rule "Email Validation" {
    when validateEmail(User.email) == false
    then set(User.error, "Invalid email format");
}
```

**See [ai_functions_in_when.rs](examples/ai_functions_in_when.rs) for complete examples!**

---

## ๐Ÿ“š Documentation

### ๐Ÿ“– Getting Started
- [**Quick Start Guide**]QUICK_START_ENGINES.md - Choose and use your engine
- [**Engine Comparison**]ENGINE_COMPARISON.md - Native vs RETE-UL decision guide
- [**Examples**]examples/ - 30+ working examples

### ๐Ÿ”ง Core Features
- [**Features Guide**]docs/FEATURES.md - All engine features explained
- [**Plugin System**]docs/PLUGINS.md - Built-in plugins & custom creation
- [**Advanced Usage**]docs/ADVANCED_USAGE.md - Complex patterns & workflows
- [**AI Integration**]docs/REAL_AI_INTEGRATION.md - ML models & LLM integration

### ๐Ÿš€ RETE-UL Engine
- [**RETE Guide**]docs/RETE_GUIDE.md - Complete RETE-UL documentation
- [**CLIPS Features**]CLIPS_INSPIRED_FEATURES.md - Template System & Defglobal
- [**CLIPS Analysis**]CLIPS_FEATURES_ANALYSIS.md - Feature comparison & roadmap

### ๐ŸŒ Distributed & Production
- [**Streaming Engine**]docs/STREAMING.md - Real-time stream processing
- [**Distributed Setup**]docs/distributed_explained.md - Getting started with distributed mode
- [**Distributed Architecture**]docs/distributed_architecture.md - Cluster setup & scaling
- [**Distributed Features**]docs/distributed_features_guide.md - Complete distributed guide
- [**Performance Guide**]docs/PERFORMANCE.md - Benchmarks & optimization

### ๐Ÿ“‹ Reference
- [**API Reference**]docs/API_REFERENCE.md - Complete API documentation
- [**GRL Syntax**]docs/GRL_SYNTAX.md - Rule language reference
- [**Roadmap**]docs/ROADMAP.md - Future plans & upcoming features
- [**Release Notes**]RELEASE_v0.10.0.md - What's new in v0.10.0
- [**Changelog**]CHANGELOG_v0.10.0.md - Complete changelog

---

## ๐Ÿ–ฅ๏ธ VS Code Extension

Install [GRL Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=tonthatvu.grl-syntax-highlighting) for `.grl` files:

**Features:**
- Syntax highlighting for GRL
- Snippets for rules, actions, functions
- Auto-detection of `.grl` files

**Install:** Search `grl-syntax-highlighting` in VS Code Extensions

---

## ๐ŸŽฏ Use Cases

### 1. Business Rules Engine
```rust
// Pricing, discounts, loyalty programs
rule "VIPDiscount" {
    when customer.points > 1000
    then order.discount = 0.20;
}
```

### 2. Dynamic Eligibility & Thresholds (NEW!)
```grl
// Product eligibility with dynamic thresholds
rule "ProductEligibility" {
    when (customer.score > settings.minScore) &&
         (customer.income > settings.minIncome) &&
         (customer.age >= settings.minAge)
    then customer.eligible = true;
}

// Credit limit based on dynamic risk assessment
rule "CreditLimit" {
    when (customer.creditScore > risk.threshold) &&
         (customer.debtRatio < risk.maxDebtRatio)
    then customer.creditLimit = customer.income * risk.multiplier;
}
```

### 3. Fraud Detection
```rust
// Real-time fraud scoring
rule "HighRiskTransaction" {
    when transaction.amount > 10000 &&
         transaction.location != customer.usual_location
    then fraud.score = 0.85;
}
```

### 4. Workflow Automation
```rust
// Multi-step approval workflows
rule "ManagerApproval" agenda-group "approvals" {
    when request.amount > 5000
    then request.requires_manager = true;
}
```

### 5. Real-Time Systems
```rust
// IoT, monitoring, alerts
rule "TemperatureAlert" {
    when sensor.temp > 80
    then Alert.send("High temperature!");
}
```

**More examples:** [examples/](examples/) directory

---

## โšก Performance

### RETE-UL Engine Benchmarks
- **Pattern Matching**: ~4ยตs per fact insertion (1000 facts)
- **Incremental Updates**: 2x speedup (only affected rules)
- **Memoization**: 99.99% cache hit rate
- **Template Validation**: 1-2ยตs per fact
- **Global Variables**: 120ns read, 180ns write

### Native Engine Benchmarks
- **Rule Execution**: ~10ยตs per rule (simple conditions)
- **Plugin Actions**: ~2-5ยตs per action call
- **Facts Access**: O(1) HashMap lookups

**Comparison:** [Performance Guide](docs/PERFORMANCE.md)

---

## Automated GRL Test Harness

This repository includes a lightweight, data-driven test harness used to exercise the GRL examples in `examples/rules` and verify they still parse and run against the engine.

Purpose:

- Provide end-to-end coverage for `.grl` example files without requiring full production action implementations.
- Detect regressions in the parser, engine, and example rules.

Where to find it:

- `tests/grl_harness_data.rs` โ€” the primary data-driven harness. It reads `tests/grl_cases.yml`, constructs `Facts`, loads the `.grl` file(s), builds a `KnowledgeBase`, registers lightweight action handlers and functions, executes the engine, and performs simple assertions.
- `tests/grl_harness.rs` โ€” smaller smoke tests used by the harness and examples.
- `tests/grl_cases.yml` โ€” YAML-driven cases. Each case points at a `.grl` file and provides `initial_facts` and optional `expect` checks.

Why it uses minimal action handlers:

Many GRL samples call custom actions (e.g., `apply_discount`, `sendAlert`, `setEcoMode`, etc.). To exercise the rules end-to-end without requiring external systems, the harness registers small, no-op or fact-mutating action handlers. These handlers are only for testing and live in `tests/grl_harness_data.rs`.

How to run the harness (local development / CI):

```bash
# from repository root (zsh)
cargo test --tests -- --nocapture
```

What to look for:

- The harness prints a per-case log (e.g., "=== Running case: fraud_detection ===") and a small set of logs generated by the registered handlers and functions.
- Each case prints the number of rules fired. The harness currently performs lightweight assertions (e.g., rules fired, and simple fact field checks) โ€” see `tests/grl_harness_data.rs` for details.

How to add or update cases:

1. Add a new case to `tests/grl_cases.yml` with fields: `name`, `grl`, `initial_facts`, and optional `expect`.
2. If the `.grl` uses custom actions not yet covered, either:
    - Add a small test handler in `tests/grl_harness_data.rs` (follow the existing pattern), or
    - Add sufficient `initial_facts` so rules can be exercised without that action being mandatory.
3. Run the harness and verify the new case behaves as expected.

Notes & next improvements:

- The harness currently registers many minimal handlers to unblock rule execution; a future iteration should replace no-ops with tighter, case-specific assertions so the tests verify meaningful behavior instead of only successful execution.
- There are some compiler warnings in the codebase (missing docs, unused-variable warnings). These do not block tests but can be cleaned up to keep CI logs tidy.

Questions or contributions: If you'd like, I can (a) strengthen per-case assertions, (b) consolidate test handlers into helpers, or (c) add a GitHub Actions workflow to run the harness in CI.

---

## ๐Ÿค Contributing

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

### Development Setup
```bash
# Clone repository
git clone https://github.com/KSD-CO/rust-rule-engine.git
cd rust-rule-engine

# Run tests
cargo test

# Run examples
cargo run --example rete_template_globals_demo

# Build documentation
cargo doc --open
```

---

## ๐Ÿ“„ License

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

---

## ๐Ÿ™ Acknowledgments

**Inspired by:**
- [Drools]https://www.drools.org/ - JBoss Rule Engine
- [CLIPS]https://www.clipsrules.net/ - NASA C Language Integrated Production System
- [Grule]https://github.com/hyperjumptech/grule-rule-engine - Go Rule Engine

**Special Thanks:**
- Rust community for amazing tools and libraries
- Contributors who helped improve the engine
- Users providing valuable feedback

---

## ๐Ÿ“ž Support

- **Issues**: [GitHub Issues]https://github.com/KSD-CO/rust-rule-engine/issues
- **Discussions**: [GitHub Discussions]https://github.com/KSD-CO/rust-rule-engine/discussions
- **Email**: ttvuhm@gmail.com

---

## ๐Ÿ“ˆ Stats

![GitHub stars](https://img.shields.io/github/stars/KSD-CO/rust-rule-engine?style=social)
![GitHub forks](https://img.shields.io/github/forks/KSD-CO/rust-rule-engine?style=social)
![Crates.io downloads](https://img.shields.io/crates/d/rust-rule-engine)

---

<div align="center">

**Made with โค๏ธ by Ton That Vu**

[โญ Star us on GitHub]https://github.com/KSD-CO/rust-rule-engine | [๐Ÿ“ฆ Download from Crates.io]https://crates.io/crates/rust-rule-engine

</div>