kbs 0.2.0 → 0.3.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 +86 -0
  3. data/README.md +52 -25
  4. data/lib/kbs/agenda.rb +208 -0
  5. data/lib/kbs/alpha_memory.rb +55 -7
  6. data/lib/kbs/alpha_network.rb +83 -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 +39 -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 +104 -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 +75 -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 +27 -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 +60 -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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c07983aed0abb377d018730407ad0afb8280c228558d991d20d693adaccb6ba7
4
- data.tar.gz: 2ac8ae8057eca02225fc7756e6f4c47201488a6c58a6f3d05707f32bdf12924b
3
+ metadata.gz: 4b6c4a01ce43cb0e03e62c3a2c3408eee1ea1926be20e3153174323a7cf1df5c
4
+ data.tar.gz: fb3f9f2ef51558bf292397a6c27fd53772456f46298b637e0908d502cfb01e2b
5
5
  SHA512:
6
- metadata.gz: e0cf306fc89d5d31a0887d753c975e6f6a875aa38216d846c0ba15110dd9d05a7f6d549bfd68a96383d094ca26fd469ba23775582fe28ef60e7c4c06d674260e
7
- data.tar.gz: c6b9bd27687f2d220f0167b111057b76e2a3d70d9cef3ae9b112034951d926bd4180f2e3d1c035ce3228064499974ec5e66db80e8e88293e6192fcf9a143f5a5
6
+ metadata.gz: 862649575330472c4466b8159e7788b50f6ee2a3aaac4e7210ed91c4e437bf7715749646b9e48d7b6056ad38b4fed37a20177645be8e2e7b8c14c9b941d435b5
7
+ data.tar.gz: 4dad7e5d1333bae4c1c9c9bcb38e984dc2f08d23b19b44994de620bb09a9430859c65c0202709f38e84768430a60b0d5fde1d41b515266b64ff2c328ce1e293f
data/CHANGELOG.md CHANGED
@@ -1,5 +1,91 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.3.0] - 2026-11-20
4
+
5
+ The engine now works like CLIPS: an agenda with conflict resolution, truth maintenance, `exists`, `modify`, and joins on shared `?variables`. Matching and retraction use indexes instead of scans.
6
+
7
+ ### Breaking changes
8
+ - Requires Ruby 4.0 or later (was 3.2).
9
+ - A `?variable` used in more than one condition now joins them: the facts must share the value. It used to match every combination. A `without` condition now blocks only on facts that agree with the variables bound before it.
10
+ - `run` fires until no matches remain, so a fact asserted by one action can fire any rule in the same `run`, in priority order. `run` returns the number of rules fired. Rules that keep re-matching need `run(limit)` or `halt`.
11
+ - `priority` now sets firing order on both engines; equal priorities keep definition order (#35).
12
+ - The DSL keyword `exists` now means "at least one such fact" and matches once; it used to be an alias for `on`.
13
+ - `WorkingMemory#facts`, `AlphaMemory#items`, `BetaMemory#tokens` and `ProductionNode#tokens` return copies; change the memories through their methods (`add_item`, `remove_token`, `clear`, …). `Token#children` is a frozen Set changed through `add_child` / `remove_child`.
14
+ - `RedisStore#query_facts` and `HybridStore#query_facts` raise `NotImplementedError` instead of returning every fact (#16).
15
+ - Shared nodes mean shared tokens, so whether a rule fired is now `ProductionNode#fired?(token)`; `Token#fired?` no longer prevents a second firing. `Activation#to_s` separates facts with `; ` and shows `*` for a `without` or `exists` condition.
16
+ - The gem ships only `lib/`, `README.md`, `CHANGELOG.md` and `LICENSE.txt` (#31). The Rakefile is gone; development tasks run through [asgard](https://github.com/MadBomber/asgard) (`.loki`).
17
+
18
+ ### Added
19
+ - **Agenda** (`engine.agenda`) holding pending matches, with conflict resolution `strategy:` `:definition` (default), `:depth` or `:breadth`; `run(limit)` and `halt`.
20
+ - **Truth maintenance**: conditions in a `logical do … end` block support the facts the action asserts, which are retracted when the support goes away. `logically_supported?`, `dependencies`, `dependents`.
21
+ - **`modify(fact, changes)`** on both engines and `KnowledgeBase`: updates a fact and re-matches it, keeping its identity (and uuid / `UPDATE` audit entry on the blackboard).
22
+ - **`fact_duplication: false`**: `add_fact` returns the existing equal fact instead of adding another; `duplicate_of` finds it.
23
+ - **`exists` conditions** (`KBS::ExistsNode`).
24
+ - **`KBS::MatchInProgressError`** when a pattern predicate changes working memory during a match.
25
+ - Bare `fact`, `assert`, `retract`, `modify`, `query` and `halt` work inside a DSL `perform` block; condition keywords after the rule is built raise `KBS::RuleBuiltError`.
26
+ - Block-form conditions accept bare names and comparisons: `on(:t) { location loc; value > 80 }`.
27
+ - `KnowledgeBase#query` accepts condition helpers such as `greater_than(80)`.
28
+ - `Engine#facts`, `Engine#close`, `KnowledgeBase#close`, `KBS.knowledge_base(engine:)` (#10, #64).
29
+ - `Fact#to_s` and `Rule#to_s` print DSL source (#3).
30
+ - **Introspection, as in CLIPS**: `watch` / `unwatch` (`:facts`, `:activations`, `:rules`) with `trace_output=`; `matches(rule_name)` shows the facts and partial matches per condition; `join_activity`, `reset_join_activity`, `network_stats` and `beta_nodes` measure the network. Also on `KnowledgeBase`.
31
+ - Benchmarks: `benchmarks/rete_scaling.rb` and `benchmarks/regex_baseline.rb` (#4).
32
+
33
+ ### Performance
34
+ With 2,000 facts or rules:
35
+ - Asserting finds alpha memories by type and constant: 1 s → 6 ms.
36
+ - Rules that start with the same conditions share those join, negation and exists nodes and their partial matches: 50 such rules over 2000 orders and payments, 517 ms → 37 ms.
37
+ - Shared-variable joins use hash indexes: 970 ms → 11 ms.
38
+ - Retracting follows recorded links instead of searching: 470 ms → 4 ms; removing negation blockers: 407 ms → 8 ms. Asserting costs about 20% more for the bookkeeping.
39
+
40
+ ### Fixed
41
+ - **Matching**
42
+ - Rules fire once per match whatever order facts arrive in (#41).
43
+ - Adding a rule late no longer re-fires earlier rules (#34).
44
+ - A rule that starts with `without` fires when nothing blocks it (#11).
45
+ - Bindings are correct after a leading `without`.
46
+ - Helpers and variables work on an attribute named `type` (#65).
47
+ - Helpers fail to match, instead of raising, on values of the wrong type (#67).
48
+ - **DSL**
49
+ - Condition helpers work in the block form of `on` (#40).
50
+ - `priority:` keyword on `rule` / `defrule` (#29).
51
+ - Zero-argument lambda actions (#14).
52
+ - `print_rules` shows DSL conditions (#58).
53
+ - **Rule source and decompiler**: literals, `!=`, `&&` / `||`, ternaries and Ruby 4.1 strings print correctly; undecompilable values no longer raise (#33, #36, #43, #50, #52).
54
+ - **Blackboard**
55
+ - `remove_fact` retracts from the network and returns the fact (#42).
56
+ - A rolled-back transaction withdraws the facts it added.
57
+ - `clear_session` works with a store passed in (#51).
58
+ - `fact_duplication: false` covers facts already stored.
59
+ - Symbol rule names and message topics work on SQLite.
60
+ - `register_knowledge_source` without a description works on Redis/Hybrid stores.
61
+ - `HybridStore#stats[:audit_records]` counts audit rows.
62
+ - The `Store` base class defines `session_id` and `register_knowledge_source`.
63
+ - `require 'kbs/blackboard'` works without the redis gem.
64
+ - **Messages and audit**
65
+ - String message content round-trips (#63).
66
+ - SQLite timestamps are read as UTC (#62).
67
+ - Two consumers can no longer receive the same message (#60).
68
+ - **Docs and examples**: every doc and snippet was checked against the code and corrected; the README and example DSL rules were fixed (#59, #66).
69
+
70
+ ## [0.2.1] - 2026-02-26
71
+
72
+ ### Added
73
+ - **Rule Source Introspection**: New `rule_source` and `print_rule_source` methods on `KnowledgeBase` to retrieve and display the DSL source code for any rule by name
74
+ - **Rule Decompiler**: `KBS::Decompiler` can reconstruct source for dynamically-created rules from Proc and Lambda objects
75
+ - **Working Memory Reset**: `KnowledgeBase#reset` now clears working memory while preserving the compiled rule network, enabling reuse with different initial facts
76
+ - **Rule Source Introspection Demo**: New `examples/rule_source_demo.rb` showcasing both file-based and dynamic rule source retrieval
77
+
78
+ ### Changed
79
+ - **README rewritten to use DSL API**: Removed references to `KBS::ReteEngine` and `KBS::Rule`; all examples now use the DSL-based `KnowledgeBase` API
80
+ - **Dependencies bumped**: minitest updated to ~> 5.26
81
+
82
+ ### Removed
83
+ - Deleted obsolete `expert-systems` example
84
+ - Deleted `DOCUMENTATION_STATUS.md`
85
+
86
+ ### Fixed
87
+ - Updated `perform` method signatures in API documentation
88
+
3
89
  ## [0.1.0] - 2025-10-09
4
90
 
5
91
  ### Added
data/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
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
- [![Ruby](https://img.shields.io/badge/ruby-%3E%3D%203.2.0-red.svg)](https://www.ruby-lang.org/)
7
+ [![Ruby](https://img.shields.io/badge/ruby-%3E%3D%204.0-red.svg)](https://www.ruby-lang.org/)
8
8
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
9
9
 
10
10
  See the [full documentation website](https://madbomber.github.io/kbs/).
@@ -16,13 +16,18 @@ See the [full documentation website](https://madbomber.github.io/kbs/).
16
16
  - **Incremental Updates**: Efficient fact addition/removal without full network recomputation
17
17
  - **Negation Support**: Built-in handling of NOT conditions and absence patterns
18
18
  - **Memory Optimization**: Nodes automatically unlink when empty to reduce computation
19
- - **Pattern Sharing**: Common sub-patterns shared between rules for maximum efficiency
19
+ - **Pattern Sharing**: Rules with the same pattern share one alpha memory
20
+ - **Indexed Matching**: Alpha memories found by fact type and constant, joins on shared `?variables` hash-indexed, and retraction without scanning
21
+ - **Agenda**: Runs to quiescence, ordered by priority then a conflict resolution strategy (`:definition`, `:depth`, `:breadth`); `run(limit)` and `halt`
22
+ - **Truth Maintenance**: Facts asserted under `logical` conditions are retracted when those conditions stop matching
23
+ - **Fact Lifecycle**: `modify` re-matches a changed fact; `fact_duplication: false` rejects duplicate facts
20
24
 
21
25
  ### Declarative DSL
22
26
  - **Readable Syntax**: Write rules in natural, expressive Ruby syntax
23
- - **Condition Helpers**: `greater_than`, `less_than`, `range`, `one_of`, `matches` for intuitive pattern matching
27
+ - **Condition Helpers**: `greater_than`, `less_than`, `range`, `one_of`, `satisfies` and more (see [DSL Helpers](#dsl-helpers))
24
28
  - **Rule Metadata**: Descriptions, priorities, and documentation built-in
25
29
  - **Negative Patterns**: `without` keyword for absence testing
30
+ - **Existence Tests**: `exists` matches once when at least one fact fits
26
31
 
27
32
  ### Blackboard Architecture
28
33
  - **Multi-Agent Coordination**: Knowledge sources collaborate via shared blackboard
@@ -38,12 +43,12 @@ See the [full documentation website](https://madbomber.github.io/kbs/).
38
43
  - **Query Interface**: Powerful fact retrieval with pattern matching and SQL queries
39
44
 
40
45
  ### Concurrent Execution
41
- - **Auto-Inference Mode**: Background thread continuously runs inference as facts change
42
- - **Thread-Safe**: Concurrent fact assertion and rule firing
46
+ - **Auto-Inference Patterns**: `examples/concurrent_inference_demo.rb` subclasses `KBS::Engine` to run inference reactively or in a background thread
47
+ - **Your Own Locking**: The engine has no locks of its own; those examples guard it with a `Mutex`
43
48
  - **Real-Time Processing**: Perfect for monitoring systems and event-driven architectures
44
49
 
45
50
  ### AI Integration
46
- - **LLM Integration**: Native support for Ollama, OpenAI via RubyLLM gem
51
+ - **LLM Integration**: Call Ollama, OpenAI and others from rule actions with the RubyLLM gem (not a kbs dependency; install it yourself)
47
52
  - **Hybrid Reasoning**: Combine symbolic rules with neural AI for enhanced decision-making
48
53
  - **Sentiment Analysis**: AI-powered news and text analysis
49
54
  - **Strategy Generation**: LLMs create trading strategies based on market conditions
@@ -103,8 +108,7 @@ kb = KBS.knowledge_base do
103
108
  desc "Detect stock momentum breakouts"
104
109
  priority 10
105
110
 
106
- on :stock, volume: greater_than(1_000_000)
107
- on :stock, price_change_pct: greater_than(3)
111
+ on :stock, volume: greater_than(1_000_000), price_change_pct: greater_than(3)
108
112
  without :position, status: "open"
109
113
 
110
114
  perform do |facts, bindings|
@@ -196,8 +200,12 @@ puts "Received: #{message[:content]}" if message
196
200
  require 'kbs'
197
201
  require 'ruby_llm'
198
202
 
199
- # Requires Ollama with a model installed
200
- # export OLLAMA_MODEL=gpt-oss:latest
203
+ # Requires `gem install ruby_llm` and LM Studio's server (`lms server start`) with a model loaded
204
+ # LM Studio speaks the OpenAI API, so ruby_llm's :openai provider points at it
205
+ RubyLLM.configure do |config|
206
+ config.openai_api_base = ENV.fetch("LMS_API_BASE", "http://localhost:1234/v1")
207
+ config.openai_api_key = ENV.fetch("LMS_API_KEY", "lm-studio") # LM Studio ignores it; ruby_llm needs one set
208
+ end
201
209
 
202
210
  kb = KBS.knowledge_base do
203
211
  rule "ai_sentiment_analysis" do
@@ -206,7 +214,11 @@ kb = KBS.knowledge_base do
206
214
  perform do |facts|
207
215
  news = facts.first
208
216
  # AI-powered sentiment analysis
209
- client = RubyLLM::Chat.new(provider: :ollama, model: 'gpt-oss:latest')
217
+ client = RubyLLM::Chat.new(
218
+ provider: :openai,
219
+ model: ENV.fetch("LMS_MODEL", "openai/gpt-oss-20b"),
220
+ assume_model_exists: true # local model ids aren't in ruby_llm's registry
221
+ )
210
222
  response = client.ask("Analyze sentiment: #{news[:headline]}")
211
223
 
212
224
  puts "🤖 AI SENTIMENT ANALYSIS: #{news[:symbol]}"
@@ -232,15 +244,15 @@ end
232
244
 
233
245
  ## 📚 Examples
234
246
 
235
- The `examples/` directory contains 13 comprehensive examples demonstrating all features:
247
+ The `examples/` directory contains 13 comprehensive examples demonstrating all features. Each one except `iot_demo_using_dsl.rb` also has a DSL version (`*_dsl.rb`), and `rule_source_demo.rb` shows rule source introspection:
236
248
 
237
249
  ### Basic Examples
238
250
  - **car_diagnostic.rb** - Simple expert system for car diagnostics
239
251
  - **working_demo.rb** - Stock trading signal generator
252
+ - **trading_demo.rb** - Multiple trading strategies
240
253
 
241
254
  ### DSL Examples
242
255
  - **iot_demo_using_dsl.rb** - IoT sensor monitoring with declarative DSL
243
- - **trading_demo.rb** - Multiple trading strategies
244
256
 
245
257
  ### Advanced Trading
246
258
  - **advanced_example.rb** - Golden cross detection and technical analysis
@@ -336,46 +348,61 @@ Facts → Alpha Network → Beta Network → Production Nodes
336
348
  Run the comprehensive test suite:
337
349
 
338
350
  ```bash
339
- rake test
351
+ asgard test_check
352
+ ```
353
+
354
+ Without [asgard](https://github.com/MadBomber/asgard) installed, run the same command it does:
355
+
356
+ ```bash
357
+ bundle exec ruby -Ilib:test -e 'Dir["test/**/test_*.rb"].each { |f| require File.expand_path(f) }'
340
358
  ```
341
359
 
342
- Individual test files:
360
+ Run a single test file (`test/test_*.rb`):
343
361
 
344
362
  ```bash
345
- ruby test/kbs_test.rb
346
- ruby test/blackboard_test.rb
347
- ruby test/dsl_test.rb
363
+ bundle exec ruby test/test_rule.rb
348
364
  ```
349
365
 
350
- **Test Coverage**: 100% with 199 tests, 447 assertions, 0 failures
366
+ SimpleCov measures coverage on every run and fails the run below the minimum set in `test/test_helper.rb` (currently 35% line coverage).
367
+
368
+ The Redis store tests are skipped unless `KBS_TEST_REDIS_URL` names a disposable Redis database. See [test/README.md](test/README.md) before setting it, because those tests flush the database.
351
369
 
352
370
  ## 📖 Documentation
353
371
 
354
372
  ### Core Classes
355
373
 
356
- - **KBS::ReteEngine** - Main inference engine
374
+ - **KBS::Engine** - Main inference engine
357
375
  - **KBS::Rule** - Rule definition
358
376
  - **KBS::Condition** - Pattern matching conditions
359
377
  - **KBS::Fact** - Working memory facts
360
378
  - **KBS::Blackboard::Engine** - Blackboard coordination
361
- - **KBS::Blackboard::Persistence::SQLiteStore** - SQLite backend
379
+ - **KBS::Blackboard::Persistence::SqliteStore** - SQLite backend
362
380
  - **KBS::Blackboard::Persistence::RedisStore** - Redis backend
363
381
  - **KBS::Blackboard::Persistence::HybridStore** - Hybrid storage
364
382
 
365
383
  ### DSL Helpers
366
384
 
385
+ Use these as attribute values in the hash form of `on`, for example `on :reading, value: greater_than(100)`, and in `kb.query` patterns. The block form of `on` has its own operators; see [Block-Style Patterns](docs/guides/dsl.md#block-style-patterns).
386
+
367
387
  - `greater_than(n)` - Match values > n
368
388
  - `less_than(n)` - Match values < n
369
- - `range(min, max)` - Match values between min and max
389
+ - `equals(value)` - Match values equal to value
390
+ - `not_equal(value)` - Match values not equal to value
391
+ - `range(min, max)`, `between(min, max)` or `range(a_range)` - Match values from min to max inclusive, or values in the Range
370
392
  - `one_of(*values)` - Match any of the values
371
- - `matches(regex)` - Match regex pattern
393
+ - `any(*values)` - Same as `one_of`; with no arguments, match anything
394
+ - `satisfies { |v| ... }` - Match values for which the block returns true
395
+
396
+ For a regex in the hash form, use `satisfies { |v| regex.match?(v.to_s) }`. In that position `matches` is another name for `on`, not a helper.
397
+
398
+ See the [DSL guide](docs/guides/dsl.md#pattern-helpers) for examples.
372
399
 
373
400
  ## 🔧 Requirements
374
401
 
375
- - Ruby >= 3.2.0
402
+ - Ruby >= 4.0
376
403
  - SQLite3 (bundled with most systems)
377
404
  - Redis (optional, for Redis storage)
378
- - Ollama (optional, for AI integration)
405
+ - RubyLLM plus Ollama or LM Studio (optional, for AI integration)
379
406
 
380
407
  ## 🤝 Contributing
381
408
 
data/lib/kbs/agenda.rb ADDED
@@ -0,0 +1,208 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # A rule matched by a token, waiting on the agenda to fire.
5
+ class Activation
6
+ attr_reader :node, :token, :salience, :rule_order, :timetag
7
+ attr_accessor :sort_key
8
+
9
+ def initialize(node, token, rule_order:, timetag:)
10
+ @node = node
11
+ @token = token
12
+ @salience = node.rule.priority
13
+ @rule_order = rule_order
14
+ @timetag = timetag
15
+ @cancelled = false
16
+ end
17
+
18
+ def rule
19
+ @node.rule
20
+ end
21
+
22
+ def cancel!
23
+ @cancelled = true
24
+ end
25
+
26
+ def cancelled?
27
+ @cancelled
28
+ end
29
+
30
+ # The rule's name and one entry per condition, separated by "; ": the
31
+ # matched fact, or * for a negated or exists condition.
32
+ def description
33
+ "#{rule.name}: #{@token.slots.map { |fact| fact ? fact.to_s : '*' }.join('; ')}"
34
+ end
35
+
36
+ # Cancels the activation unless it already is.
37
+ #
38
+ # @return [Boolean] whether this call cancelled it
39
+ def withdraw
40
+ return false if @cancelled
41
+
42
+ @cancelled = true
43
+ end
44
+
45
+ # Where the activation sorts on an agenda that uses `strategy`:
46
+ # lowest first.
47
+ def key_for(strategy)
48
+ priority = -@salience
49
+ case strategy
50
+ when :depth then [priority, -@timetag, 0]
51
+ when :breadth then [priority, @timetag, 0]
52
+ else [priority, @rule_order, @timetag]
53
+ end
54
+ end
55
+
56
+ def to_s
57
+ "#{@salience} #{description}"
58
+ end
59
+ end
60
+
61
+ # The conflict set: every activation that has not fired yet, ordered
62
+ # by rule priority (salience) and then by the conflict resolution
63
+ # strategy.
64
+ #
65
+ # :definition rules in the order they were added, each rule's
66
+ # activations oldest first (the default)
67
+ # :depth newest activation first
68
+ # :breadth oldest activation first
69
+ #
70
+ # Activations sit in a binary heap. Removing one marks it cancelled and
71
+ # it is dropped when it reaches the top, so add, remove and pop are
72
+ # O(log n).
73
+ class Agenda
74
+ STRATEGIES = %i[definition depth breadth].freeze
75
+
76
+ attr_reader :strategy, :size
77
+
78
+ # An object told about each activation that is added, and each one
79
+ # removed before it fired, through activation_added(activation) and
80
+ # activation_removed(activation).
81
+ attr_accessor :listener
82
+
83
+ def initialize(strategy: :definition)
84
+ @listener = nil
85
+ validate_strategy(strategy)
86
+ @strategy = strategy
87
+ @heap = []
88
+ @size = 0
89
+ @timetag = 0
90
+ end
91
+
92
+ def strategy=(strategy)
93
+ validate_strategy(strategy)
94
+ @strategy = strategy
95
+ pending = to_a
96
+ @heap = []
97
+ pending.each { |activation| push(activation) }
98
+ end
99
+
100
+ # @return [Activation] the new activation, to pass to #remove later
101
+ def add(node, token, rule_order: 0)
102
+ activation = Activation.new(node, token, rule_order: rule_order, timetag: @timetag += 1)
103
+ push(activation)
104
+ @size += 1
105
+ @listener&.activation_added(activation)
106
+ activation
107
+ end
108
+
109
+ def remove(activation)
110
+ return unless activation&.withdraw
111
+
112
+ @size -= 1
113
+ @listener&.activation_removed(activation)
114
+ end
115
+
116
+ # Removes and returns the next activation to fire, or nil when empty.
117
+ def pop
118
+ drop_cancelled
119
+ return nil if @heap.empty?
120
+
121
+ activation = pop_top
122
+ activation.cancel!
123
+ @size -= 1
124
+ activation
125
+ end
126
+
127
+ def peek
128
+ drop_cancelled
129
+ @heap.first
130
+ end
131
+
132
+ def empty?
133
+ @size.zero?
134
+ end
135
+
136
+ def clear
137
+ @heap.each(&:cancel!)
138
+ @heap = []
139
+ @size = 0
140
+ end
141
+
142
+ # Pending activations in firing order.
143
+ def to_a
144
+ @heap.reject(&:cancelled?).sort_by(&:sort_key)
145
+ end
146
+
147
+ def sort_key_for(activation)
148
+ activation.key_for(@strategy)
149
+ end
150
+
151
+ private
152
+
153
+ def validate_strategy(strategy)
154
+ return if STRATEGIES.include?(strategy)
155
+
156
+ raise ArgumentError, "unknown strategy #{strategy.inspect}; use one of #{STRATEGIES.inspect}"
157
+ end
158
+
159
+ def drop_cancelled
160
+ pop_top while @heap.first&.cancelled?
161
+ end
162
+
163
+ def push(activation)
164
+ activation.sort_key = sort_key_for(activation)
165
+ @heap << activation
166
+ sift_up(@heap.size - 1)
167
+ end
168
+
169
+ def pop_top
170
+ top = @heap.first
171
+ last = @heap.pop
172
+ unless @heap.empty?
173
+ @heap[0] = last
174
+ sift_down(0)
175
+ end
176
+ top
177
+ end
178
+
179
+ # Whether the activation at heap position `index` sorts before the one
180
+ # at `other`.
181
+ def before?(index, other)
182
+ (@heap[index].sort_key <=> @heap[other].sort_key).negative?
183
+ end
184
+
185
+ def sift_up(index)
186
+ while index.positive?
187
+ parent = (index - 1) / 2
188
+ break unless before?(index, parent)
189
+
190
+ @heap[index], @heap[parent] = @heap[parent], @heap[index]
191
+ index = parent
192
+ end
193
+ end
194
+
195
+ def sift_down(index)
196
+ loop do
197
+ smallest = index
198
+ [(2 * index) + 1, (2 * index) + 2].each do |child|
199
+ smallest = child if child < @heap.size && before?(child, smallest)
200
+ end
201
+ break if smallest == index
202
+
203
+ @heap[index], @heap[smallest] = @heap[smallest], @heap[index]
204
+ index = smallest
205
+ end
206
+ end
207
+ end
208
+ end
@@ -1,37 +1,85 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
+ # The facts that fit one condition pattern. Shared by every rule that
5
+ # uses the pattern; tells its join nodes when a fact arrives or leaves.
4
6
  class AlphaMemory
5
- attr_accessor :items, :successors, :pattern
7
+ attr_accessor :successors, :pattern
6
8
  attr_reader :linked
7
9
 
8
10
  def initialize(pattern = {})
9
- @items = []
11
+ @items = Set.new
10
12
  @successors = []
11
13
  @pattern = pattern
12
14
  @linked = true
15
+ @indexes = {}
16
+ end
17
+
18
+ # @return [Array] the facts in this memory, in the order they arrived.
19
+ # A copy: use #add_item and #remove_item to change the memory.
20
+ def items
21
+ @items.to_a
22
+ end
23
+
24
+ def each_item(&)
25
+ @items.each(&)
26
+ end
27
+
28
+ def size
29
+ @items.size
30
+ end
31
+
32
+ def include?(fact)
33
+ @items.include?(fact)
13
34
  end
14
35
 
15
36
  def unlink!
16
37
  @linked = false
17
- @successors.each { |s| s.right_unlink! if s.respond_to?(:right_unlink!) }
38
+ @successors.each(&:right_unlink!)
18
39
  end
19
40
 
20
41
  def relink!
21
42
  @linked = true
22
- @successors.each { |s| s.right_relink! if s.respond_to?(:right_relink!) }
43
+ @successors.each(&:right_relink!)
23
44
  end
24
45
 
25
46
  def activate(fact)
26
47
  return unless @linked
27
- @items << fact
28
- @successors.each { |s| s.right_activate(fact) }
48
+ add_item(fact)
49
+ @successors.each { |successor| successor.right_activate(fact) }
29
50
  end
30
51
 
31
52
  def deactivate(fact)
32
53
  return unless @linked
54
+ remove_item(fact)
55
+ @successors.each { |successor| successor.right_deactivate(fact) }
56
+ end
57
+
58
+ # Stores a fact without telling the successors.
59
+ def add_item(fact)
60
+ @items << fact
61
+ @indexes.each_value { |index| index.add(fact) }
62
+ end
63
+
64
+ def remove_item(fact)
33
65
  @items.delete(fact)
34
- @successors.each { |s| s.right_deactivate(fact) if s.respond_to?(:right_deactivate) }
66
+ @indexes.each_value { |index| index.remove(fact) }
67
+ end
68
+
69
+ def clear
70
+ @items.clear
71
+ @indexes.each_value(&:clear)
72
+ end
73
+
74
+ # A hash index of the items on `fields`, kept up to date as facts
75
+ # come and go. Joins with the same fields share one index.
76
+ #
77
+ # @param fields [Array<Symbol>] fact attributes that make up the key
78
+ # @return [KBS::MemoryIndex]
79
+ def index_on(fields)
80
+ @indexes[fields] ||= MemoryIndex.new { |fact| MemoryIndex.fact_key(fact, fields) }.tap do |index|
81
+ @items.each { |fact| index.add(fact) }
82
+ end
35
83
  end
36
84
  end
37
85
  end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module KBS
4
+ # Finds the alpha memories a fact belongs in without testing every
5
+ # pattern.
6
+ #
7
+ # Memories are grouped by fact type. Within a type, a memory whose
8
+ # pattern tests an attribute against a constant is filed in a hash under
9
+ # that attribute and value, so a fact reaches it with one lookup on its
10
+ # own value. Only memories with no constant test are tried for every
11
+ # fact of the type. Candidates are still checked with Fact#matches?,
12
+ # which covers the rest of each pattern.
13
+ class AlphaNetwork
14
+ # @return [Hash{Hash => KBS::AlphaMemory}] every memory, by pattern
15
+ attr_reader :memories
16
+
17
+ def initialize
18
+ @memories = {}
19
+ @types = {}
20
+ @untyped = []
21
+ @sequence = {}.compare_by_identity
22
+ end
23
+
24
+ # The memory for `pattern`, made and filed if it is new. The block is
25
+ # called with a new memory, to fill it with existing facts.
26
+ def fetch(pattern)
27
+ @memories[pattern] ||= AlphaMemory.new(pattern).tap do |memory|
28
+ file(memory)
29
+ yield memory if block_given?
30
+ end
31
+ end
32
+
33
+ # @return [Array<KBS::AlphaMemory>] the memories whose pattern `fact`
34
+ # matches, in the order they were created
35
+ def memories_for(fact)
36
+ matches = candidates_for(fact).select { |memory| fact.matches?(memory.pattern) }
37
+ matches.size > 1 ? matches.sort_by { |memory| @sequence[memory] } : matches
38
+ end
39
+
40
+ # @return [Array<KBS::AlphaMemory>] the memories that have to be
41
+ # checked for `fact`
42
+ def candidates_for(fact)
43
+ type = @types[fact.type]
44
+ return @untyped.dup unless type
45
+
46
+ candidates = @untyped + type[:unselected]
47
+ type[:selectors].each do |attribute, table|
48
+ selected = table[MemoryIndex.normalize(fact.attributes[attribute])]
49
+ candidates.concat(selected) if selected
50
+ end
51
+ candidates
52
+ end
53
+
54
+ # The attribute and constant a pattern is filed under: its first
55
+ # attribute tested against a plain value. nil when it has none.
56
+ #
57
+ # @return [Array(Symbol, Object), nil]
58
+ def self.selector(pattern)
59
+ pattern.each do |attribute, value|
60
+ next if attribute == :type || value.is_a?(Proc) || JoinTestBuilder.variable?(value)
61
+
62
+ return [attribute, MemoryIndex.normalize(value)]
63
+ end
64
+ nil
65
+ end
66
+
67
+ private
68
+
69
+ def file(memory)
70
+ @sequence[memory] = @sequence.size
71
+ fact_type = memory.pattern[:type]
72
+ return @untyped << memory unless fact_type
73
+
74
+ type = @types[fact_type] ||= { unselected: [], selectors: {} }
75
+ attribute, value = self.class.selector(memory.pattern)
76
+ if attribute
77
+ ((type[:selectors][attribute] ||= {})[value] ||= []) << memory
78
+ else
79
+ type[:unselected] << memory
80
+ end
81
+ end
82
+ end
83
+ end