kbs 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/deploy-github-pages.yml +52 -0
  3. data/CHANGELOG.md +68 -2
  4. data/README.md +235 -334
  5. data/docs/DOCUMENTATION_STATUS.md +158 -0
  6. data/docs/advanced/custom-persistence.md +775 -0
  7. data/docs/advanced/debugging.md +726 -0
  8. data/docs/advanced/index.md +8 -0
  9. data/docs/advanced/performance.md +832 -0
  10. data/docs/advanced/testing.md +691 -0
  11. data/docs/api/blackboard.md +1157 -0
  12. data/docs/api/engine.md +978 -0
  13. data/docs/api/facts.md +1212 -0
  14. data/docs/api/index.md +12 -0
  15. data/docs/api/rules.md +1034 -0
  16. data/docs/architecture/blackboard.md +553 -0
  17. data/docs/architecture/index.md +277 -0
  18. data/docs/architecture/network-structure.md +343 -0
  19. data/docs/architecture/rete-algorithm.md +737 -0
  20. data/docs/assets/css/custom.css +83 -0
  21. data/docs/assets/images/blackboard-architecture.svg +136 -0
  22. data/docs/assets/images/compiled-network.svg +101 -0
  23. data/docs/assets/images/fact-assertion-flow.svg +117 -0
  24. data/docs/assets/images/kbs.jpg +0 -0
  25. data/docs/assets/images/pattern-matching-trace.svg +136 -0
  26. data/docs/assets/images/rete-network-layers.svg +96 -0
  27. data/docs/assets/images/system-layers.svg +69 -0
  28. data/docs/assets/images/trading-signal-network.svg +139 -0
  29. data/docs/assets/js/mathjax.js +17 -0
  30. data/docs/examples/expert-systems.md +1031 -0
  31. data/docs/examples/index.md +9 -0
  32. data/docs/examples/multi-agent.md +1335 -0
  33. data/docs/examples/stock-trading.md +488 -0
  34. data/docs/guides/blackboard-memory.md +558 -0
  35. data/docs/guides/dsl.md +1321 -0
  36. data/docs/guides/facts.md +652 -0
  37. data/docs/guides/getting-started.md +383 -0
  38. data/docs/guides/index.md +23 -0
  39. data/docs/guides/negation.md +529 -0
  40. data/docs/guides/pattern-matching.md +561 -0
  41. data/docs/guides/persistence.md +451 -0
  42. data/docs/guides/variable-binding.md +491 -0
  43. data/docs/guides/writing-rules.md +755 -0
  44. data/docs/index.md +157 -0
  45. data/docs/installation.md +156 -0
  46. data/docs/quick-start.md +228 -0
  47. data/examples/README.md +2 -2
  48. data/examples/advanced_example.rb +2 -2
  49. data/examples/advanced_example_dsl.rb +224 -0
  50. data/examples/ai_enhanced_kbs.rb +1 -1
  51. data/examples/ai_enhanced_kbs_dsl.rb +538 -0
  52. data/examples/blackboard_demo_dsl.rb +50 -0
  53. data/examples/car_diagnostic.rb +1 -1
  54. data/examples/car_diagnostic_dsl.rb +54 -0
  55. data/examples/concurrent_inference_demo.rb +5 -5
  56. data/examples/concurrent_inference_demo_dsl.rb +363 -0
  57. data/examples/csv_trading_system.rb +1 -1
  58. data/examples/csv_trading_system_dsl.rb +525 -0
  59. data/examples/knowledge_base.db +0 -0
  60. data/examples/portfolio_rebalancing_system.rb +2 -2
  61. data/examples/portfolio_rebalancing_system_dsl.rb +613 -0
  62. data/examples/redis_trading_demo_dsl.rb +177 -0
  63. data/examples/run_all.rb +50 -0
  64. data/examples/run_all_dsl.rb +49 -0
  65. data/examples/stock_trading_advanced.rb +1 -1
  66. data/examples/stock_trading_advanced_dsl.rb +404 -0
  67. data/examples/temp.txt +7693 -0
  68. data/examples/temp_dsl.txt +8447 -0
  69. data/examples/timestamped_trading.rb +1 -1
  70. data/examples/timestamped_trading_dsl.rb +258 -0
  71. data/examples/trading_demo.rb +1 -1
  72. data/examples/trading_demo_dsl.rb +322 -0
  73. data/examples/working_demo.rb +1 -1
  74. data/examples/working_demo_dsl.rb +160 -0
  75. data/lib/kbs/blackboard/engine.rb +3 -3
  76. data/lib/kbs/blackboard/fact.rb +1 -1
  77. data/lib/kbs/condition.rb +1 -1
  78. data/lib/kbs/dsl/knowledge_base.rb +1 -1
  79. data/lib/kbs/dsl/variable.rb +1 -1
  80. data/lib/kbs/{rete_engine.rb → engine.rb} +1 -1
  81. data/lib/kbs/fact.rb +1 -1
  82. data/lib/kbs/version.rb +1 -1
  83. data/lib/kbs.rb +2 -2
  84. data/mkdocs.yml +181 -0
  85. metadata +66 -6
  86. data/examples/stock_trading_system.rb.bak +0 -563
data/README.md CHANGED
@@ -1,45 +1,77 @@
1
- # RETE II Knowledge-Based System in Ruby
1
+ ![KBS - Knowledge-Based System](docs/assets/images/kbs.jpg)
2
2
 
3
- A comprehensive implementation of the RETE II algorithm and knowledge-based systems architecture in Ruby, featuring persistent blackboard memory, domain-specific language for rule definition, and real-world applications including an advanced stock trading expert system.
3
+ # KBS - Knowledge-Based System
4
4
 
5
- ## 🌟 Features
5
+ A comprehensive Ruby implementation of a Knowledge-Based System featuring the RETE algorithm, Blackboard architecture, and AI integration for building intelligent rule-based applications.
6
6
 
7
- ### Core RETE II Engine
8
- - **Complete RETE II Implementation**: Enhanced pattern matching with unlinking optimization
7
+ [![Ruby](https://img.shields.io/badge/ruby-%3E%3D%203.2.0-red.svg)](https://www.ruby-lang.org/)
8
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
+
10
+ See the [full documentation website](https://madbomber.github.io/kbs/).
11
+
12
+ ## 🌟 Key Features
13
+
14
+ ### RETE Inference Engine
15
+ - **Optimized Pattern Matching**: RETE algorithm with unlinking optimization for high-performance forward-chaining inference
9
16
  - **Incremental Updates**: Efficient fact addition/removal without full network recomputation
10
- - **Negation Support**: Built-in handling of NOT conditions in rules
17
+ - **Negation Support**: Built-in handling of NOT conditions and absence patterns
11
18
  - **Memory Optimization**: Nodes automatically unlink when empty to reduce computation
12
- - **Pattern Sharing**: Common sub-patterns shared between rules for efficiency
13
-
14
- ### Domain Specific Language (DSL)
15
- - **Natural Rule Syntax**: Write rules in readable, English-like syntax
16
- - **Rich Condition Types**: `when`, `given`, `not`, `absent`, `missing`
17
- - **Pattern Helpers**: `greater_than`, `less_than`, `between`, `in`, `matches`
18
- - **Variable Binding**: Automatic variable extraction and binding
19
-
20
- ### Blackboard Memory System
21
- - **SQLite Persistence**: Full ACID compliance with persistent fact storage
22
- - **Message Queue**: Inter-component communication system
23
- - **Audit Trail**: Complete history of all fact changes and rule firings
24
- - **Transaction Support**: Atomic operations with rollback capability
25
- - **Query Interface**: SQL-based fact retrieval with indexing
26
-
27
- ### Stock Trading Expert System
28
- - **20+ Trading Strategies**: Golden cross, momentum, RSI reversal, breakouts, etc.
29
- - **Technical Analysis**: Moving averages, RSI, volume analysis, VWAP, trend following
30
- - **Risk Management**: Stop losses, take profits, position sizing, correlation analysis
31
- - **Portfolio Management**: Sector rebalancing, position replacement, quality optimization
32
- - **CSV Historical Processing**: Backtesting with multi-day OHLC data
33
- - **AI-Enhanced Decision Making**: LLM-powered sentiment analysis and strategy generation
19
+ - **Pattern Sharing**: Common sub-patterns shared between rules for maximum efficiency
20
+
21
+ ### Declarative DSL
22
+ - **Readable Syntax**: Write rules in natural, expressive Ruby syntax
23
+ - **Condition Helpers**: `greater_than`, `less_than`, `range`, `one_of`, `matches` for intuitive pattern matching
24
+ - **Rule Metadata**: Descriptions, priorities, and documentation built-in
25
+ - **Negative Patterns**: `without` keyword for absence testing
26
+
27
+ ### Blackboard Architecture
28
+ - **Multi-Agent Coordination**: Knowledge sources collaborate via shared blackboard
29
+ - **Message Passing**: Inter-component communication with priority-based message queue
30
+ - **Knowledge Source Registration**: Modular agent registration with topic subscriptions
31
+ - **Session Management**: Isolated reasoning sessions with cleanup
32
+
33
+ ### Flexible Persistence
34
+ - **SQLite Storage**: ACID-compliant persistent fact storage with full transaction support
35
+ - **Redis Storage**: High-speed in-memory fact storage for real-time systems (100x faster)
36
+ - **Hybrid Storage**: Best of both worlds - Redis for facts, SQLite for audit trail
37
+ - **Audit Trails**: Complete history of all fact changes and reasoning steps
38
+ - **Query Interface**: Powerful fact retrieval with pattern matching and SQL queries
39
+
40
+ ### Concurrent Execution
41
+ - **Auto-Inference Mode**: Background thread continuously runs inference as facts change
42
+ - **Thread-Safe**: Concurrent fact assertion and rule firing
43
+ - **Real-Time Processing**: Perfect for monitoring systems and event-driven architectures
44
+
45
+ ### AI Integration
46
+ - **LLM Integration**: Native support for Ollama, OpenAI via RubyLLM gem
47
+ - **Hybrid Reasoning**: Combine symbolic rules with neural AI for enhanced decision-making
48
+ - **Sentiment Analysis**: AI-powered news and text analysis
49
+ - **Strategy Generation**: LLMs create trading strategies based on market conditions
50
+ - **Natural Language**: Generate human-readable explanations for decisions
51
+ - **Pattern Recognition**: AI identifies complex patterns beyond traditional indicators
34
52
 
35
53
  ## 🚀 Quick Start
36
54
 
55
+ ### Installation
56
+
57
+ Add to your Gemfile:
58
+
59
+ ```ruby
60
+ gem 'kbs'
61
+ ```
62
+
63
+ Or install directly:
64
+
65
+ ```bash
66
+ gem install kbs
67
+ ```
68
+
37
69
  ### Basic Usage
38
70
 
39
71
  ```ruby
40
- require_relative 'kbs'
72
+ require 'kbs'
41
73
 
42
- # Create a simple rule engine
74
+ # Create inference engine
43
75
  engine = KBS::ReteEngine.new
44
76
 
45
77
  # Define a rule
@@ -50,9 +82,8 @@ rule = KBS::Rule.new(
50
82
  KBS::Condition.new(:reading, { value: ->(v) { v > 100 } })
51
83
  ],
52
84
  action: lambda do |facts, bindings|
53
- puts "ðŸšĻ HIGH TEMPERATURE ALERT!"
54
85
  reading = facts.find { |f| f.type == :reading }
55
- puts "Temperature: #{reading[:value]}°C"
86
+ puts "ðŸšĻ HIGH TEMPERATURE: #{reading[:value]}°C"
56
87
  end
57
88
  )
58
89
 
@@ -64,43 +95,45 @@ engine.add_fact(:reading, { value: 105, unit: "celsius" })
64
95
 
65
96
  # Run inference
66
97
  engine.run
98
+ # => ðŸšĻ HIGH TEMPERATURE: 105°C
67
99
  ```
68
100
 
69
101
  ### Using the DSL
70
102
 
71
103
  ```ruby
72
- require_relative 'kbs_dsl'
104
+ require 'kbs'
105
+ require 'kbs/dsl'
73
106
 
74
107
  kb = KBS.knowledge_base do
75
- rule "stock_momentum" do
76
- desc "Detect momentum breakouts"
108
+ rule "momentum_breakout" do
109
+ desc "Detect stock momentum breakouts"
77
110
  priority 10
78
-
79
- when :stock, volume: greater_than(1_000_000)
80
- when :stock, price_change: greater_than(3)
81
- not.when :position, status: "open"
82
-
83
- then do |facts, bindings|
111
+
112
+ on :stock, volume: greater_than(1_000_000)
113
+ on :stock, price_change_pct: greater_than(3)
114
+ without :position, status: "open"
115
+
116
+ perform do |facts, bindings|
84
117
  stock = facts.find { |f| f.type == :stock }
85
- puts "🚀 MOMENTUM BREAKOUT: #{stock[:symbol]}"
86
- puts " Price Change: +#{stock[:price_change]}%"
87
- puts " Volume: #{stock[:volume]}"
118
+ puts "🚀 BREAKOUT: #{stock[:symbol]} +#{stock[:price_change_pct]}%"
88
119
  end
89
120
  end
90
121
  end
91
122
 
92
- # Add facts and run
93
- kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change: 4.2
123
+ kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change_pct: 4.2
94
124
  kb.run
125
+ # => 🚀 BREAKOUT: AAPL +4.2%
95
126
  ```
96
127
 
97
- ### Persistent Blackboard
128
+ ### Blackboard with SQLite Persistence
98
129
 
99
130
  ```ruby
100
- require_relative 'blackboard'
131
+ require 'kbs/blackboard'
101
132
 
102
- # Create persistent knowledge base
103
- engine = KBS::BlackboardEngine.new(db_path: 'knowledge.db')
133
+ # Create persistent blackboard
134
+ engine = KBS::Blackboard::Engine.new(
135
+ store: KBS::Blackboard::Persistence::SQLiteStore.new(db_path: 'knowledge.db')
136
+ )
104
137
 
105
138
  # Add persistent facts
106
139
  sensor = engine.add_fact(:sensor, { type: "temperature", location: "room1" })
@@ -108,349 +141,213 @@ puts "Fact UUID: #{sensor.uuid}"
108
141
 
109
142
  # Query facts
110
143
  sensors = engine.blackboard.get_facts(:sensor)
111
- sensors.each { |s| puts s }
112
-
113
- # Post messages
114
- engine.post_message("TemperatureMonitor", "alerts",
115
- { message: "Temperature spike detected", level: "warning" })
144
+ sensors.each { |s| puts "#{s[:type]} at #{s[:location]}" }
116
145
 
117
- # Consume messages
118
- alert = engine.consume_message("alerts", "MainController")
119
- puts "Alert: #{alert[:content]}" if alert
120
- ```
121
-
122
- ## 📁 Project Structure
123
-
124
- ```
125
- kbs/
126
- ├── README.md # This comprehensive documentation
127
- ├── kbs.rb # Core RETE II implementation
128
- ├── kbs_dsl.rb # Domain Specific Language
129
- ├── blackboard.rb # Persistent blackboard memory system
130
- ├── csv_trading_system.rb # Historical data backtesting system
131
- ├── portfolio_rebalancing_system.rb # Advanced portfolio management
132
- ├── ai_enhanced_kbs.rb # AI-powered enhancements
133
- ├── sample_stock_data.csv # Historical market data
134
- ├── knowledge_base.db # Persistent SQLite database
135
- ├── examples/ # Demo and example files
136
- │ ├── stock_trading_advanced.rb # Advanced trading strategies
137
- │ ├── stock_trading_system.rb # Basic trading examples
138
- │ ├── timestamped_trading.rb # Temporal fact processing
139
- │ ├── trading_demo.rb # Trading scenarios demo
140
- │ ├── working_demo.rb # Basic working examples
141
- │ └── kbs_advanced_example.rb # Complex RETE examples
142
- └── tests/ # Unit test files
143
- ├── kbs_test.rb # Comprehensive unit tests
144
- └── simple_test.rb # Simple unit tests
146
+ # View audit history
147
+ history = engine.blackboard.get_history(limit: 10)
148
+ history.each do |entry|
149
+ puts "[#{entry[:timestamp]}] #{entry[:action]}: #{entry[:fact_type]}"
150
+ end
145
151
  ```
146
152
 
147
- ## ðŸĶ Stock Trading System
148
-
149
- The included stock trading expert system demonstrates real-world application with:
150
-
151
- ### Trading Strategies
152
- - **Golden Cross**: 20-day MA crosses above 50-day MA with volume confirmation
153
- - **RSI Oversold Bounce**: RSI < 30 with price reversal signals
154
- - **Breakout Patterns**: Resistance breaks with volume spikes
155
- - **Trend Following**: Strong uptrend identification with momentum
156
- - **Take Profit**: Automated profit-taking at 10%+ gains
157
- - **Stop Loss**: Risk management with 8% loss limits
158
- - **Portfolio Rebalancing**: Sector allocation drift correction
159
- - **Position Replacement**: Underperformer swapping with quality candidates
160
- - **Correlation Risk Reduction**: High correlation position diversification
161
- - **Momentum Rotation**: Sector rotation based on momentum trends
162
- - **Quality Upgrades**: Low quality position replacement
163
- - **Risk-Adjusted Optimization**: Sharpe ratio-based position management
164
-
165
- ### Portfolio Management Features
166
- - **Sector Allocation Targets**: Technology 40%, Healthcare 25%, Finance 20%, Consumer 15%
167
- - **Drift Detection**: Automatic rebalancing when allocations exceed 5% targets
168
- - **Performance Tracking**: Relative performance monitoring vs sector benchmarks
169
- - **Correlation Analysis**: Position correlation monitoring and risk reduction
170
- - **Quality Scoring**: Fundamental analysis integration for position evaluation
171
-
172
- ### CSV Historical Processing
153
+ ### Redis for High-Speed Storage
173
154
 
174
155
  ```ruby
175
- require_relative 'csv_trading_system'
176
-
177
- # Process historical OHLC data with technical analysis
178
- system = CSVTradingSystem.new('sample_stock_data.csv')
179
- system.process_csv_data
156
+ require 'kbs/blackboard'
180
157
 
181
- # Output:
182
- # ðŸĶ CSV TRADING SYSTEM - Historical Backtesting
183
- # Initial Capital: $100,000
184
- # 📅 2024-08-01 - Processing AAPL
185
- # 📈 GOLDEN CROSS: AAPL
186
- # 20-MA: $194.25
187
- # 50-MA: $193.15
188
- # Signal: Strong BUY
189
- # ✅ EXECUTED: BUY 100 shares of AAPL at $194.25
190
- ```
191
-
192
- ### Portfolio Rebalancing
158
+ # High-frequency trading with Redis
159
+ engine = KBS::Blackboard::Engine.new(
160
+ store: KBS::Blackboard::Persistence::RedisStore.new(
161
+ url: 'redis://localhost:6379/0'
162
+ )
163
+ )
193
164
 
194
- ```ruby
195
- require_relative 'portfolio_rebalancing_system'
165
+ # Fast in-memory fact storage
166
+ engine.add_fact(:market_price, { symbol: "AAPL", price: 150.25, volume: 1_000_000 })
196
167
 
197
- # Advanced portfolio management with sector allocation
198
- system = PortfolioRebalancingSystem.new
199
- system.simulate_rebalancing_scenarios
168
+ # Message queue for real-time coordination
169
+ engine.post_message("MarketDataFeed", "prices",
170
+ { symbol: "AAPL", bid: 150.24, ask: 150.26 },
171
+ priority: 10
172
+ )
200
173
 
201
- # Output:
202
- # ⚖ïļ ALLOCATION DRIFT: Technology
203
- # Current: 49.7%
204
- # Target: 40.0%
205
- # Drift: +24.3%
206
- # Action: REDUCE Technology allocation
174
+ message = engine.consume_message("prices", "TradingStrategy")
175
+ puts "Received: #{message[:content]}"
207
176
  ```
208
177
 
209
- ## ðŸĪ– AI-Enhanced Knowledge System
210
-
211
- The system includes cutting-edge AI integration through `ruby_llm` and `ruby_llm-mcp` gems:
212
-
213
- ### AI Features
214
- - **Sentiment Analysis**: LLM-powered news sentiment analysis for market intelligence
215
- - **Dynamic Strategy Generation**: AI creates trading strategies based on market conditions
216
- - **Risk Assessment**: Intelligent position risk analysis with confidence scoring
217
- - **Pattern Recognition**: AI identifies complex market patterns beyond traditional indicators
218
- - **Natural Language Explanations**: Human-readable explanations for all trading decisions
219
- - **Adaptive Rule Creation**: System generates new rules based on detected anomalies
220
-
221
- ### AI Integration Example
178
+ ### AI-Enhanced Reasoning
222
179
 
223
180
  ```ruby
224
- require_relative 'ai_enhanced_kbs'
181
+ require 'kbs'
182
+ require 'kbs/examples/ai_enhanced_kbs'
183
+
184
+ # Requires Ollama with a model installed
185
+ # export OLLAMA_MODEL=gpt-oss:latest
225
186
 
226
- # Create AI-powered knowledge system
227
187
  system = AIEnhancedKBS::AIKnowledgeSystem.new
228
- system.demonstrate_ai_enhancements
229
188
 
230
- # Add market news for sentiment analysis
189
+ # Add news for AI sentiment analysis
231
190
  system.engine.add_fact(:news_data, {
232
191
  symbol: "AAPL",
233
192
  headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
234
- content: "Apple Inc. announced exceptional results with 12% revenue growth..."
193
+ content: "Apple Inc. announced exceptional results..."
235
194
  })
236
195
 
196
+ system.engine.run
197
+
237
198
  # Output:
238
199
  # ðŸĪ– AI SENTIMENT ANALYSIS: AAPL
239
- # Headline: Apple Reports Record Q4 Earnings, Beats Expectations by 15%...
240
- # AI Sentiment: positive (75%)
241
- # Key Themes: earnings, growth
200
+ # AI Sentiment: positive (92%)
201
+ # Key Themes: strong earnings growth, share buyback program
242
202
  # Market Impact: bullish
243
203
  ```
244
204
 
245
- ### Mock AI Implementation
205
+ ## 📚 Examples
246
206
 
247
- When the AI gems aren't available, the system gracefully falls back to mock implementations, ensuring the system remains functional for testing and development:
207
+ The `examples/` directory contains 13 comprehensive examples demonstrating all features:
248
208
 
249
- ```ruby
250
- # Automatic fallback to mock implementations
251
- class MockAIClient
252
- def complete(prompt)
253
- case prompt
254
- when /sentiment/i
255
- '{"sentiment": "positive", "score": 0.7, "confidence": 75}'
256
- when /strategy/i
257
- '{"name": "Momentum Strategy", "rationale": "Market showing upward momentum"}'
258
- end
259
- end
260
- end
261
- ```
209
+ ### Basic Examples
210
+ - **car_diagnostic.rb** - Simple expert system for car diagnostics
211
+ - **working_demo.rb** - Stock trading signal generator
262
212
 
263
- ## 🧠 RETE II Algorithm
213
+ ### DSL Examples
214
+ - **iot_demo_using_dsl.rb** - IoT sensor monitoring with declarative DSL
215
+ - **trading_demo.rb** - Multiple trading strategies
264
216
 
265
- The RETE II algorithm is an enhanced version of the original RETE algorithm with several key improvements:
217
+ ### Advanced Trading
218
+ - **advanced_example.rb** - Golden cross detection and technical analysis
219
+ - **stock_trading_advanced.rb** - Position management with stop losses
220
+ - **timestamped_trading.rb** - Time-aware temporal reasoning
221
+ - **csv_trading_system.rb** - CSV data integration and backtesting
222
+ - **portfolio_rebalancing_system.rb** - Portfolio optimization
266
223
 
267
- ### Key Features
268
- - **Unlinking**: Nodes can be temporarily unlinked when they have no matches
269
- - **Left/Right Unlinking**: Both sides of join nodes can be optimized
270
- - **Negation Handling**: Improved support for NOT conditions
271
- - **Memory Efficiency**: Reduced memory usage through intelligent unlinking
224
+ ### Persistence & Architecture
225
+ - **blackboard_demo.rb** - SQLite persistence and message queue
226
+ - **redis_trading_demo.rb** - Redis and hybrid storage patterns
272
227
 
273
- ### Performance Benefits
274
- - **Sparse Data Optimization**: Excellent performance when only small subsets of rules are active
275
- - **Incremental Updates**: Only affected parts of the network are recomputed
276
- - **Reduced Join Operations**: Unlinking eliminates unnecessary join computations
277
- - **Better Scalability**: Handles large rule sets more efficiently
228
+ ### Advanced Features
229
+ - **concurrent_inference_demo.rb** - Auto-inference and background threads
230
+ - **ai_enhanced_kbs.rb** - LLM integration with Ollama
278
231
 
279
- ## ðŸ’ū Blackboard Architecture
232
+ See [examples/README.md](examples/README.md) for detailed documentation of each example.
280
233
 
281
- The blackboard system implements a multi-agent architecture where:
234
+ ## 🏗ïļ Architecture
282
235
 
283
- - **Knowledge Sources**: Independent reasoning agents
284
- - **Blackboard**: Shared memory space for facts and hypotheses
285
- - **Control**: Manages knowledge source activation and scheduling
286
- - **Persistence**: SQLite backend for fault tolerance
236
+ ### RETE Network Structure
237
+
238
+ ```
239
+ Facts → Alpha Network → Beta Network → Production Nodes
240
+ (Pattern (Join Nodes) (Rule Actions)
241
+ Matching)
242
+ ```
287
243
 
288
- ### Benefits
289
- - **Modularity**: Easy to add new reasoning capabilities
290
- - **Fault Tolerance**: Persistent state survives system restarts
291
- - **Auditability**: Complete history of all reasoning steps
292
- - **Scalability**: Multiple agents can work concurrently
244
+ **Key Optimizations:**
245
+ - **Left/Right Unlinking**: Join nodes unlink when memories are empty
246
+ - **Selective Activation**: Only affected network nodes are updated
247
+ - **Token Firing State**: Prevents duplicate rule executions
248
+ - **Shared Patterns**: Common sub-patterns shared across rules
293
249
 
294
- ## 🔧 Advanced Features
250
+ ### Blackboard Pattern
295
251
 
296
- ### Variable Binding
297
- ```ruby
298
- rule "price_alert" do
299
- when :stock do
300
- symbol :?stock_symbol
301
- price greater_than(100)
302
- end
303
-
304
- then do |facts, bindings|
305
- puts "Alert for #{bindings[:?stock_symbol]}"
306
- end
307
- end
252
+ ```
253
+ ┌─────────────────────────────────────────┐
254
+ │ Blackboard (Memory) │
255
+ │ ┌────────────────────────────────────┐ │
256
+ │ │ Facts, Messages, Audit Trail │ │
257
+ │ └────────────────────────────────────┘ │
258
+ └─────────────────────────────────────────┘
259
+ ↑ ↑
260
+ │ │
261
+ ┌────────┐ ┌─────────┐
262
+ │ KS │ │ KS │ Knowledge Sources
263
+ │ #1 │ │ #2 │ (Agents)
264
+ └────────┘ └─────────┘
308
265
  ```
309
266
 
310
- ### Pattern Matching
311
- ```ruby
312
- # Functional patterns
313
- when :stock, price: ->(p) { p > 100 && p < 200 }
267
+ ## ðŸŽŊ Use Cases
314
268
 
315
- # Range patterns
316
- when :stock, rsi: between(30, 70)
269
+ ### Expert Systems
270
+ - Medical diagnosis
271
+ - Fault detection and troubleshooting
272
+ - Configuration and design assistance
273
+ - Technical support automation
274
+
275
+ ### Financial Applications
276
+ - Algorithmic trading systems
277
+ - Portfolio management and rebalancing
278
+ - Risk assessment and monitoring
279
+ - Market analysis and signal generation
280
+
281
+ ### Real-Time Monitoring
282
+ - IoT sensor analysis and alerts
283
+ - Network monitoring and anomaly detection
284
+ - Industrial process control
285
+ - Fraud detection systems
286
+
287
+ ### Business Automation
288
+ - Workflow automation
289
+ - Compliance checking
290
+ - Policy enforcement
291
+ - Dynamic pricing and promotions
317
292
 
318
- # Collection patterns
319
- when :stock, sector: one_of("Technology", "Healthcare")
293
+ ## ⚡ Performance
320
294
 
321
- # Regex patterns
322
- when :news, headline: matches(/earnings|profit/i)
323
- ```
295
+ ### Benchmarks
296
+ - **Rule Compilation**: ~1ms per rule for typical patterns
297
+ - **Fact Addition**: ~0.1ms per fact (warm network)
298
+ - **Pattern Matching**: ~10Ξs per pattern evaluation
299
+ - **SQLite vs Redis**: Redis ~100x faster for high-frequency operations
324
300
 
325
- ### Negation and Absence
326
- ```ruby
327
- rule "no_open_positions" do
328
- when :signal, action: "buy"
329
- not.when :position, status: "open" # No open positions
330
- absent :risk_alert, level: "high" # No high risk alerts
331
-
332
- then do |facts, bindings|
333
- puts "Safe to open new position"
334
- end
335
- end
336
- ```
301
+ ### Complexity
302
+ - **Time**: O(RFP) where R=rules, F=facts, P=patterns per rule
303
+ - **Space**: O(RF) with unlinking optimization
304
+ - **Updates**: O(log R) for incremental fact changes
337
305
 
338
306
  ## 🧊 Testing
339
307
 
340
- Run the test suite:
308
+ Run the comprehensive test suite:
341
309
 
342
310
  ```bash
343
- ruby kbs_test.rb
311
+ rake test
344
312
  ```
345
313
 
346
- Run demonstrations:
314
+ Individual test files:
347
315
 
348
316
  ```bash
349
- # Core system functionality
350
- ruby kbs.rb # Basic RETE II engine
351
- ruby blackboard.rb # Blackboard persistence
352
- ruby csv_trading_system.rb # Historical CSV trading
353
- ruby portfolio_rebalancing_system.rb # Portfolio management
354
- ruby ai_enhanced_kbs.rb # AI-enhanced system
355
-
356
- # Example programs
357
- ruby examples/stock_trading_advanced.rb # Advanced trading system
358
- ruby examples/working_demo.rb # Basic working examples
359
- ruby examples/trading_demo.rb # Trading scenarios
360
- ruby examples/timestamped_trading.rb # Temporal processing
361
- ruby examples/kbs_advanced_example.rb # Complex RETE examples
362
-
363
- # Testing
364
- ruby tests/kbs_test.rb # Comprehensive tests
365
- ruby tests/simple_test.rb # Simple unit tests
317
+ ruby test/kbs_test.rb
318
+ ruby test/blackboard_test.rb
319
+ ruby test/dsl_test.rb
366
320
  ```
367
321
 
368
- ## 📊 Performance Characteristics
369
-
370
- ### RETE II Optimizations
371
- - **Time Complexity**: O(RFP) where R=rules, F=facts, P=patterns
372
- - **Space Complexity**: O(RF) with unlinking optimization
373
- - **Update Performance**: O(log R) for incremental updates
374
- - **Memory Usage**: Significantly reduced vs. original RETE
375
-
376
- ### Benchmarks
377
- - **Rule Compilation**: ~1ms per rule for typical patterns
378
- - **Fact Addition**: ~0.1ms per fact (warm network)
379
- - **Pattern Matching**: ~10Ξs per pattern evaluation
380
- - **Network Update**: ~0.01ms per affected node
322
+ **Test Coverage**: 100% with 199 tests, 447 assertions, 0 failures
381
323
 
382
- ## ðŸŽŊ Use Cases
324
+ ## 📖 Documentation
383
325
 
384
- ### Expert Systems
385
- - Medical diagnosis systems
386
- - Fault detection and diagnostics
387
- - Configuration and design systems
388
- - Planning and scheduling
326
+ ### Core Classes
389
327
 
390
- ### Business Rules
391
- - Compliance checking
392
- - Workflow automation
393
- - Pricing and discount rules
394
- - Policy enforcement
395
-
396
- ### Real-Time Systems
397
- - IoT event processing
398
- - Network monitoring
399
- - Fraud detection
400
- - Trading systems
328
+ - **KBS::ReteEngine** - Main inference engine
329
+ - **KBS::Rule** - Rule definition
330
+ - **KBS::Condition** - Pattern matching conditions
331
+ - **KBS::Fact** - Working memory facts
332
+ - **KBS::Blackboard::Engine** - Blackboard coordination
333
+ - **KBS::Blackboard::Persistence::SQLiteStore** - SQLite backend
334
+ - **KBS::Blackboard::Persistence::RedisStore** - Redis backend
335
+ - **KBS::Blackboard::Persistence::HybridStore** - Hybrid storage
401
336
 
402
- ### Research Applications
403
- - AI reasoning systems
404
- - Knowledge representation
405
- - Multi-agent systems
406
- - Cognitive architectures
337
+ ### DSL Helpers
407
338
 
408
- ## 🔎 Technical Details
409
-
410
- ### RETE Network Structure
411
- ```
412
- Facts → Alpha Network → Beta Network → Production Nodes
413
- (Pattern (Join Nodes) (Actions)
414
- Matching)
415
- ```
339
+ - `greater_than(n)` - Match values > n
340
+ - `less_than(n)` - Match values < n
341
+ - `range(min, max)` - Match values between min and max
342
+ - `one_of(*values)` - Match any of the values
343
+ - `matches(regex)` - Match regex pattern
416
344
 
417
- ### Unlinking Algorithm
418
- ```ruby
419
- class BetaMemory
420
- def unlink!
421
- return if @tokens.empty?
422
- @linked = false
423
- @successors.each { |s| s.left_unlink! }
424
- end
425
-
426
- def relink!
427
- return if @tokens.empty?
428
- @linked = true
429
- @successors.each { |s| s.left_relink! }
430
- end
431
- end
432
- ```
345
+ ## 🔧 Requirements
433
346
 
434
- ### Blackboard Schema
435
- ```sql
436
- -- Core fact storage
437
- CREATE TABLE facts (
438
- id INTEGER PRIMARY KEY,
439
- uuid TEXT UNIQUE,
440
- fact_type TEXT,
441
- attributes TEXT,
442
- created_at TIMESTAMP,
443
- retracted BOOLEAN DEFAULT 0
444
- );
445
-
446
- -- Audit trail
447
- CREATE TABLE fact_history (
448
- id INTEGER PRIMARY KEY,
449
- fact_uuid TEXT,
450
- action TEXT,
451
- timestamp TIMESTAMP
452
- );
453
- ```
347
+ - Ruby >= 3.2.0
348
+ - SQLite3 (bundled with most systems)
349
+ - Redis (optional, for Redis storage)
350
+ - Ollama (optional, for AI integration)
454
351
 
455
352
  ## ðŸĪ Contributing
456
353
 
@@ -466,8 +363,9 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
466
363
 
467
364
  ## 🙏 Acknowledgments
468
365
 
469
- - Charles Forgy for the original RETE algorithm
470
- - The AI research community for RETE II enhancements
366
+ - **Charles Forgy** for the original RETE algorithm
367
+ - **Robert Doorenbos** for RETE/UL and unlinking optimizations
368
+ - The AI and knowledge systems research community
471
369
  - Ruby community for excellent tooling and libraries
472
370
 
473
371
  ## 📚 References
@@ -475,7 +373,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
475
373
  - Forgy, C. L. (1982). "Rete: A fast algorithm for the many pattern/many object pattern match problem"
476
374
  - Doorenbos, R. B. (1995). "Production Matching for Large Learning Systems" (RETE/UL)
477
375
  - Friedman-Hill, E. (2003). "Jess in Action: Java Rule-based Systems"
376
+ - Englemore, R. & Morgan, T. (1988). "Blackboard Systems"
478
377
 
479
378
  ---
480
379
 
481
- Built with âĪïļ for the knowledge systems community.
380
+ **Built with âĪïļ for the Ruby community**
381
+
382
+ For more information, visit the [GitHub repository](https://github.com/madbomber/kbs).