kbs 0.2.1 → 0.4.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 (134) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -1
  3. data/README.md +66 -25
  4. data/lib/kbs/agenda.rb +301 -0
  5. data/lib/kbs/alpha_memory.rb +80 -9
  6. data/lib/kbs/alpha_network.rb +95 -0
  7. data/lib/kbs/beta_memory.rb +54 -19
  8. data/lib/kbs/blackboard/audit_log.rb +26 -25
  9. data/lib/kbs/blackboard/engine.rb +49 -40
  10. data/lib/kbs/blackboard/fact.rb +17 -21
  11. data/lib/kbs/blackboard/memory.rb +116 -40
  12. data/lib/kbs/blackboard/message_queue.rb +39 -28
  13. data/lib/kbs/blackboard/persistence/hybrid_store.rb +20 -9
  14. data/lib/kbs/blackboard/persistence/redis_store.rb +59 -51
  15. data/lib/kbs/blackboard/persistence/sqlite_store.rb +29 -32
  16. data/lib/kbs/blackboard/persistence/store.rb +11 -1
  17. data/lib/kbs/blackboard/redis_message_queue.rb +16 -7
  18. data/lib/kbs/condition.rb +42 -2
  19. data/lib/kbs/decompiler.rb +300 -124
  20. data/lib/kbs/dsl/condition_helpers.rb +8 -6
  21. data/lib/kbs/dsl/knowledge_base.rb +73 -93
  22. data/lib/kbs/dsl/pattern_evaluator.rb +38 -15
  23. data/lib/kbs/dsl/rule_builder.rb +118 -40
  24. data/lib/kbs/dsl/variable.rb +51 -6
  25. data/lib/kbs/dsl.rb +10 -3
  26. data/lib/kbs/engine.rb +395 -77
  27. data/lib/kbs/errors.rb +38 -0
  28. data/lib/kbs/exists_node.rb +12 -0
  29. data/lib/kbs/fact.rb +5 -19
  30. data/lib/kbs/fact_registry.rb +51 -0
  31. data/lib/kbs/introspection.rb +93 -0
  32. data/lib/kbs/join_indexing.rb +106 -0
  33. data/lib/kbs/join_node.rb +93 -57
  34. data/lib/kbs/join_test_builder.rb +80 -0
  35. data/lib/kbs/join_tests.rb +66 -0
  36. data/lib/kbs/memory_index.rb +104 -0
  37. data/lib/kbs/negation_node.rb +6 -82
  38. data/lib/kbs/network_node.rb +31 -0
  39. data/lib/kbs/pattern_matching.rb +52 -0
  40. data/lib/kbs/production_node.rb +50 -6
  41. data/lib/kbs/quantifier_node.rb +140 -0
  42. data/lib/kbs/rule.rb +26 -13
  43. data/lib/kbs/rule_source.rb +74 -0
  44. data/lib/kbs/rule_step.rb +27 -0
  45. data/lib/kbs/token.rb +76 -10
  46. data/lib/kbs/tracer.rb +80 -0
  47. data/lib/kbs/truth_maintenance.rb +82 -0
  48. data/lib/kbs/version.rb +1 -1
  49. data/lib/kbs/working_memory.rb +25 -3
  50. data/lib/kbs.rb +17 -4
  51. metadata +22 -129
  52. data/.envrc +0 -3
  53. data/.github/workflows/deploy-github-pages.yml +0 -52
  54. data/COMMITS.md +0 -196
  55. data/Rakefile +0 -8
  56. data/docs/advanced/custom-persistence.md +0 -775
  57. data/docs/advanced/debugging.md +0 -726
  58. data/docs/advanced/index.md +0 -8
  59. data/docs/advanced/performance.md +0 -865
  60. data/docs/advanced/testing.md +0 -827
  61. data/docs/api/blackboard.md +0 -1157
  62. data/docs/api/engine.md +0 -1047
  63. data/docs/api/facts.md +0 -1212
  64. data/docs/api/index.md +0 -12
  65. data/docs/api/rules.md +0 -1104
  66. data/docs/architecture/blackboard.md +0 -544
  67. data/docs/architecture/index.md +0 -277
  68. data/docs/architecture/network-structure.md +0 -343
  69. data/docs/architecture/rete-algorithm.md +0 -737
  70. data/docs/assets/css/custom.css +0 -83
  71. data/docs/assets/images/blackboard-architecture.svg +0 -136
  72. data/docs/assets/images/compiled-network.svg +0 -101
  73. data/docs/assets/images/fact-assertion-flow.svg +0 -117
  74. data/docs/assets/images/fact-rule-relationship.svg +0 -65
  75. data/docs/assets/images/fact-structure.svg +0 -42
  76. data/docs/assets/images/inference-cycle.svg +0 -47
  77. data/docs/assets/images/kb-components.svg +0 -43
  78. data/docs/assets/images/kbs.jpg +0 -0
  79. data/docs/assets/images/pattern-matching-trace.svg +0 -136
  80. data/docs/assets/images/rete-network-layers.svg +0 -96
  81. data/docs/assets/images/rule-structure.svg +0 -44
  82. data/docs/assets/images/system-layers.svg +0 -69
  83. data/docs/assets/images/trading-signal-network.svg +0 -139
  84. data/docs/assets/js/mathjax.js +0 -17
  85. data/docs/examples/index.md +0 -223
  86. data/docs/guides/blackboard-memory.md +0 -589
  87. data/docs/guides/dsl.md +0 -1321
  88. data/docs/guides/facts.md +0 -652
  89. data/docs/guides/getting-started.md +0 -385
  90. data/docs/guides/index.md +0 -23
  91. data/docs/guides/negation.md +0 -529
  92. data/docs/guides/pattern-matching.md +0 -561
  93. data/docs/guides/persistence.md +0 -451
  94. data/docs/guides/variable-binding.md +0 -491
  95. data/docs/guides/writing-rules.md +0 -914
  96. data/docs/index.md +0 -155
  97. data/docs/installation.md +0 -156
  98. data/docs/quick-start.md +0 -221
  99. data/docs/what-is-a-fact.md +0 -694
  100. data/docs/what-is-a-knowledge-base.md +0 -350
  101. data/docs/what-is-a-rule.md +0 -833
  102. data/examples/.gitignore +0 -1
  103. data/examples/README.md +0 -531
  104. data/examples/advanced_example.rb +0 -270
  105. data/examples/advanced_example_dsl.rb +0 -224
  106. data/examples/ai_enhanced_kbs.rb +0 -523
  107. data/examples/ai_enhanced_kbs_dsl.rb +0 -538
  108. data/examples/blackboard_demo.rb +0 -50
  109. data/examples/blackboard_demo_dsl.rb +0 -50
  110. data/examples/car_diagnostic.rb +0 -64
  111. data/examples/car_diagnostic_dsl.rb +0 -54
  112. data/examples/concurrent_inference_demo.rb +0 -362
  113. data/examples/concurrent_inference_demo_dsl.rb +0 -362
  114. data/examples/csv_trading_system.rb +0 -559
  115. data/examples/csv_trading_system_dsl.rb +0 -525
  116. data/examples/iot_demo_using_dsl.rb +0 -83
  117. data/examples/portfolio_rebalancing_system.rb +0 -651
  118. data/examples/portfolio_rebalancing_system_dsl.rb +0 -613
  119. data/examples/redis_trading_demo.rb +0 -177
  120. data/examples/redis_trading_demo_dsl.rb +0 -177
  121. data/examples/rule_source_demo.rb +0 -123
  122. data/examples/run_all.rb +0 -50
  123. data/examples/run_all_dsl.rb +0 -49
  124. data/examples/sample_stock_data.csv +0 -46
  125. data/examples/stock_trading_advanced.rb +0 -469
  126. data/examples/stock_trading_advanced_dsl.rb +0 -404
  127. data/examples/temp_dsl.txt +0 -9392
  128. data/examples/timestamped_trading.rb +0 -286
  129. data/examples/timestamped_trading_dsl.rb +0 -258
  130. data/examples/trading_demo.rb +0 -334
  131. data/examples/trading_demo_dsl.rb +0 -322
  132. data/examples/working_demo.rb +0 -176
  133. data/examples/working_demo_dsl.rb +0 -160
  134. data/mkdocs.yml +0 -181
@@ -1,177 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require_relative '../lib/kbs/blackboard'
4
-
5
- puts "Redis-Backed High-Frequency Trading System"
6
- puts "=" * 70
7
-
8
- # Demo 1: Pure Redis Store (fast, in-memory)
9
- puts "\n=== Pure Redis Store Demo ==="
10
- puts "Fast in-memory fact storage with Redis"
11
-
12
- begin
13
- redis_store = KBS::Blackboard::Persistence::RedisStore.new(
14
- url: 'redis://localhost:6379/1' # Use DB 1 for demo
15
- )
16
-
17
- # Clear previous demo data
18
- redis_store.redis.flushdb
19
- puts "(Cleared previous Redis data)"
20
-
21
- engine = KBS::Blackboard::Engine.new(store: redis_store)
22
-
23
- # Add trading rules
24
- spread_rule = KBS::Rule.new('tight_spread_opportunity') do |r|
25
- r.conditions << KBS::Condition.new(:market_price, { symbol: 'AAPL' })
26
- r.conditions << KBS::Condition.new(:order, { symbol: 'AAPL', type: 'BUY' })
27
- r.action = ->(facts) {
28
- price = facts.find { |f| f.type == :market_price }
29
- order = facts.find { |f| f.type == :order }
30
- spread = 0.02 # Tight spread
31
- puts "\n💹 TRADING SIGNAL: Tight spread opportunity for #{price[:symbol]}"
32
- puts " Price: $#{price[:price]}, Spread: $#{spread}"
33
- puts " Order: #{order[:type]} #{order[:quantity]} @ $#{order[:limit]}"
34
- }
35
- end
36
-
37
- high_volume_rule = KBS::Rule.new('high_volume_alert') do |r|
38
- r.conditions << KBS::Condition.new(:market_price, { volume: ->(v) { v > 800 } })
39
- r.action = ->(facts) {
40
- price = facts.first
41
- puts "\n📊 HIGH VOLUME: #{price[:symbol]} trading at #{price[:volume]} shares"
42
- }
43
- end
44
-
45
- engine.add_rule(spread_rule)
46
- engine.add_rule(high_volume_rule)
47
-
48
- puts "\nAdding high-frequency market data..."
49
- price1 = engine.add_fact(:market_price, { symbol: "AAPL", price: 150.25, volume: 1000 })
50
- price2 = engine.add_fact(:market_price, { symbol: "GOOGL", price: 2800.50, volume: 500 })
51
- order = engine.add_fact(:order, { symbol: "AAPL", type: "BUY", quantity: 100, limit: 150.00 })
52
-
53
- puts "Facts added with UUIDs:"
54
- puts " AAPL Price: #{price1.uuid}"
55
- puts " GOOGL Price: #{price2.uuid}"
56
- puts " Order: #{order.uuid}"
57
-
58
- puts "\nRunning inference engine..."
59
- engine.run
60
-
61
- puts "\nPosting trading messages..."
62
- engine.post_message("MarketDataFeed", "prices", { symbol: "AAPL", bid: 150.24, ask: 150.26 }, priority: 10)
63
- engine.post_message("OrderManager", "orders", { action: "fill", order_id: order.uuid }, priority: 5)
64
-
65
- puts "\nConsuming highest priority message..."
66
- message = engine.consume_message("prices", "TradingStrategy")
67
- puts " Received: #{message[:content]}" if message
68
-
69
- puts "\nQuerying market prices..."
70
- prices = engine.blackboard.get_facts(:market_price)
71
- puts " Found #{prices.size} price(s):"
72
- prices.each { |p| puts " - #{p}" }
73
-
74
- puts "\nRedis Statistics:"
75
- stats = engine.stats
76
- stats.each do |key, value|
77
- puts " #{key.to_s.gsub('_', ' ').capitalize}: #{value}"
78
- end
79
-
80
- engine.blackboard.close
81
-
82
- rescue Redis::CannotConnectError => e
83
- puts "\n⚠️ Redis not available: #{e.message}"
84
- puts " Please start Redis: redis-server"
85
- puts " Or install Redis: brew install redis (macOS)"
86
- end
87
-
88
- # Demo 2: Hybrid Store (Redis + SQLite)
89
- puts "\n\n=== Hybrid Store Demo ==="
90
- puts "Redis for fast fact access + SQLite for durable audit trail"
91
-
92
- begin
93
- hybrid_store = KBS::Blackboard::Persistence::HybridStore.new(
94
- redis_url: 'redis://localhost:6379/2', # Use DB 2 for demo
95
- db_path: ':memory:' # In-memory SQLite for demo
96
- )
97
-
98
- # Clear previous demo data from Redis
99
- hybrid_store.redis_store.redis.flushdb
100
- puts "(Cleared previous Redis data)"
101
-
102
- engine = KBS::Blackboard::Engine.new(store: hybrid_store)
103
-
104
- # Add monitoring rules
105
- temp_alert = KBS::Rule.new('temperature_alert') do |r|
106
- r.conditions << KBS::Condition.new(:sensor, {
107
- type: 'temperature',
108
- value: ->(v) { v > 25 }
109
- })
110
- r.action = ->(facts) {
111
- sensor = facts.first
112
- puts "\n🌡️ TEMPERATURE ALERT: #{sensor[:location]} at #{sensor[:value]}°C (threshold: 25°C)"
113
- }
114
- end
115
-
116
- cpu_warning = KBS::Rule.new('cpu_warning') do |r|
117
- r.conditions << KBS::Condition.new(:sensor, {
118
- type: 'cpu_usage',
119
- value: ->(v) { v > 40 }
120
- })
121
- r.action = ->(facts) {
122
- sensor = facts.first
123
- puts "\n⚙️ CPU WARNING: #{sensor[:location]} at #{sensor[:value]}% (threshold: 40%)"
124
- }
125
- end
126
-
127
- engine.add_rule(temp_alert)
128
- engine.add_rule(cpu_warning)
129
-
130
- puts "\nAdding facts (stored in Redis)..."
131
- sensor1 = engine.add_fact(:sensor, { location: "trading_floor", type: "temperature", value: 22 })
132
- sensor2 = engine.add_fact(:sensor, { location: "data_center", type: "cpu_usage", value: 45 })
133
-
134
- puts "Facts added:"
135
- puts " Sensor 1: #{sensor1.uuid}"
136
- puts " Sensor 2: #{sensor2.uuid}"
137
-
138
- puts "\nRunning inference engine..."
139
- engine.run
140
-
141
- puts "\nUpdating sensor value (audit logged to SQLite)..."
142
- sensor1[:value] = 28
143
-
144
- puts "\nRunning inference again after update..."
145
- engine.run
146
-
147
- puts "\nFact History from SQLite Audit Log:"
148
- history = engine.blackboard.get_history(limit: 5)
149
- history.each do |entry|
150
- puts " [#{entry[:timestamp].strftime('%H:%M:%S')}] #{entry[:action]}: #{entry[:fact_type]}(#{entry[:attributes]})"
151
- end
152
-
153
- puts "\nHybrid Store Benefits:"
154
- puts " ✓ Facts in Redis (fast reads/writes)"
155
- puts " ✓ Messages in Redis (real-time messaging)"
156
- puts " ✓ Audit trail in SQLite (durable, queryable)"
157
- puts " ✓ Best of both worlds for production systems"
158
-
159
- puts "\nStatistics:"
160
- stats = engine.stats
161
- stats.each do |key, value|
162
- puts " #{key.to_s.gsub('_', ' ').capitalize}: #{value}"
163
- end
164
-
165
- engine.blackboard.close
166
-
167
- rescue Redis::CannotConnectError => e
168
- puts "\n⚠️ Redis not available: #{e.message}"
169
- puts " Hybrid store requires Redis for fact storage"
170
- end
171
-
172
- puts "\n" + "=" * 70
173
- puts "Demo complete!"
174
- puts "\nComparison:"
175
- puts " SQLite Store: Durable, transactional, embedded (no server needed)"
176
- puts " Redis Store: Fast (100x), distributed, requires Redis server"
177
- puts " Hybrid Store: Fast facts + durable audit (production recommended)"
@@ -1,177 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require_relative '../lib/kbs/blackboard'
4
-
5
- puts "Redis-Backed High-Frequency Trading System"
6
- puts "=" * 70
7
-
8
- # Demo 1: Pure Redis Store (fast, in-memory)
9
- puts "\n=== Pure Redis Store Demo ==="
10
- puts "Fast in-memory fact storage with Redis"
11
-
12
- begin
13
- redis_store = KBS::Blackboard::Persistence::RedisStore.new(
14
- url: 'redis://localhost:6379/1' # Use DB 1 for demo
15
- )
16
-
17
- # Clear previous demo data
18
- redis_store.redis.flushdb
19
- puts "(Cleared previous Redis data)"
20
-
21
- engine = KBS::Blackboard::Engine.new(store: redis_store)
22
-
23
- # Add trading rules (raw API since Blackboard::Engine doesn't use DSL)
24
- spread_rule = KBS::Rule.new('tight_spread_opportunity') do |r|
25
- r.conditions << KBS::Condition.new(:market_price, { symbol: 'AAPL' })
26
- r.conditions << KBS::Condition.new(:order, { symbol: 'AAPL', type: 'BUY' })
27
- r.action = ->(facts) {
28
- price = facts.find { |f| f.type == :market_price }
29
- order = facts.find { |f| f.type == :order }
30
- spread = 0.02 # Tight spread
31
- puts "\n💹 TRADING SIGNAL: Tight spread opportunity for #{price[:symbol]}"
32
- puts " Price: $#{price[:price]}, Spread: $#{spread}"
33
- puts " Order: #{order[:type]} #{order[:quantity]} @ $#{order[:limit]}"
34
- }
35
- end
36
-
37
- high_volume_rule = KBS::Rule.new('high_volume_alert') do |r|
38
- r.conditions << KBS::Condition.new(:market_price, { volume: ->(v) { v > 800 } })
39
- r.action = ->(facts) {
40
- price = facts.first
41
- puts "\n📊 HIGH VOLUME: #{price[:symbol]} trading at #{price[:volume]} shares"
42
- }
43
- end
44
-
45
- engine.add_rule(spread_rule)
46
- engine.add_rule(high_volume_rule)
47
-
48
- puts "\nAdding high-frequency market data..."
49
- price1 = engine.add_fact(:market_price, { symbol: "AAPL", price: 150.25, volume: 1000 })
50
- price2 = engine.add_fact(:market_price, { symbol: "GOOGL", price: 2800.50, volume: 500 })
51
- order = engine.add_fact(:order, { symbol: "AAPL", type: "BUY", quantity: 100, limit: 150.00 })
52
-
53
- puts "Facts added with UUIDs:"
54
- puts " AAPL Price: #{price1.uuid}"
55
- puts " GOOGL Price: #{price2.uuid}"
56
- puts " Order: #{order.uuid}"
57
-
58
- puts "\nRunning inference engine..."
59
- engine.run
60
-
61
- puts "\nPosting trading messages..."
62
- engine.post_message("MarketDataFeed", "prices", { symbol: "AAPL", bid: 150.24, ask: 150.26 }, priority: 10)
63
- engine.post_message("OrderManager", "orders", { action: "fill", order_id: order.uuid }, priority: 5)
64
-
65
- puts "\nConsuming highest priority message..."
66
- message = engine.consume_message("prices", "TradingStrategy")
67
- puts " Received: #{message[:content]}" if message
68
-
69
- puts "\nQuerying market prices..."
70
- prices = engine.blackboard.get_facts(:market_price)
71
- puts " Found #{prices.size} price(s):"
72
- prices.each { |p| puts " - #{p}" }
73
-
74
- puts "\nRedis Statistics:"
75
- stats = engine.stats
76
- stats.each do |key, value|
77
- puts " #{key.to_s.gsub('_', ' ').capitalize}: #{value}"
78
- end
79
-
80
- engine.blackboard.close
81
-
82
- rescue Redis::CannotConnectError => e
83
- puts "\n⚠️ Redis not available: #{e.message}"
84
- puts " Please start Redis: redis-server"
85
- puts " Or install Redis: brew install redis (macOS)"
86
- end
87
-
88
- # Demo 2: Hybrid Store (Redis + SQLite)
89
- puts "\n\n=== Hybrid Store Demo ==="
90
- puts "Redis for fast fact access + SQLite for durable audit trail"
91
-
92
- begin
93
- hybrid_store = KBS::Blackboard::Persistence::HybridStore.new(
94
- redis_url: 'redis://localhost:6379/2', # Use DB 2 for demo
95
- db_path: ':memory:' # In-memory SQLite for demo
96
- )
97
-
98
- # Clear previous demo data from Redis
99
- hybrid_store.redis_store.redis.flushdb
100
- puts "(Cleared previous Redis data)"
101
-
102
- engine = KBS::Blackboard::Engine.new(store: hybrid_store)
103
-
104
- # Add monitoring rules (raw API since Blackboard::Engine doesn't use DSL)
105
- temp_alert = KBS::Rule.new('temperature_alert') do |r|
106
- r.conditions << KBS::Condition.new(:sensor, {
107
- type: 'temperature',
108
- value: ->(v) { v > 25 }
109
- })
110
- r.action = ->(facts) {
111
- sensor = facts.first
112
- puts "\n🌡️ TEMPERATURE ALERT: #{sensor[:location]} at #{sensor[:value]}°C (threshold: 25°C)"
113
- }
114
- end
115
-
116
- cpu_warning = KBS::Rule.new('cpu_warning') do |r|
117
- r.conditions << KBS::Condition.new(:sensor, {
118
- type: 'cpu_usage',
119
- value: ->(v) { v > 40 }
120
- })
121
- r.action = ->(facts) {
122
- sensor = facts.first
123
- puts "\n⚙️ CPU WARNING: #{sensor[:location]} at #{sensor[:value]}% (threshold: 40%)"
124
- }
125
- end
126
-
127
- engine.add_rule(temp_alert)
128
- engine.add_rule(cpu_warning)
129
-
130
- puts "\nAdding facts (stored in Redis)..."
131
- sensor1 = engine.add_fact(:sensor, { location: "trading_floor", type: "temperature", value: 22 })
132
- sensor2 = engine.add_fact(:sensor, { location: "data_center", type: "cpu_usage", value: 45 })
133
-
134
- puts "Facts added:"
135
- puts " Sensor 1: #{sensor1.uuid}"
136
- puts " Sensor 2: #{sensor2.uuid}"
137
-
138
- puts "\nRunning inference engine..."
139
- engine.run
140
-
141
- puts "\nUpdating sensor value (audit logged to SQLite)..."
142
- sensor1[:value] = 28
143
-
144
- puts "\nRunning inference again after update..."
145
- engine.run
146
-
147
- puts "\nFact History from SQLite Audit Log:"
148
- history = engine.blackboard.get_history(limit: 5)
149
- history.each do |entry|
150
- puts " [#{entry[:timestamp].strftime('%H:%M:%S')}] #{entry[:action]}: #{entry[:fact_type]}(#{entry[:attributes]})"
151
- end
152
-
153
- puts "\nHybrid Store Benefits:"
154
- puts " ✓ Facts in Redis (fast reads/writes)"
155
- puts " ✓ Messages in Redis (real-time messaging)"
156
- puts " ✓ Audit trail in SQLite (durable, queryable)"
157
- puts " ✓ Best of both worlds for production systems"
158
-
159
- puts "\nStatistics:"
160
- stats = engine.stats
161
- stats.each do |key, value|
162
- puts " #{key.to_s.gsub('_', ' ').capitalize}: #{value}"
163
- end
164
-
165
- engine.blackboard.close
166
-
167
- rescue Redis::CannotConnectError => e
168
- puts "\n⚠️ Redis not available: #{e.message}"
169
- puts " Hybrid store requires Redis for fact storage"
170
- end
171
-
172
- puts "\n" + "=" * 70
173
- puts "Demo complete!"
174
- puts "\nComparison:"
175
- puts " SQLite Store: Durable, transactional, embedded (no server needed)"
176
- puts " Redis Store: Fast (100x), distributed, requires Redis server"
177
- puts " Hybrid Store: Fast facts + durable audit (production recommended)"
@@ -1,123 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require_relative '../lib/kbs'
4
-
5
- puts "Rule Source Introspection Demo"
6
- puts "=" * 60
7
- puts
8
- puts "KBS can show the source of any rule — whether it was defined"
9
- puts "in a file (exact source) or built dynamically at runtime"
10
- puts "(reconstructed from bytecode via KBS::Decompiler)."
11
- puts
12
-
13
- # ── Part 1: File-defined rules ───────────────────────────────
14
-
15
- puts "PART 1: File-Defined Rules"
16
- puts "-" * 60
17
- puts
18
-
19
- kb = KBS.knowledge_base do
20
- rule "dead_battery" do
21
- on :symptom, problem: "won't start"
22
- on :symptom, problem: "no lights"
23
-
24
- perform do |facts, bindings|
25
- puts "DIAGNOSIS: Dead battery"
26
- puts "RECOMMENDATION: Replace or jump-start the battery"
27
- end
28
- end
29
-
30
- rule "overheating" do
31
- on :symptom, problem: "high temperature"
32
- on :symptom, problem: "steam from hood"
33
- without :symptom, problem: "coolant leak"
34
-
35
- perform do |facts, bindings|
36
- puts "DIAGNOSIS: Engine overheating (no coolant leak)"
37
- puts "RECOMMENDATION: Check radiator and cooling system"
38
- end
39
- end
40
- end
41
-
42
- kb.rules.each_key do |name|
43
- puts "Source for '#{name}':"
44
- puts
45
- kb.print_rule_source(name)
46
- puts
47
- end
48
-
49
- # ── Part 2: Dynamically-created rules ────────────────────────
50
-
51
- puts
52
- puts "PART 2: Dynamically-Created Rules"
53
- puts "-" * 60
54
- puts
55
- puts "These rules have no source file — KBS reconstructs them"
56
- puts "from their internal state using YARV bytecode decompilation."
57
- puts
58
-
59
- # Simulate what an AI agent framework might do: build rules at
60
- # runtime from configuration data, user input, or LLM output.
61
-
62
- dynamic_kb = KBS::DSL::KnowledgeBase.new
63
-
64
- # Rule with lambda condition helpers
65
- builder = KBS::DSL::RuleBuilder.new("high_temp_alert")
66
- builder.desc "Fire when temperature exceeds safe threshold"
67
- builder.priority 5
68
- builder.on :sensor, location: "server_room", temp: ->(v) { v > 85 }
69
- builder.without :alert, type: :cooling_active
70
- builder.perform { |facts| puts "ALERT: Server room temperature critical!" }
71
-
72
- rule = builder.build
73
- dynamic_kb.instance_variable_get(:@rule_builders)["high_temp_alert"] = builder
74
- dynamic_kb.instance_variable_get(:@rules)["high_temp_alert"] = rule
75
- dynamic_kb.engine.add_rule(rule)
76
-
77
- # Rule with multiple proc-based conditions
78
- builder2 = KBS::DSL::RuleBuilder.new("buy_signal")
79
- builder2.on :stock, price: ->(v) { v < 150 }, volume: ->(v) { v > 1_000_000 }
80
- builder2.without :position, status: :open
81
- builder2.perform { |facts| puts "BUY signal triggered" }
82
-
83
- rule2 = builder2.build
84
- dynamic_kb.instance_variable_get(:@rule_builders)["buy_signal"] = builder2
85
- dynamic_kb.instance_variable_get(:@rules)["buy_signal"] = rule2
86
- dynamic_kb.engine.add_rule(rule2)
87
-
88
- ["high_temp_alert", "buy_signal"].each do |name|
89
- puts "Reconstructed source for '#{name}':"
90
- puts
91
- dynamic_kb.print_rule_source(name)
92
- puts
93
- end
94
-
95
- # ── Part 3: Decompiler standalone ─────────────────────────────
96
-
97
- puts
98
- puts "PART 3: KBS::Decompiler Standalone"
99
- puts "-" * 60
100
- puts
101
- puts "The decompiler works on any Proc or Lambda:"
102
- puts
103
-
104
- examples = {
105
- "lambda" => ->(x) { x * 2 + 1 },
106
- "proc" => proc { |a, b| a > b },
107
- "complex" => ->(items) { items.select { |x| x > 0 }.map { |x| x * 2 } },
108
- }
109
-
110
- examples.each do |label, pr|
111
- puts " #{label}:"
112
- puts " decompile => #{KBS::Decompiler.new(pr).decompile}"
113
- puts " decompile_block => #{KBS::Decompiler.new(pr).decompile_block}"
114
- puts
115
- end
116
-
117
- # ── Part 4: Unknown rule ──────────────────────────────────────
118
-
119
- puts "PART 4: Unknown Rule"
120
- puts "-" * 60
121
- puts
122
- kb.print_rule_source("nonexistent")
123
- puts " rule_source returns: #{kb.rule_source('nonexistent').inspect}"
data/examples/run_all.rb DELETED
@@ -1,50 +0,0 @@
1
- #!/usr/bin/env ruby
2
- # frozen_string_literal: true
3
-
4
- # Run all example files in the examples directory
5
-
6
- require 'pathname'
7
-
8
- # Get the directory where this script is located
9
- examples_dir = Pathname.new(__FILE__).dirname
10
-
11
- # Find all Ruby files except this one
12
- example_files = Dir.glob(examples_dir.join('*.rb'))
13
- .reject { |f| File.basename(f).start_with? 'run_all' }
14
- .reject { |f| File.basename(f).end_with? '_dsl.rb' }
15
- .sort
16
-
17
- puts
18
- puts "Running #{example_files.size} examples from #{examples_dir}"
19
- puts
20
- puts
21
-
22
- example_files.each_with_index do |file, index|
23
- filename = File.basename(file)
24
- filename_size = filename.size + 6
25
-
26
- STDERR.puts "Running example #{index + 1}/#{example_files.size}: #{filename} ..."
27
-
28
- puts
29
- puts "=" * filename_size
30
- puts "## #{filename} ##"
31
- puts "=" * filename_size
32
- puts
33
-
34
- # Run the example
35
- system("ruby", file)
36
-
37
- exit_status = $?.exitstatus
38
-
39
- if exit_status != 0
40
- puts
41
- puts "⚠️ Example #{filename} exited with status #{exit_status}"
42
- end
43
-
44
- puts
45
- end
46
-
47
- puts
48
- puts
49
- puts "Completed running all #{example_files.size} examples"
50
- puts
@@ -1,49 +0,0 @@
1
- #!/usr/bin/env ruby
2
- # frozen_string_literal: true
3
-
4
- # Run all example DSL files in the examples directory
5
-
6
- require 'pathname'
7
-
8
- # Get the directory where this script is located
9
- examples_dir = Pathname.new(__FILE__).dirname
10
-
11
- # Find all Ruby files except this one
12
- example_files = Dir.glob(examples_dir.join('*_dsl.rb'))
13
- .reject { |f| File.basename(f).start_with? 'run_all' }
14
- .sort
15
-
16
- puts
17
- puts "Running #{example_files.size} examples from #{examples_dir}"
18
- puts
19
- puts
20
-
21
- example_files.each_with_index do |file, index|
22
- filename = File.basename(file)
23
- filename_size = filename.size + 6
24
-
25
- STDERR.puts "Running example #{index + 1}/#{example_files.size}: #{filename} ..."
26
-
27
- puts
28
- puts "=" * filename_size
29
- puts "## #{filename} ##"
30
- puts "=" * filename_size
31
- puts
32
-
33
- # Run the example
34
- system("ruby", file)
35
-
36
- exit_status = $?.exitstatus
37
-
38
- if exit_status != 0
39
- puts
40
- puts "⚠️ Example #{filename} exited with status #{exit_status}"
41
- end
42
-
43
- puts
44
- end
45
-
46
- puts
47
- puts
48
- puts "Completed running all #{example_files.size} examples"
49
- puts
@@ -1,46 +0,0 @@
1
- Date,Symbol,Open,High,Low,Close,Volume
2
- 2024-08-01,AAPL,190.50,192.30,189.80,191.75,45231000
3
- 2024-08-02,AAPL,191.90,193.45,190.25,192.10,42891000
4
- 2024-08-03,AAPL,192.20,194.80,191.55,194.25,51203000
5
- 2024-08-04,AAPL,194.00,195.20,192.30,193.85,38756000
6
- 2024-08-05,AAPL,193.50,194.75,191.80,192.45,44672000
7
- 2024-08-06,AAPL,192.80,195.60,192.45,195.25,47938000
8
- 2024-08-07,AAPL,195.50,197.80,194.90,197.35,52847000
9
- 2024-08-08,AAPL,197.20,198.45,195.75,196.80,46291000
10
- 2024-08-09,AAPL,196.50,197.90,194.80,195.60,41859000
11
- 2024-08-10,AAPL,195.80,198.20,195.40,197.85,49562000
12
- 2024-08-11,AAPL,198.00,200.15,197.25,199.90,55743000
13
- 2024-08-12,AAPL,199.75,201.40,198.60,200.85,48392000
14
- 2024-08-13,AAPL,200.90,202.75,199.85,202.30,53681000
15
- 2024-08-14,AAPL,202.50,204.20,201.80,203.45,47256000
16
- 2024-08-15,AAPL,203.20,205.80,202.90,205.15,51847000
17
- 2024-08-01,GOOGL,160.20,162.50,159.80,161.90,28453000
18
- 2024-08-02,GOOGL,162.10,163.75,160.95,162.85,26781000
19
- 2024-08-03,GOOGL,162.90,165.40,162.20,164.75,31294000
20
- 2024-08-04,GOOGL,164.50,166.80,163.85,165.90,29102000
21
- 2024-08-05,GOOGL,165.70,167.20,164.50,166.45,27638000
22
- 2024-08-06,GOOGL,166.80,169.30,166.20,168.75,33572000
23
- 2024-08-07,GOOGL,168.90,171.45,168.30,170.90,35847000
24
- 2024-08-08,GOOGL,170.75,172.60,169.85,171.25,32194000
25
- 2024-08-09,GOOGL,171.50,173.20,170.40,172.80,30685000
26
- 2024-08-10,GOOGL,172.60,174.95,172.10,174.30,34729000
27
- 2024-08-11,GOOGL,174.50,176.80,173.95,176.20,37591000
28
- 2024-08-12,GOOGL,176.40,178.20,175.80,177.65,33847000
29
- 2024-08-13,GOOGL,177.80,180.15,177.25,179.45,36293000
30
- 2024-08-14,GOOGL,179.60,181.90,178.95,180.75,34562000
31
- 2024-08-15,GOOGL,180.90,183.40,180.30,182.85,38174000
32
- 2024-08-01,TSLA,235.80,240.20,234.50,238.90,78392000
33
- 2024-08-02,TSLA,239.20,242.75,237.80,241.50,82451000
34
- 2024-08-03,TSLA,241.80,245.60,240.90,244.20,89637000
35
- 2024-08-04,TSLA,244.50,247.30,242.80,245.75,75284000
36
- 2024-08-05,TSLA,245.90,248.40,243.20,246.85,71956000
37
- 2024-08-06,TSLA,247.20,251.80,246.50,250.30,86742000
38
- 2024-08-07,TSLA,250.60,254.90,249.80,253.45,94587000
39
- 2024-08-08,TSLA,253.70,256.20,251.40,254.90,81639000
40
- 2024-08-09,TSLA,254.50,257.80,252.90,255.60,78294000
41
- 2024-08-10,TSLA,255.90,259.40,254.70,258.75,85731000
42
- 2024-08-11,TSLA,259.00,262.80,257.90,261.50,92846000
43
- 2024-08-12,TSLA,261.80,264.50,260.20,263.25,87359000
44
- 2024-08-13,TSLA,263.50,267.90,262.80,266.40,91582000
45
- 2024-08-14,TSLA,266.70,270.20,265.50,268.85,88473000
46
- 2024-08-15,TSLA,269.10,273.60,268.40,272.30,95627000