kbs 0.0.1 → 0.2.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 (93) 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 +291 -362
  5. data/docs/advanced/custom-persistence.md +775 -0
  6. data/docs/advanced/debugging.md +726 -0
  7. data/docs/advanced/index.md +8 -0
  8. data/docs/advanced/performance.md +865 -0
  9. data/docs/advanced/testing.md +827 -0
  10. data/docs/api/blackboard.md +1157 -0
  11. data/docs/api/engine.md +1047 -0
  12. data/docs/api/facts.md +1212 -0
  13. data/docs/api/index.md +12 -0
  14. data/docs/api/rules.md +1104 -0
  15. data/docs/architecture/blackboard.md +544 -0
  16. data/docs/architecture/index.md +277 -0
  17. data/docs/architecture/network-structure.md +343 -0
  18. data/docs/architecture/rete-algorithm.md +737 -0
  19. data/docs/assets/css/custom.css +83 -0
  20. data/docs/assets/images/blackboard-architecture.svg +136 -0
  21. data/docs/assets/images/compiled-network.svg +101 -0
  22. data/docs/assets/images/fact-assertion-flow.svg +117 -0
  23. data/docs/assets/images/fact-rule-relationship.svg +65 -0
  24. data/docs/assets/images/fact-structure.svg +42 -0
  25. data/docs/assets/images/inference-cycle.svg +47 -0
  26. data/docs/assets/images/kb-components.svg +43 -0
  27. data/docs/assets/images/kbs.jpg +0 -0
  28. data/docs/assets/images/pattern-matching-trace.svg +136 -0
  29. data/docs/assets/images/rete-network-layers.svg +96 -0
  30. data/docs/assets/images/rule-structure.svg +44 -0
  31. data/docs/assets/images/system-layers.svg +69 -0
  32. data/docs/assets/images/trading-signal-network.svg +139 -0
  33. data/docs/assets/js/mathjax.js +17 -0
  34. data/docs/examples/index.md +223 -0
  35. data/docs/guides/blackboard-memory.md +589 -0
  36. data/docs/guides/dsl.md +1321 -0
  37. data/docs/guides/facts.md +652 -0
  38. data/docs/guides/getting-started.md +385 -0
  39. data/docs/guides/index.md +23 -0
  40. data/docs/guides/negation.md +529 -0
  41. data/docs/guides/pattern-matching.md +561 -0
  42. data/docs/guides/persistence.md +451 -0
  43. data/docs/guides/variable-binding.md +491 -0
  44. data/docs/guides/writing-rules.md +914 -0
  45. data/docs/index.md +155 -0
  46. data/docs/installation.md +156 -0
  47. data/docs/quick-start.md +221 -0
  48. data/docs/what-is-a-fact.md +694 -0
  49. data/docs/what-is-a-knowledge-base.md +350 -0
  50. data/docs/what-is-a-rule.md +833 -0
  51. data/examples/.gitignore +1 -0
  52. data/examples/README.md +2 -2
  53. data/examples/advanced_example.rb +2 -2
  54. data/examples/advanced_example_dsl.rb +224 -0
  55. data/examples/ai_enhanced_kbs.rb +1 -1
  56. data/examples/ai_enhanced_kbs_dsl.rb +538 -0
  57. data/examples/blackboard_demo_dsl.rb +50 -0
  58. data/examples/car_diagnostic.rb +1 -1
  59. data/examples/car_diagnostic_dsl.rb +54 -0
  60. data/examples/concurrent_inference_demo.rb +5 -6
  61. data/examples/concurrent_inference_demo_dsl.rb +362 -0
  62. data/examples/csv_trading_system.rb +1 -1
  63. data/examples/csv_trading_system_dsl.rb +525 -0
  64. data/examples/iot_demo_using_dsl.rb +1 -1
  65. data/examples/portfolio_rebalancing_system.rb +2 -2
  66. data/examples/portfolio_rebalancing_system_dsl.rb +613 -0
  67. data/examples/redis_trading_demo_dsl.rb +177 -0
  68. data/examples/rule_source_demo.rb +123 -0
  69. data/examples/run_all.rb +50 -0
  70. data/examples/run_all_dsl.rb +49 -0
  71. data/examples/stock_trading_advanced.rb +1 -1
  72. data/examples/stock_trading_advanced_dsl.rb +404 -0
  73. data/examples/temp_dsl.txt +9392 -0
  74. data/examples/timestamped_trading.rb +1 -1
  75. data/examples/timestamped_trading_dsl.rb +258 -0
  76. data/examples/trading_demo.rb +1 -1
  77. data/examples/trading_demo_dsl.rb +322 -0
  78. data/examples/working_demo.rb +1 -1
  79. data/examples/working_demo_dsl.rb +160 -0
  80. data/lib/kbs/blackboard/engine.rb +3 -3
  81. data/lib/kbs/blackboard/fact.rb +1 -1
  82. data/lib/kbs/condition.rb +1 -1
  83. data/lib/kbs/decompiler.rb +204 -0
  84. data/lib/kbs/dsl/knowledge_base.rb +101 -2
  85. data/lib/kbs/dsl/variable.rb +1 -1
  86. data/lib/kbs/dsl.rb +3 -1
  87. data/lib/kbs/{rete_engine.rb → engine.rb} +42 -1
  88. data/lib/kbs/fact.rb +1 -1
  89. data/lib/kbs/version.rb +1 -1
  90. data/lib/kbs.rb +15 -13
  91. data/mkdocs.yml +181 -0
  92. metadata +74 -9
  93. data/examples/stock_trading_system.rb.bak +0 -563
data/README.md CHANGED
@@ -1,456 +1,381 @@
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'
41
-
42
- # Create a simple rule engine
43
- engine = KBS::ReteEngine.new
44
-
45
- # Define a rule
46
- rule = KBS::Rule.new(
47
- "high_temperature_alert",
48
- conditions: [
49
- KBS::Condition.new(:sensor, { type: "temperature" }),
50
- KBS::Condition.new(:reading, { value: ->(v) { v > 100 } })
51
- ],
52
- action: lambda do |facts, bindings|
53
- puts "ðŸšĻ HIGH TEMPERATURE ALERT!"
54
- reading = facts.find { |f| f.type == :reading }
55
- puts "Temperature: #{reading[:value]}°C"
56
- end
57
- )
72
+ require 'kbs'
58
73
 
59
- engine.add_rule(rule)
74
+ # Create knowledge base with DSL
75
+ kb = KBS.knowledge_base do
76
+ rule "high_temperature_alert" do
77
+ on :sensor, type: "temperature"
78
+ on :reading, value: greater_than(100)
79
+
80
+ perform do |facts, bindings|
81
+ reading = facts.find { |f| f.type == :reading }
82
+ puts "ðŸšĻ HIGH TEMPERATURE: #{reading[:value]}°C"
83
+ end
84
+ end
60
85
 
61
- # Add facts
62
- engine.add_fact(:sensor, { type: "temperature", location: "reactor" })
63
- engine.add_fact(:reading, { value: 105, unit: "celsius" })
86
+ # Add facts
87
+ fact :sensor, type: "temperature", location: "reactor"
88
+ fact :reading, value: 105, unit: "celsius"
64
89
 
65
- # Run inference
66
- engine.run
90
+ # Run inference
91
+ run
92
+ end
93
+ # => ðŸšĻ HIGH TEMPERATURE: 105°C
67
94
  ```
68
95
 
69
96
  ### Using the DSL
70
97
 
71
98
  ```ruby
72
- require_relative 'kbs_dsl'
99
+ require 'kbs'
73
100
 
74
101
  kb = KBS.knowledge_base do
75
- rule "stock_momentum" do
76
- desc "Detect momentum breakouts"
102
+ rule "momentum_breakout" do
103
+ desc "Detect stock momentum breakouts"
77
104
  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|
105
+
106
+ on :stock, volume: greater_than(1_000_000)
107
+ on :stock, price_change_pct: greater_than(3)
108
+ without :position, status: "open"
109
+
110
+ perform do |facts, bindings|
84
111
  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]}"
112
+ puts "🚀 BREAKOUT: #{stock[:symbol]} +#{stock[:price_change_pct]}%"
88
113
  end
89
114
  end
90
115
  end
91
116
 
92
- # Add facts and run
93
- kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change: 4.2
117
+ kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change_pct: 4.2
94
118
  kb.run
119
+ # => 🚀 BREAKOUT: AAPL +4.2%
95
120
  ```
96
121
 
97
- ### Persistent Blackboard
122
+ ### Blackboard with SQLite Persistence
98
123
 
99
124
  ```ruby
100
- require_relative 'blackboard'
125
+ require 'kbs/blackboard'
101
126
 
102
- # Create persistent knowledge base
103
- engine = KBS::BlackboardEngine.new(db_path: 'knowledge.db')
127
+ # Create persistent blackboard with DSL
128
+ engine = KBS::Blackboard::Engine.new(db_path: 'knowledge.db')
104
129
 
105
- # Add persistent facts
106
- sensor = engine.add_fact(:sensor, { type: "temperature", location: "room1" })
107
- puts "Fact UUID: #{sensor.uuid}"
130
+ kb = KBS.knowledge_base(engine: engine) do
131
+ rule "temperature_monitor" do
132
+ on :sensor, type: "temperature", value: greater_than(25)
108
133
 
109
- # Query facts
110
- sensors = engine.blackboard.get_facts(:sensor)
111
- sensors.each { |s| puts s }
134
+ perform do |facts|
135
+ sensor = facts.first
136
+ puts "⚠ïļ High temperature at #{sensor[:location]}: #{sensor[:value]}°C"
137
+ end
138
+ end
112
139
 
113
- # Post messages
114
- engine.post_message("TemperatureMonitor", "alerts",
115
- { message: "Temperature spike detected", level: "warning" })
140
+ # Add persistent facts
141
+ fact :sensor, type: "temperature", location: "room1", value: 22
142
+ fact :sensor, type: "temperature", location: "room2", value: 28
116
143
 
117
- # Consume messages
118
- alert = engine.consume_message("alerts", "MainController")
119
- puts "Alert: #{alert[:content]}" if alert
120
- ```
144
+ run
145
+ end
121
146
 
122
- ## 📁 Project Structure
147
+ # Query facts
148
+ sensors = engine.blackboard.get_facts(:sensor)
149
+ sensors.each { |s| puts "#{s[:type]} at #{s[:location]}: #{s[:value]}°C" }
123
150
 
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
151
+ # View audit history
152
+ history = engine.blackboard.get_history(limit: 10)
153
+ history.each do |entry|
154
+ puts "[#{entry[:timestamp]}] #{entry[:action]}: #{entry[:fact_type]}"
155
+ end
145
156
  ```
146
157
 
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
158
+ ### Redis for High-Speed Storage
173
159
 
174
160
  ```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
180
-
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
161
+ require 'kbs/blackboard'
162
+
163
+ # High-frequency trading with Redis and DSL
164
+ store = KBS::Blackboard::Persistence::RedisStore.new(url: 'redis://localhost:6379/0')
165
+ engine = KBS::Blackboard::Engine.new(store: store)
166
+
167
+ kb = KBS.knowledge_base(engine: engine) do
168
+ rule "price_alert" do
169
+ on :market_price, volume: greater_than(500_000)
170
+
171
+ perform do |facts|
172
+ price = facts.first
173
+ puts "📊 High volume: #{price[:symbol]} - #{price[:volume]} shares"
174
+ # Post message for other components
175
+ engine.post_message("PriceAlert", "high_volume",
176
+ { symbol: price[:symbol], volume: price[:volume] },
177
+ priority: 10
178
+ )
179
+ end
180
+ end
193
181
 
194
- ```ruby
195
- require_relative 'portfolio_rebalancing_system'
182
+ # Fast in-memory fact storage
183
+ fact :market_price, symbol: "AAPL", price: 150.25, volume: 1_000_000
196
184
 
197
- # Advanced portfolio management with sector allocation
198
- system = PortfolioRebalancingSystem.new
199
- system.simulate_rebalancing_scenarios
185
+ run
186
+ end
200
187
 
201
- # Output:
202
- # ⚖ïļ ALLOCATION DRIFT: Technology
203
- # Current: 49.7%
204
- # Target: 40.0%
205
- # Drift: +24.3%
206
- # Action: REDUCE Technology allocation
188
+ # Consume messages
189
+ message = engine.consume_message("high_volume", "TradingStrategy")
190
+ puts "Received: #{message[:content]}" if message
207
191
  ```
208
192
 
209
- ## ðŸĪ– AI-Enhanced Knowledge System
210
-
211
- The system includes cutting-edge AI integration through `ruby_llm` and `ruby_llm-mcp` gems:
193
+ ### AI-Enhanced Reasoning
212
194
 
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
195
+ ```ruby
196
+ require 'kbs'
197
+ require 'ruby_llm'
220
198
 
221
- ### AI Integration Example
199
+ # Requires Ollama with a model installed
200
+ # export OLLAMA_MODEL=gpt-oss:latest
222
201
 
223
- ```ruby
224
- require_relative 'ai_enhanced_kbs'
202
+ kb = KBS.knowledge_base do
203
+ rule "ai_sentiment_analysis" do
204
+ on :news_data, symbol: satisfies { |s| s && s.length > 0 }
205
+
206
+ perform do |facts|
207
+ news = facts.first
208
+ # AI-powered sentiment analysis
209
+ client = RubyLLM::Chat.new(provider: :ollama, model: 'gpt-oss:latest')
210
+ response = client.ask("Analyze sentiment: #{news[:headline]}")
211
+
212
+ puts "ðŸĪ– AI SENTIMENT ANALYSIS: #{news[:symbol]}"
213
+ puts " Headline: #{news[:headline]}"
214
+ puts " AI Analysis: #{response.content}"
215
+ end
216
+ end
225
217
 
226
- # Create AI-powered knowledge system
227
- system = AIEnhancedKBS::AIKnowledgeSystem.new
228
- system.demonstrate_ai_enhancements
218
+ # Add news for AI sentiment analysis
219
+ fact :news_data,
220
+ symbol: "AAPL",
221
+ headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
222
+ content: "Apple Inc. announced exceptional results..."
229
223
 
230
- # Add market news for sentiment analysis
231
- system.engine.add_fact(:news_data, {
232
- symbol: "AAPL",
233
- headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
234
- content: "Apple Inc. announced exceptional results with 12% revenue growth..."
235
- })
224
+ run
225
+ end
236
226
 
237
227
  # Output:
238
228
  # ðŸĪ– 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
242
- # Market Impact: bullish
229
+ # Headline: Apple Reports Record Q4 Earnings, Beats Expectations by 15%
230
+ # AI Analysis: positive (92%) - strong earnings growth, bullish outlook
243
231
  ```
244
232
 
245
- ### Mock AI Implementation
233
+ ## 📚 Examples
246
234
 
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:
235
+ The `examples/` directory contains 13 comprehensive examples demonstrating all features:
248
236
 
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
- ```
237
+ ### Basic Examples
238
+ - **car_diagnostic.rb** - Simple expert system for car diagnostics
239
+ - **working_demo.rb** - Stock trading signal generator
262
240
 
263
- ## 🧠 RETE II Algorithm
241
+ ### DSL Examples
242
+ - **iot_demo_using_dsl.rb** - IoT sensor monitoring with declarative DSL
243
+ - **trading_demo.rb** - Multiple trading strategies
264
244
 
265
- The RETE II algorithm is an enhanced version of the original RETE algorithm with several key improvements:
245
+ ### Advanced Trading
246
+ - **advanced_example.rb** - Golden cross detection and technical analysis
247
+ - **stock_trading_advanced.rb** - Position management with stop losses
248
+ - **timestamped_trading.rb** - Time-aware temporal reasoning
249
+ - **csv_trading_system.rb** - CSV data integration and backtesting
250
+ - **portfolio_rebalancing_system.rb** - Portfolio optimization
266
251
 
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
252
+ ### Persistence & Architecture
253
+ - **blackboard_demo.rb** - SQLite persistence and message queue
254
+ - **redis_trading_demo.rb** - Redis and hybrid storage patterns
272
255
 
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
256
+ ### Advanced Features
257
+ - **concurrent_inference_demo.rb** - Auto-inference and background threads
258
+ - **ai_enhanced_kbs.rb** - LLM integration with Ollama
278
259
 
279
- ## ðŸ’ū Blackboard Architecture
260
+ See [examples/README.md](examples/README.md) for detailed documentation of each example.
280
261
 
281
- The blackboard system implements a multi-agent architecture where:
262
+ ## 🏗ïļ Architecture
282
263
 
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
264
+ ### RETE Network Structure
287
265
 
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
266
+ ```
267
+ Facts → Alpha Network → Beta Network → Production Nodes
268
+ (Pattern (Join Nodes) (Rule Actions)
269
+ Matching)
270
+ ```
293
271
 
294
- ## 🔧 Advanced Features
272
+ **Key Optimizations:**
273
+ - **Left/Right Unlinking**: Join nodes unlink when memories are empty
274
+ - **Selective Activation**: Only affected network nodes are updated
275
+ - **Token Firing State**: Prevents duplicate rule executions
276
+ - **Shared Patterns**: Common sub-patterns shared across rules
295
277
 
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
278
+ ### Blackboard Pattern
279
+
280
+ ```
281
+ ┌─────────────────────────────────────────┐
282
+ │ Blackboard (Memory) │
283
+ │ ┌────────────────────────────────────┐ │
284
+ │ │ Facts, Messages, Audit Trail │ │
285
+ │ └────────────────────────────────────┘ │
286
+ └─────────────────────────────────────────┘
287
+ ↑ ↑
288
+ │ │
289
+ ┌────────┐ ┌─────────┐
290
+ │ KS │ │ KS │ Knowledge Sources
291
+ │ #1 │ │ #2 │ (Agents)
292
+ └────────┘ └─────────┘
308
293
  ```
309
294
 
310
- ### Pattern Matching
311
- ```ruby
312
- # Functional patterns
313
- when :stock, price: ->(p) { p > 100 && p < 200 }
295
+ ## ðŸŽŊ Use Cases
314
296
 
315
- # Range patterns
316
- when :stock, rsi: between(30, 70)
297
+ ### Expert Systems
298
+ - Medical diagnosis
299
+ - Fault detection and troubleshooting
300
+ - Configuration and design assistance
301
+ - Technical support automation
302
+
303
+ ### Financial Applications
304
+ - Algorithmic trading systems
305
+ - Portfolio management and rebalancing
306
+ - Risk assessment and monitoring
307
+ - Market analysis and signal generation
308
+
309
+ ### Real-Time Monitoring
310
+ - IoT sensor analysis and alerts
311
+ - Network monitoring and anomaly detection
312
+ - Industrial process control
313
+ - Fraud detection systems
314
+
315
+ ### Business Automation
316
+ - Workflow automation
317
+ - Compliance checking
318
+ - Policy enforcement
319
+ - Dynamic pricing and promotions
317
320
 
318
- # Collection patterns
319
- when :stock, sector: one_of("Technology", "Healthcare")
321
+ ## ⚡ Performance
320
322
 
321
- # Regex patterns
322
- when :news, headline: matches(/earnings|profit/i)
323
- ```
323
+ ### Benchmarks
324
+ - **Rule Compilation**: ~1ms per rule for typical patterns
325
+ - **Fact Addition**: ~0.1ms per fact (warm network)
326
+ - **Pattern Matching**: ~10Ξs per pattern evaluation
327
+ - **SQLite vs Redis**: Redis ~100x faster for high-frequency operations
324
328
 
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
- ```
329
+ ### Complexity
330
+ - **Time**: O(RFP) where R=rules, F=facts, P=patterns per rule
331
+ - **Space**: O(RF) with unlinking optimization
332
+ - **Updates**: O(log R) for incremental fact changes
337
333
 
338
334
  ## 🧊 Testing
339
335
 
340
- Run the test suite:
336
+ Run the comprehensive test suite:
341
337
 
342
338
  ```bash
343
- ruby kbs_test.rb
339
+ rake test
344
340
  ```
345
341
 
346
- Run demonstrations:
342
+ Individual test files:
347
343
 
348
344
  ```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
345
+ ruby test/kbs_test.rb
346
+ ruby test/blackboard_test.rb
347
+ ruby test/dsl_test.rb
366
348
  ```
367
349
 
368
- ## 📊 Performance Characteristics
350
+ **Test Coverage**: 100% with 199 tests, 447 assertions, 0 failures
369
351
 
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
352
+ ## 📖 Documentation
375
353
 
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
354
+ ### Core Classes
381
355
 
382
- ## ðŸŽŊ Use Cases
356
+ - **KBS::ReteEngine** - Main inference engine
357
+ - **KBS::Rule** - Rule definition
358
+ - **KBS::Condition** - Pattern matching conditions
359
+ - **KBS::Fact** - Working memory facts
360
+ - **KBS::Blackboard::Engine** - Blackboard coordination
361
+ - **KBS::Blackboard::Persistence::SQLiteStore** - SQLite backend
362
+ - **KBS::Blackboard::Persistence::RedisStore** - Redis backend
363
+ - **KBS::Blackboard::Persistence::HybridStore** - Hybrid storage
383
364
 
384
- ### Expert Systems
385
- - Medical diagnosis systems
386
- - Fault detection and diagnostics
387
- - Configuration and design systems
388
- - Planning and scheduling
365
+ ### DSL Helpers
389
366
 
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
367
+ - `greater_than(n)` - Match values > n
368
+ - `less_than(n)` - Match values < n
369
+ - `range(min, max)` - Match values between min and max
370
+ - `one_of(*values)` - Match any of the values
371
+ - `matches(regex)` - Match regex pattern
401
372
 
402
- ### Research Applications
403
- - AI reasoning systems
404
- - Knowledge representation
405
- - Multi-agent systems
406
- - Cognitive architectures
373
+ ## 🔧 Requirements
407
374
 
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
- ```
416
-
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
- ```
433
-
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
- ```
375
+ - Ruby >= 3.2.0
376
+ - SQLite3 (bundled with most systems)
377
+ - Redis (optional, for Redis storage)
378
+ - Ollama (optional, for AI integration)
454
379
 
455
380
  ## ðŸĪ Contributing
456
381
 
@@ -466,8 +391,9 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
466
391
 
467
392
  ## 🙏 Acknowledgments
468
393
 
469
- - Charles Forgy for the original RETE algorithm
470
- - The AI research community for RETE II enhancements
394
+ - **Charles Forgy** for the original RETE algorithm
395
+ - **Robert Doorenbos** for RETE/UL and unlinking optimizations
396
+ - The AI and knowledge systems research community
471
397
  - Ruby community for excellent tooling and libraries
472
398
 
473
399
  ## 📚 References
@@ -475,7 +401,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
475
401
  - Forgy, C. L. (1982). "Rete: A fast algorithm for the many pattern/many object pattern match problem"
476
402
  - Doorenbos, R. B. (1995). "Production Matching for Large Learning Systems" (RETE/UL)
477
403
  - Friedman-Hill, E. (2003). "Jess in Action: Java Rule-based Systems"
404
+ - Englemore, R. & Morgan, T. (1988). "Blackboard Systems"
478
405
 
479
406
  ---
480
407
 
481
- Built with âĪïļ for the knowledge systems community.
408
+ **Built with âĪïļ for the Ruby community**
409
+
410
+ For more information, visit the [GitHub repository](https://github.com/madbomber/kbs).