### Run Any Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Basic command to run any example by replacing '' with the desired example's name. ```bash cargo run --example ``` -------------------------------- ### Run Basic Demo Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/PROJECT_CREATED.txt Execute the basic demo example for the IoT Farm Monitoring System. Navigate to the project directory and use cargo run with the --example flag. ```bash cd iot-farm-monitoring cargo run --example basic_demo ``` -------------------------------- ### Run Basic Demo - Rust Source: https://github.com/ksd-co/rust-rule-engine/blob/main/PROJECT_CREATED.txt Execute the standalone demo of the IoT Farm Monitoring System. This example does not require Kafka setup and demonstrates core functionalities. ```bash cd iot-farm-monitoring $ cargo run --example basic_demo ``` -------------------------------- ### Initialize Rule Engine Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/DOCUMENTATION_STRUCTURE.md Demonstrates the basic setup for initializing the rule engine. This is a complete, runnable example. ```rust use rust_rule_engine::{Engine, Facts, Value}; fn main() -> Result<(), Box> { let mut engine = Engine::new(); // ... complete code Ok(()) } ``` -------------------------------- ### Run Example with Features Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute an example that requires a specific feature to be enabled. For instance, 'streaming' for streaming-related examples. ```bash cargo run --example streaming_with_rules_demo --features streaming ``` -------------------------------- ### Install and Start Redis on macOS Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Instructions to install Redis using Homebrew and start the Redis service on macOS. ```bash # macOS brew install redis brew services start redis ``` -------------------------------- ### Run Basic Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute the basic 'grule_demo' and 'fraud_detection' examples using Cargo. ```bash cargo run --example grule_demo cargo run --example fraud_detection ``` -------------------------------- ### Run Real-World Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/CYCLIC_IMPORT_DETECTION.md Command to run the example demonstrating cyclic import detection scenarios. ```bash cargo run --example cyclic_import_detection ``` -------------------------------- ### Install and Start Redis on Linux (Ubuntu/Debian) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Commands to install the Redis server package and start the Redis service on Ubuntu/Debian-based Linux distributions. ```bash # Linux (Ubuntu/Debian) sudo apt-get install redis-server sudo systemctl start redis ``` -------------------------------- ### Basic Setup with Proof Graph Cache Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/PROOF_GRAPH_CACHING.md Demonstrates the basic setup of the RETE and backward engines, enabling the ProofGraph cache automatically for queries. ```rust use rust_rule_engine::backward::{BackwardEngine, DepthFirstSearch}; use rust_rule_engine::rete::IncrementalEngine; use std::sync::{Arc, Mutex}; // 1. Create RETE engine let mut rete_engine = IncrementalEngine::new(); // 2. Load rules into knowledge base let mut kb = KnowledgeBase::new(); b.add_rule(Rule::new(/* ... */)); // 3. Create backward engine let mut backward_engine = BackwardEngine::new(kb.clone()); // 4. Create search with ProofGraph (automatically enabled) let search = DepthFirstSearch::new_with_engine( kb, Arc::new(Mutex::new(rete_engine)), ); // 5. Query (cache is used automatically) let result = backward_engine.query_with_search( "eligible(?x)", &mut facts, Box::new(search), )?; ``` -------------------------------- ### Run Module System Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute examples that showcase the module system for organizing rules. These examples do not require special features. ```bash cargo run --example smart_home_modules cargo run --example phase3_demo ``` -------------------------------- ### Run Performance Comparison Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute performance comparison examples like 'quick_engine_comparison' and 'parallel_engine_demo' in release mode using Cargo. ```bash cargo run --example quick_engine_comparison --release cargo run --example parallel_engine_demo --release ``` -------------------------------- ### Run Examples with Release Mode Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/05-performance/README.md General command to run examples, recommended to use --release flag for performance tests. This ensures optimal performance measurements. ```bash cargo run --example quick_engine_comparison cargo run --release --example parallel_engine_demo # ... other examples (recommended to use --release for performance tests) ``` -------------------------------- ### Run Method Calls Demo Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/rules/01-basic/README.md Command to run the method_calls_demo example using Cargo. ```bash cargo run --example method_calls_demo ``` -------------------------------- ### Test with Minimal Rule Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/TROUBLESHOOTING.md When debugging, start with a minimal rule and fact setup to isolate issues. If the minimal case works, the problem is likely in the more complex parts of your setup or logic. ```rust // Minimal test let mut kb = KnowledgeBase::new("test"); b.add_rule(Rule::new( "Simple".to_string(), ConditionGroup::single(Condition::new( "A".to_string(), Operator::Equal, Value::Boolean(true), )), vec![ActionType::Set { field: "B".to_string(), value: Value::Boolean(true), }], ))?; let mut bc_engine = BackwardEngine::new(kb); let mut facts = Facts::new(); facts.set("A", Value::Boolean(true)); let result = bc_engine.query("B == true", &mut facts)?; assert!(result.is_provable()); // Should pass ``` -------------------------------- ### Run Streaming Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/03-advanced-features/README.md Execute streaming-related examples that integrate the Rule Engine with streaming operators. These examples require the 'streaming' feature to be enabled. ```bash cargo run --example streaming_with_rules_demo --features streaming cargo run --example streaming_state_management_demo --features streaming cargo run --example streaming_watermark_demo --features streaming ``` -------------------------------- ### Run Expression Demo Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/rules/01-basic/README.md Command to run the expression_demo example using Cargo. ```bash cargo run --example expression_demo ``` -------------------------------- ### Run Real-time Trading Stream Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/STREAMING.md Execute the real-time trading stream example with the streaming feature enabled. This command is used to run the example from the command line. ```bash cargo run --example realtime_trading_stream --features streaming ``` -------------------------------- ### Module Manager State Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/MODULE_PARSING_GUIDE.md Illustrates the internal state of the ModuleManager after registering example modules. ```text SENSORS ├── export: all └── imports: [] CONTROL ├── export: all └── imports: [ { from_module: "SENSORS", rules: "*", templates: "temperature" } ] ``` -------------------------------- ### Run Advanced Feature Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute advanced feature examples like 'accumulate_grl_demo' and 'streaming_with_rules_demo' using Cargo. The streaming example requires the 'streaming' feature. ```bash cargo run --example accumulate_grl_demo cargo run --example streaming_with_rules_demo --features streaming ``` -------------------------------- ### Run First Rust Rule Engine Example Source: https://github.com/ksd-co/rust-rule-engine/wiki/Home Execute the default project using Cargo to run the initial example. ```bash cargo run ``` -------------------------------- ### Phase 3 Demo Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/10-module-system/README.md An example command to run the demonstration for Phase 3 features, including transitive re-exports, module-level salience, and validation tools. ```bash cargo run --example phase3_demo ``` -------------------------------- ### Run Advanced RETE Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute the 'rete_p3_incremental' example for advanced RETE features using Cargo. ```bash cargo run --example rete_p3_incremental ``` -------------------------------- ### Run Grule Demo Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/rules/01-basic/README.md Command to run the grule_demo example using Cargo. ```bash cargo run --example grule_demo ``` -------------------------------- ### Run Backward Chaining Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute specific examples demonstrating backward chaining functionality. Ensure the 'backward-chaining' feature is enabled. ```bash cargo run --example simple_query_demo --features backward-chaining cargo run --example ecommerce_approval_demo --features backward-chaining cargo run --example medical_diagnosis_demo --features backward-chaining ``` -------------------------------- ### Example Module Definitions Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/MODULE_PARSING_GUIDE.md Example GRL code demonstrating module definitions with exports and imports. ```grl defmodule SENSORS { export: all } defmodule CONTROL { import: SENSORS (rules * (templates temperature)) export: all } ``` -------------------------------- ### Start Redis Server with Docker Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/REDIS_STATE_BACKEND.md Recommended method to start a Redis server for local development and testing using Docker. ```bash # Using Docker (recommended) docker run -d -p 6379:6379 redis:latest ``` -------------------------------- ### Clone and Setup for Development Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Clone the rust-rule-engine repository and navigate into the project directory to set up for development. ```bash # Clone and setup git clone https://github.com/KSD-CO/rust-rule-engine cd rust-rule-engine ``` -------------------------------- ### Run Backward Chaining Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/09-backward-chaining/README.md Execute the backward chaining example tests. Ensure the 'backward-chaining' feature is enabled. ```bash cargo run --example backward_critical_missing_tests --features backward-chaining ``` -------------------------------- ### Run RETE Engine Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/README.md Execute the 'rete_demo' and 'rete_grl_demo' examples for the RETE engine using Cargo. ```bash cargo run --example rete_demo cargo run --example rete_grl_demo ``` -------------------------------- ### Install Redis Locally Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/REDIS_STATE_BACKEND.md Instructions for installing Redis server locally on Ubuntu/Debian and macOS. ```bash # Or install locally # Ubuntu/Debian sudo apt-get install redis-server # macOS brew install redis ``` -------------------------------- ### Run Rust Rule Engine Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/01-getting-started/README.md Command to execute specific examples using Cargo. Use this to run the provided demos. ```bash cargo run --example grule_demo cargo run --example fraud_detection # ... other examples ``` -------------------------------- ### Run Rust Rule Engine Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Execute a specific example provided with the rust-rule-engine source code, such as 'basic_usage'. ```bash cargo run --example basic_usage ``` -------------------------------- ### Run Basic Real AI Integration Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/examples/AI_INTEGRATION.md Execute the basic real AI integration example using Cargo. This example demonstrates integration with OpenAI GPT-3.5, Anthropic Claude, Hugging Face models, and custom ML APIs with error handling. ```bash cargo run --example real_ai_integration ``` -------------------------------- ### Run in Development Mode Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Executes the basic usage example with auto-reloading enabled. ```bash cargo watch -x "run --example basic_usage" ``` -------------------------------- ### Run Production AI Service Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/examples/AI_INTEGRATION.md Execute the production AI service example using Cargo. This example showcases features like intelligent caching, automatic retries, cost tracking, multi-model comparison, and fallback strategies. ```bash cargo run --example production_ai_service ``` -------------------------------- ### Run RETE Examples with Cargo Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/07-advanced-rete/README.md Commands to execute specific RETE examples using Cargo. Use `--release` for optimized builds. ```bash cargo run --example rete_p2_working_memory ``` ```bash cargo run --example rete_p3_incremental ``` ```bash cargo run --release --example rete_engine_cached ``` -------------------------------- ### Run Backward Chaining Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/BACKWARD_CHAINING_QUICK_START.md Execute example Rust programs demonstrating nested queries, query optimization, and GRL file integration. Ensure the `backward-chaining` feature is enabled. ```bash # Nested queries cargo run --example nested_query_demo --features backward-chaining # Query optimization cargo run --example optimizer_demo --features backward-chaining # GRL integration cargo run --example grl_optimizer_demo --features backward-chaining ``` -------------------------------- ### GRL Smart Home Example with Modules Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/core-features/GRL_SYNTAX.md A comprehensive GRL example demonstrating module definitions, imports, exports, and rules for a smart home system. Organizes sensors, control logic, alerts, and logging into distinct modules. ```grl ;; ============================================ ;; MODULE DEFINITIONS ;; ============================================ defmodule SENSORS { export: all } defmodule CONTROL { import: SENSORS (rules * (templates temperature humidity motion)) export: all } defmodule ALERT { import: SENSORS (rules * (templates temperature)) import: CONTROL (rules * (templates hvac light)) export: all } defmodule LOGGER { import: SENSORS (rules * (templates *)) import: CONTROL (rules * (templates *)) import: ALERT (rules * (templates *)) export: all } ;; ============================================ ;; SENSORS MODULE - Temperature & Humidity ;; ============================================ rule "CheckHighTemperature" salience 100 { when temperature.value > 28 then println("⚠️ TEMPERATURE: " + temperature.location + " = " + temperature.value + "°C"); } rule "CheckLowTemperature" salience 100 { when temperature.value < 16 then println("❄️ COLD: " + temperature.location + " = " + temperature.value + "°C"); } rule "CheckHighHumidity" salience 90 { when humidity.value > 70 then println("⚠️ HUMIDITY: " + humidity.location + " = " + humidity.value + "%"); } ;; ============================================ ;; CONTROL MODULE - Decision Making ;; ============================================ rule "ActivateCooling" salience 80 { when temperature.value > 28 && hvac.state == "OFF" then println("🔧 CONTROL: AC activated"); hvac.state = "ON"; hvac.mode = "COOL"; } rule "ActivateHeating" salience 80 { when temperature.value < 16 && hvac.state == "OFF" then println("🔧 CONTROL: Heating activated"); hvac.state = "ON"; hvac.mode = "HEAT"; } rule "TurnOnLights" salience 70 { when motion.detected == true && light.state == "OFF" then println("💡 CONTROL: Lights ON"); light.state = "ON"; } ;; ============================================ ;; ALERT MODULE - Notifications ;; ============================================ rule "CriticalTemperature" salience 110 { when temperature.value > 35 then println("🚨 ALERT: CRITICAL - " + temperature.value + "°C"); } rule "LogACActivation" salience 50 { when hvac.state == "ON" && hvac.mode == "COOL" then println("📝 LOG: AC system activated"); } rule "LogHeatingActivation" salience 50 { when hvac.state == "ON" && hvac.mode == "HEAT" then println("📝 LOG: Heating system activated"); } ;; ============================================ ;; LOGGER MODULE - System Logging ;; ============================================ rule "LogAllTemperatureEvents" salience 40 { when temperature.value > 0 then println("📝 LOGGER: Temperature event - " + temperature.value + "°C"); } rule "LogSystemStatus" salience 30 { when hvac.state != "" then println("📝 LOGGER: HVAC Status - " + hvac.state + " (" + hvac.mode + ")"); } ``` -------------------------------- ### Verify Rust Rule Engine Installation Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md A basic Rust program to verify the installation by creating an engine, adding a rule, and running it with facts. ```rust use rust_rule_engine::{Engine, Facts, Value}; fn main() -> Result<(), Box> { let mut engine = Engine::new(); engine.add_rule_from_string(r#" rule "Test" { when X == 1 then Y = 2; } "#)?; let mut facts = Facts::new(); facts.set("X", Value::Integer(1)); engine.run(&mut facts)?; assert_eq!(facts.get("Y"), Some(&Value::Integer(2))); println!("✅ Installation verified!"); Ok(()) } ``` -------------------------------- ### Query & Reasoning Setup Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Configure the rust-rule-engine with the "backward-chaining" feature for query and reasoning capabilities. ```toml [dependencies.rust-rule-engine] version = "1.11" features = ["backward-chaining"] ``` -------------------------------- ### Run Explanation Demo (Make) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md Execute the explanation demo using Make. This is an alternative method to running the demo that showcases proof tree generation. ```bash make explanation_demo ``` -------------------------------- ### Run RETE Engine Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/02-rete-engine/README.md Command to run various RETE engine examples using Cargo. Ensure you have the Rust toolchain installed. ```bash cargo run --example rete_demo cargo run --example rete_grl_demo # ... other examples ``` -------------------------------- ### Directory Structure Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/DOCUMENTATION_STRUCTURE.md Illustrates the hierarchical organization of documentation files within the project. ```tree docs/ ├── README.md # Documentation index & navigation ├── BACKWARD_CHAINING_QUICK_START.md # Quick start for backward chaining ├── DOCUMENTATION_STRUCTURE.md # This file │ ├── getting-started/ # 🚀 New users start here │ ├── README.md # Getting started index │ ├── QUICK_START.md # 5-minute quick start │ ├── INSTALLATION.md # Installation guide │ ├── CONCEPTS.md # Core concepts │ └── FIRST_RULES.md # Writing your first rules │ ├── core-features/ # 🎯 Essential features │ ├── README.md # Core features index │ ├── GRL_SYNTAX.md # GRL language reference │ └── FEATURES.md # Features overview │ ├── advanced-features/ # ⚡ Advanced capabilities │ ├── README.md # Advanced features index │ ├── STREAMING.md # Stream processing intro │ ├── STREAMING_ARCHITECTURE.md # Streaming deep dive │ ├── STREAM_OPERATORS.md # Stream operators reference │ ├── PLUGINS.md # Plugin system │ ├── PERFORMANCE.md # Performance optimization │ ├── REDIS_STATE_BACKEND.md # Redis integration │ └── ADVANCED_USAGE.md # Advanced patterns │ ├── api-reference/ # 📖 API documentation │ ├── README.md # API reference index │ ├── API_REFERENCE.md # Public API reference │ ├── GRL_QUERY_SYNTAX.md # Query language (v1.11.0+) │ └── PARSER_CHEAT_SHEET.md # Parser quick reference │ ├── guides/ # 📝 How-to guides │ ├── README.md # Guides index │ ├── BACKWARD_CHAINING_RETE_INTEGRATION.md # Hybrid reasoning │ ├── MODULE_PARSING_GUIDE.md # Module management │ ├── TROUBLESHOOTING.md # Problem solving │ ├── CYCLIC_IMPORT_DETECTION.md # Import cycles │ └── MODULE_REFACTORING.md # Refactoring strategies │ └── examples/ # 💡 Real-world examples ├── README.md # Examples index └── AI_INTEGRATION.md # AI/ML integration ``` -------------------------------- ### Full Production Setup with Optimizations Source: https://github.com/ksd-co/rust-rule-engine/wiki/07-Performance-Optimization Combines Beta indexing, Alpha indexing (for large facts), and Node Sharing (for many rules) for a comprehensive production setup. ```rust // Full production setup use rust_rule_engine::rete:: AlphaMemoryIndex, BetaMemoryIndex, NodeSharingRegistry, // If >10K rules ; // 1. Beta indexing (always) let beta_index = BetaMemoryIndex::new("join_key".to_string()); // 2. Alpha indexing (if >10K facts) let mut alpha_mem = AlphaMemoryIndex::new(); alpha_mem.auto_tune(); // 3. Node sharing (if >10K rules, memory-constrained) let node_registry = NodeSharingRegistry::new(); ``` -------------------------------- ### Valid Module Name Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/MODULE_PARSING_GUIDE.md Illustrates valid module names according to the regex `([A-Z_]\w*)`, which must start with an uppercase letter or underscore. ```text SENSORS _PRIVATE CONTROL_V2 A ``` -------------------------------- ### Run E-commerce Approval Demo Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/09-backward-chaining/README.md Execute the e-commerce order approval system example to understand backward chaining in a real-world scenario. This example covers VIP customers, new customers, large orders, and batch processing. ```bash cargo run --example ecommerce_approval_demo --features backward-chaining ``` -------------------------------- ### Sample Output: Smart Home System with Module Architecture Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/10-module-system/README.md Illustrates the expected output from the smart home system example, showing the module structure, statistics, and current focus. ```text 🏠 Smart Home System with Module Architecture ... 📋 Module Structure: ✓ SENSORS (3 rules, 3 templates, exports all) ✓ CONTROL (3 rules, 2 templates, imports from SENSORS) ✓ ALERT (2 rules, 1 template, imports from SENSORS & CONTROL) ✓ LOGGER (3 rules, 1 template, imports from all) ... 📊 Statistics: Total Modules: 5 Current Focus: MAIN Visibility checks: 11/12 correct ✓ ``` -------------------------------- ### Key Prefixing Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/REDIS_STATE_BACKEND.md Demonstrates how to use the 'key_prefix' option to namespace keys in Redis, preventing collisions. ```rust StateBackend::Redis { url: "redis://127.0.0.1:6379".to_string(), key_prefix: "prod_stream_v2".to_string(), } // Key "counter" becomes "prod_stream_v2:counter" in Redis ``` -------------------------------- ### Get Field Analytics Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/STREAMING.md Retrieve and print analytics for a specific field, such as the overall average. This example shows how to access field-specific data and format numerical output. ```rust let analytics = engine.get_field_analytics("price").await; if let Some(Value::Number(avg)) = analytics.get("overall_average") { println!("Average price: ${:.2}", avg); } ``` -------------------------------- ### Initialize and Query Rule Engines Source: https://github.com/ksd-co/rust-rule-engine/blob/main/README.md Demonstrates setting up IncrementalEngine and BackwardEngine, enabling proof graph caching, and performing initial and subsequent queries to leverage the cache. ```rust use rust_rule_engine::backward::{BackwardEngine, DepthFirstSearch}; use rust_rule_engine::rete::IncrementalEngine; // Create engines let mut rete_engine = IncrementalEngine::new(); let kb = /* load rules */; let mut backward_engine = BackwardEngine::new(kb); // Create search with ProofGraph enabled let search = DepthFirstSearch::new_with_engine( backward_engine.kb().clone(), Arc::new(Mutex::new(rete_engine)), ); // First query builds cache let result1 = backward_engine.query_with_search( "eligible(?x)", &mut facts, Box::new(search.clone()), )?; // Subsequent queries use cache let result2 = backward_engine.query_with_search( "eligible(?x)", &mut facts, Box::new(search), )?; ``` -------------------------------- ### Run Simple Query Demo Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/09-backward-chaining/README.md Run the basic backward chaining query example to explore simple goal queries, results, proof traces, and missing fact detection. Demonstrates memoization benefits. ```bash cargo run --example simple_query_demo --features backward-chaining ``` -------------------------------- ### Rust Example: Smart Home Modules Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/10-module-system/README.md Demonstrates the module system by programmatically setting up a module hierarchy, including creation, import/export patterns, visibility analysis, and statistics. ```rust fn main() { // ... setup module hierarchy ... // ... import/export patterns ... // ... visibility analysis ... // ... statistics and introspection ... // ... module focus/execution flow ... } ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Installs cargo-watch for auto-reloading and cargo-tarpaulin for test coverage. ```bash cargo install cargo-watch ``` ```bash cargo install cargo-tarpaulin ``` -------------------------------- ### Create and Run Your First Rule Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/QUICK_START.md This example demonstrates how to create a new engine, add a rule from a string, set up facts, run the engine, and assert the results. Ensure the 'Customer.TotalSpent' fact is set before running. ```rust use rust_rule_engine::{Engine, Facts, Value}; fn main() -> Result<(), Box> { // 1. Create an engine let mut engine = Engine::new(); // 2. Add a simple rule engine.add_rule_from_string(r#"" rule "VIP Discount" { when Customer.TotalSpent > 1000 then Customer.DiscountRate = 0.2; Customer.IsVIP = true; } "#)?; // 3. Set up facts let mut facts = Facts::new(); facts.set("Customer.TotalSpent", Value::Number(1500.0)); // 4. Run the engine engine.run(&mut facts)?; // 5. Check results assert_eq!(facts.get("Customer.IsVIP"), Some(&Value::Boolean(true))); assert_eq!(facts.get("Customer.DiscountRate"), Some(&Value::Number(0.2))); println!("✅ VIP status granted with 20% discount!"); Ok(()) } ``` -------------------------------- ### Run Quick Engine Comparison Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/05-performance/README.md Execute the quick engine comparison example to compare Native vs RETE engine performance. Use this for a basic understanding of engine differences. ```bash cargo run --example quick_engine_comparison ``` -------------------------------- ### Table of Contents Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/DOCUMENTATION_STRUCTURE.md Example of a table of contents for navigating longer documentation files. ```markdown ## Table of Contents 1. [Section 1](#section-1) 2. [Section 2](#section-2) ``` -------------------------------- ### Main Application Setup with Actix-web Source: https://github.com/ksd-co/rust-rule-engine/wiki/04-Production-Deployment Sets up the Actix-web server, initializes configuration, logging, database, cache, and the rule engine. It defines routes for health checks, rule execution, and rule reloading. ```rust use actix_web::{web, App, HttpServer}; use std::sync::Arc; #[actix_web::main] async fn main() -> std::io::Result<()> { // Configuration let config = Config::from_env(); // Initialize logging init_logging(&config.logging.level); tracing::info!("Starting Rust Rule Engine Service"); tracing::info!("Config: {:?}", config); // Database let db = Arc::new(Database::new(&config.database.url, config.database.pool_size).await); tracing::info!("Database connected"); // Cache let cache = Arc::new(Cache::new(&config.cache.url)); tracing::info!("Cache initialized"); // Rule Engine let engine = Arc::new(RuleEngineManager::new(&config.engine.rules_dir).await); tracing::info!("Rule engine loaded"); // Start HTTP server let server_config = config.clone(); let http_server = HttpServer::new(move || { App::new() .app_data(web::Data::new(engine.clone())) .app_data(web::Data::new(cache.clone())) .app_data(web::Data::new(db.clone())) .route("/health", web::get().to(health_check)) .route("/execute", web::post().to(execute_rules)) .route("/admin/reload", web::post().to(reload_rules)) }) .workers(server_config.server.workers) .bind(format!("{}:{}", server_config.server.host, server_config.server.port))? .run() .await?; Ok(()) } ``` -------------------------------- ### Run Optimizer Demo (Make) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md Execute the optimizer demo using Make. This command is used to run examples showcasing query optimization techniques. ```bash make optimizer_demo ``` -------------------------------- ### Basic Parallel Execution Setup Source: https://github.com/ksd-co/rust-rule-engine/blob/main/RETE_ARCHITECTURE.md Demonstrates the basic steps to create a parallel rule engine, add rules, and execute them. Ensure the `rust_rule_engine::engine::ParallelRuleEngine` and `ParallelConfig` are available. ```rust use rust_rule_engine::engine::ParallelRuleEngine; // Create parallel engine let mut engine = ParallelRuleEngine::new(ParallelConfig::default())?; // Add rules (will be analyzed for dependencies) engine.add_rules_from_grl(&grl_content)?; // Execute in parallel let result = engine.execute_parallel().await?; println!("Parallel execution results:"); println!("- Rules fired: {}", result.fired_rules.len()); println!("- Execution time: {}ms", result.execution_time_ms); println!("- Thread utilization: {}%", result.thread_utilization); println!("- Speedup vs sequential: {:.1}x", result.speedup_factor); ``` -------------------------------- ### Run Explanation Demo (Cargo) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md Execute the explanation demo using Cargo, enabling the backward-chaining feature. This demo showcases proof tree generation and export capabilities. ```bash cargo run --features backward-chaining --example explanation_demo ``` -------------------------------- ### Run Optimizer Demo (Cargo) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md Execute the optimizer demo using Cargo with the backward-chaining feature enabled. This example highlights query optimization techniques. ```bash cargo run --example optimizer_demo --features backward-chaining ``` -------------------------------- ### Install Recommended Tools Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/INSTALLATION.md Installs rustfmt for code formatting, clippy for linting, and opens generated documentation. ```bash cargo install rustfmt ``` ```bash cargo install clippy ``` ```bash cargo doc --open --all-features ``` -------------------------------- ### Detective Investigation Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md An example of a GRL query for a detective investigation, determining guilt and recommending actions. ```APIDOC ## Detective Investigation Query ```grl query "CheckSuspectGuilty" { goal: Investigation.Guilty == true strategy: depth-first max-depth: 15 on-success: { Investigation.Verdict = "Guilty"; Action.RecommendedAction = "Issue arrest warrant"; LogProofTrace(); } on-failure: { Investigation.Verdict = "Insufficient Evidence"; Investigation.MissingEvidence = GetMissingFacts(); Action.RecommendedAction = "Continue investigation"; } } ``` ``` -------------------------------- ### Medical Diagnosis Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md An example of a GRL query for medical diagnosis, including rules and success/failure actions. ```APIDOC ## Medical Diagnosis Query ```grl rule "DiagnoseFlu" { when Patient.HasFever == true && Patient.HasCough == true && Patient.HasFatigue == true then Diagnosis.Disease = "Influenza"; } rule "FeverFromInfection" { when Patient.WhiteBloodCellCount > 11000 then Patient.HasFever = true; } // Query to check diagnosis query "CheckFluDiagnosis" { goal: Diagnosis.Disease == "Influenza" strategy: depth-first max-depth: 10 enable-memoization: true on-success: { LogMessage("Flu diagnosis confirmed"); Treatment.Recommended = "Rest and fluids"; } on-failure: { LogMessage("Flu not confirmed"); Action.Next = "Consider other diagnoses"; } } ``` ``` -------------------------------- ### Rust Basic Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/RETE_ARCHITECTURE.md Demonstrates how to create a BackwardChainingEngine, add rules, set facts, and query if a user is VIP. ```rust use rust_rule_engine::backward::BackwardChainingEngine; // Create backward chaining engine let mut bc_engine = BackwardChainingEngine::new(); // Add rules for VIP determination bc_engine.add_rule(r#" rule "VIPUser" { when User.Tier == "gold" && User.Points > 1000 && User.IsActive == true then User.IsVIP = true; } "#)?; // Query if user is VIP let mut facts = TypedFacts::new(); facts.set("User.Tier", "gold"); facts.set("User.Points", 1500i64); facts.set("User.IsActive", true); let result = bc_engine.query("User.IsVIP == true", &mut facts)?; if result.success { println!("User is VIP! Proof: {:?}", result.proof_trace); } else { println!("User is not VIP"); } ``` -------------------------------- ### Run Proof Graph Cache Demo Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/PROOF_GRAPH_CACHING.md Command to execute the proof graph cache demonstration example, showcasing various caching scenarios. ```bash cargo run --example proof_graph_cache_demo --features backward-chaining ``` -------------------------------- ### Comprehensive Optimization Manager Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/advanced-features/RETE_OPTIMIZATION.md Demonstrates setting up and using an OptimizationManager, including registering rules for node sharing, processing facts with token pooling, and viewing statistics. Use for complex rule sets and performance tuning. ```rust use rust_rule_engine::rete::optimization::OptimizationManager; use rust_rule_engine::rete::{AlphaNode, TypedFacts}; fn main() { let mut manager = OptimizationManager::new(); // 1. Register rules with node sharing for i in 0..1000 { let node = AlphaNode { field: format!("field{}", i % 100), operator: ">".to_string(), value: "50".to_string(), }; manager.node_sharing.register(&node, i); } // 2. Process facts with token pooling for i in 0..10000 { let mut fact = TypedFacts::new(); fact.set("id", i as i64); fact.set("value", (i % 100) as i64); let token = manager.token_pool.acquire_with_fact(fact); // ... process ... manager.token_pool.release(token); } // 3. View comprehensive stats println!("{}", manager.stats()); } ``` -------------------------------- ### Install Hey for Load Testing (Bash) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/examples/AI_INTEGRATION.md This bash command installs the 'hey' load testing tool from GitHub. ```bash # Install hey for load testing go install github.com/rakyll/hey@latest ``` -------------------------------- ### Business Logic Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md An example of a GRL query for business logic, such as checking VIP eligibility and applying benefits. ```APIDOC ## Business Logic Query ```grl query "CheckVIPEligibility" { goal: Customer.IsVIP == true strategy: breadth-first max-depth: 5 on-success: { Customer.DiscountRate = 0.2; Customer.ShippingFree = true; LogMessage("VIP benefits applied"); } on-failure: { LogMessage("Customer not eligible for VIP"); Action.Recommend = "Suggest VIP upgrade"; } on-missing: { LogMessage("Missing customer data"); Request.AdditionalInfo = ["PurchaseHistory", "LoyaltyPoints"]; } } ``` ``` -------------------------------- ### Kafka Integration Steps Source: https://github.com/ksd-co/rust-rule-engine/blob/main/PROJECT_CREATED.txt Optional steps to integrate with Kafka. This includes installing cmake, setting up Kafka, running the Kafka consumer, and producing events. ```bash make kafka-setup ``` ```bash cargo run --features kafka --example kafka_consumer ``` ```bash make kafka-produce ``` -------------------------------- ### Run Demo and Tests Source: https://github.com/ksd-co/rust-rule-engine/blob/main/README.md Commands to execute the comprehensive demo with multiple scenarios and run integration tests for the proof graph functionality. ```bash # Run comprehensive demo with 5 scenarios cargo run --example proof_graph_cache_demo --features backward-chaining # Run integration tests cargo test proof_graph --features backward-chaining ``` -------------------------------- ### Medical Diagnosis GRL Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md A comprehensive GRL example for medical diagnosis, including rules and a query with success and failure actions. ```grl rule "DiagnoseFlu" { when Patient.HasFever == true && Patient.HasCough == true && Patient.HasFatigue == true then Diagnosis.Disease = "Influenza"; } rule "FeverFromInfection" { when Patient.WhiteBloodCellCount > 11000 then Patient.HasFever = true; } // Query to check diagnosis query "CheckFluDiagnosis" { goal: Diagnosis.Disease == "Influenza" strategy: depth-first max-depth: 10 enable-memoization: true on-success: { LogMessage("Flu diagnosis confirmed"); Treatment.Recommended = "Rest and fluids"; } on-failure: { LogMessage("Flu not confirmed"); Action.Next = "Consider other diagnoses"; } } ``` -------------------------------- ### Basic BackwardEngine Usage Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/BACKWARD_CHAINING_RETE_INTEGRATION.md Demonstrates the basic usage of the BackwardEngine, including its creation (which automatically builds the index) and performing a query. It also shows how to access index statistics. ```rust use rust_rule_engine::backward::{BackwardEngine, ConclusionIndex}; // Create engine (index built automatically) let mut engine = BackwardEngine::new(kb); // Query uses O(1) index lookup let result = engine.query("User.IsVIP == true", &mut facts)?; // Check index stats let stats = engine.index_stats(); println!("Indexed {} rules across {} fields", stats.total_rules, stats.indexed_fields); ``` -------------------------------- ### Run AI REST API Production Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/examples/AI_INTEGRATION.md Execute the AI REST API production example using Cargo. This example focuses on building a production-ready REST API with AI integration, including real-time cost tracking, cache monitoring, provider statistics, and health checks. ```bash cargo run --example ai_rest_api_production ``` -------------------------------- ### GRL Basic Rule Example Source: https://github.com/ksd-co/rust-rule-engine/wiki/03-GRL-Syntax-Guide An example of a GRL rule that applies a discount to an order if it meets specific criteria. Includes salience and no-loop attributes. ```grl rule "ApplyDiscount" salience 100 no-loop { when order.status == "active" && order.amount > 100 then order.discount = order.amount * 0.10; Log("Discount applied"); } ``` -------------------------------- ### Run Other Advanced Examples Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/03-advanced-features/README.md Execute various advanced examples of the Rust Rule Engine. These cover functionalities like custom accumulation, conflict resolution, and more. ```bash cargo run --example accumulate_demo cargo run --example conflict_resolution_demo ``` -------------------------------- ### Execute All Examples Test Script Source: https://github.com/ksd-co/rust-rule-engine/blob/main/EXAMPLE_TEST_REPORT_v1.19.3.md This bash script is used to run all example tests for the rule engine. It exits with code 0 if all tests pass. ```bash bash /tmp/test_all_examples.sh ``` -------------------------------- ### Plan Imports Carefully - Good Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/guides/CYCLIC_IMPORT_DETECTION.md Illustrates good import practices by showing clear layer structure and valid downward imports. ```rust // Good: Clear layer structure manager.import_from("APP", "CONTROL", ...)?; manager.import_from("CONTROL", "SENSORS", ...)?; // Would fail: manager.import_from("SENSORS", "APP", ...)?; ``` -------------------------------- ### Healthcare: Treatment Authorization Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/QUICK_START.md Example of a healthcare rule for treatment authorization. It authorizes treatment if the patient has 'Premium' insurance coverage and the treatment cost is below a threshold. ```rust // Treatment authorization rule "Authorize Treatment" { when Patient.InsuranceCoverage == "Premium" && Treatment.Cost < 10000 then Treatment.Authorized = true; } ``` -------------------------------- ### E-commerce: Dynamic Pricing Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/QUICK_START.md Example of an e-commerce rule for dynamic pricing. It applies a flash sale discount if the product is in 'Electronics' category and stock is sufficient. ```rust // Dynamic pricing rule "Flash Sale" { when Product.Category == "Electronics" && Inventory.Stock > 100 then Product.Price = Product.Price * 0.8; Product.Label = "Flash Sale!"; } ``` -------------------------------- ### Incomplete Rule Engine Initialization Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/DOCUMENTATION_STRUCTURE.md An example of an incomplete code snippet that lacks the necessary subsequent code for functionality. Use complete, runnable examples in documentation. ```rust let engine = Engine::new(); // ... what comes next? ``` -------------------------------- ### Run Optimization Demos with Cargo Source: https://github.com/ksd-co/rust-rule-engine/wiki/07-Performance-Optimization Execute demonstration commands using Cargo to see optimizations like alpha indexing, beta memory indexing, and GRL optimization in action. These examples provide practical insights into the performance improvements. ```bash # See alpha indexing in action cargo run --example alpha_indexing_demo # Beta memory indexing cargo run --example rete_optimization_demo # GRL with optimization cargo run --example grl_optimization_demo ``` -------------------------------- ### Detective Investigation GRL Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md A GRL query example for a detective investigation, focusing on determining guilt and outlining actions for success, failure, and missing evidence. ```grl query "CheckSuspectGuilty" { goal: Investigation.Guilty == true strategy: depth-first max-depth: 15 on-success: { Investigation.Verdict = "Guilty"; Action.RecommendedAction = "Issue arrest warrant"; LogProofTrace(); } on-failure: { Investigation.Verdict = "Insufficient Evidence"; Investigation.MissingEvidence = GetMissingFacts(); Action.RecommendedAction = "Continue investigation"; } } ``` -------------------------------- ### Run Examples with Cargo Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/rules/03-advanced/README.md Execute various rule engine demos using Cargo commands, covering conflict resolution, action handlers, pattern matching, and TMS. ```bash # Conflict resolution cargo run --example conflict_resolution_demo # Action handlers cargo run --example action_handlers_demo # Pattern matching cargo run --example pattern_matching_from_grl # TMS demo cargo run --example tms_demo ``` -------------------------------- ### Bash Commands for Running Demos Source: https://github.com/ksd-co/rust-rule-engine/blob/main/examples/rules/04-use-cases/README.md Provides example bash commands to run different demonstration applications included with the rule engine project. ```bash # Fraud detection demo cargo run --example fraud_detection # Analytics demo cargo run --example analytics_demo # Workflow demo cargo run --example workflow_engine_demo ``` -------------------------------- ### Business Logic GRL Query Example Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/api-reference/GRL_QUERY_SYNTAX.md An example of a GRL query for business logic, demonstrating VIP eligibility checks with success, failure, and missing data actions. ```grl query "CheckVIPEligibility" { goal: Customer.IsVIP == true strategy: breadth-first max-depth: 5 on-success: { Customer.DiscountRate = 0.2; Customer.ShippingFree = true; LogMessage("VIP benefits applied"); } on-failure: { LogMessage("Customer not eligible for VIP"); Action.Recommend = "Suggest VIP upgrade"; } on-missing: { LogMessage("Missing customer data"); Request.AdditionalInfo = ["PurchaseHistory", "LoyaltyPoints"]; } } ``` -------------------------------- ### E-commerce Rules Engine Example in Rust Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/getting-started/FIRST_RULES.md This snippet demonstrates how to set up and run an e-commerce rules engine in Rust. It includes defining rules for customer tiers, order discounts, shipping, and final total calculation, then processing facts to produce an order summary. ```rust use rust_rule_engine::{Engine, Facts, Value}; fn main() -> Result<(), Box> { let mut engine = Engine::new(); // Rule 1: VIP Status engine.add_rule_from_string(r#"" rule "Grant VIP Status" salience 100 { when Customer.TotalSpent > 5000 && Customer.OrderCount > 10 then Customer.IsVIP = true; Customer.Tier = "VIP"; } "#)?; // Rule 2: VIP Discount engine.add_rule_from_string(r#"" rule "VIP Discount" salience 90 { when Customer.IsVIP == true && Order.SubTotal > 0 then Order.VIPDiscount = Order.SubTotal * 0.15; } "#)?; // Rule 3: Free Shipping engine.add_rule_from_string(r#"" rule "Free Shipping for VIP" salience 80 { when Customer.IsVIP == true || Order.SubTotal > 100 then Order.ShippingCost = 0; Order.FreeShipping = true; } "#)?; // Rule 4: Calculate Total engine.add_rule_from_string(r#"" rule "Calculate Final Total" salience 70 { when Order.SubTotal > 0 then Order.Tax = Order.SubTotal * 0.08; Order.FinalTotal = Order.SubTotal - Order.VIPDiscount + Order.Tax + Order.ShippingCost; } "#)?; // Set up facts let mut facts = Facts::new(); facts.set("Customer.TotalSpent", Value::Number(6000.0)); facts.set("Customer.OrderCount", Value::Integer(15)); facts.set("Order.SubTotal", Value::Number(200.0)); facts.set("Order.VIPDiscount", Value::Number(0.0)); facts.set("Order.ShippingCost", Value::Number(9.99)); // Run engine engine.run(&mut facts)?; // Print results println!("=== Order Summary ==="); println!("VIP Status: {:?}", facts.get("Customer.IsVIP")); println!("SubTotal: ${:?}", facts.get("Order.SubTotal")); println!("VIP Discount: -${:?}", facts.get("Order.VIPDiscount")); println!("Tax: +${:?}", facts.get("Order.Tax")); println!("Shipping: ${:?}", facts.get("Order.ShippingCost")); println!("Final Total: ${:?}", facts.get("Order.FinalTotal")); Ok(()) } ``` -------------------------------- ### Start AI REST API (Bash) Source: https://github.com/ksd-co/rust-rule-engine/blob/main/docs/examples/AI_INTEGRATION.md This bash command starts the AI REST API in production mode. It is typically used as a prerequisite for running integration tests. ```bash # Start the AI REST API cargo run --example ai_rest_api_production ```