smart_brain 0.1.2 → 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 (79) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/MEMPAL_GUIDE.md +1074 -0
  4. data/README.en.md +206 -173
  5. data/README.md +593 -173
  6. data/config/brain.yml +69 -1
  7. data/conversation_demo.rb +438 -438
  8. data/db/migrate/002_turn_events_payload.sql +9 -0
  9. data/db/migrate/003_tiers_and_lifecycle.sql +28 -0
  10. data/db/migrate/004_kg_edges.sql +30 -0
  11. data/db/migrate/005_domains_and_memory_scopes.sql +163 -0
  12. data/docs/coding_todo.md +139 -0
  13. data/docs/context_package.md +220 -0
  14. data/docs/evidence_pack.md +190 -0
  15. data/docs/gap_vs_mempal.md +161 -0
  16. data/docs/installation.md +198 -0
  17. data/docs/mcp.md +93 -0
  18. data/docs/media_memory_schema.md +271 -0
  19. data/docs/memory_types.md +278 -0
  20. data/docs/multi_scope_memory_refactor_plan.md +483 -0
  21. data/docs/multi_scope_migration.md +65 -0
  22. data/docs/policies.md +308 -0
  23. data/docs/retrieval_plan.md +233 -0
  24. data/docs/smartbrain_design.md +299 -0
  25. data/docs/user_guide.md +547 -0
  26. data/example.rb +91 -91
  27. data/examples/01_memory_basic.rb +57 -0
  28. data/examples/02_governance.rb +63 -0
  29. data/examples/03_postgres_persistence.rb +63 -0
  30. data/examples/04_ollama_llm.rb +69 -0
  31. data/examples/05_smart_rag_integration.rb +79 -0
  32. data/examples/06_multi_scope_memory.rb +50 -0
  33. data/examples/07_media_memory.rb +53 -0
  34. data/examples/README.md +49 -0
  35. data/exe/smart_brain +168 -0
  36. data/lib/smart_brain/adapters/smart_rag/direct_client.rb +57 -5
  37. data/lib/smart_brain/adapters/smart_rag/http_client.rb +118 -5
  38. data/lib/smart_brain/adapters/smart_rag/http_transport.rb +138 -0
  39. data/lib/smart_brain/adapters/smart_rag/media_metadata_extractor.rb +255 -0
  40. data/lib/smart_brain/adapters/smart_rag/null_client.rb +44 -2
  41. data/lib/smart_brain/adapters/smart_rag/scope_filter.rb +60 -0
  42. data/lib/smart_brain/configuration.rb +60 -0
  43. data/lib/smart_brain/consolidator/working_summary.rb +80 -12
  44. data/lib/smart_brain/context_composer/composer.rb +40 -3
  45. data/lib/smart_brain/contracts/retrieval_plan.rb +10 -0
  46. data/lib/smart_brain/contracts/scope_context.rb +46 -0
  47. data/lib/smart_brain/contracts/scope_ref.rb +25 -0
  48. data/lib/smart_brain/db.rb +109 -0
  49. data/lib/smart_brain/event_store/in_memory.rb +6 -2
  50. data/lib/smart_brain/event_store/postgres.rb +199 -0
  51. data/lib/smart_brain/fusion/merger.rb +31 -2
  52. data/lib/smart_brain/governance/briefing.rb +146 -0
  53. data/lib/smart_brain/governance/fact_check.rb +110 -0
  54. data/lib/smart_brain/governance/knowledge_graph.rb +60 -0
  55. data/lib/smart_brain/governance/lifecycle.rb +225 -0
  56. data/lib/smart_brain/governance/tiers.rb +60 -0
  57. data/lib/smart_brain/memory_extractor/extractor.rb +25 -7
  58. data/lib/smart_brain/memory_store/in_memory.rb +202 -17
  59. data/lib/smart_brain/memory_store/postgres.rb +500 -0
  60. data/lib/smart_brain/model_provider/base.rb +87 -0
  61. data/lib/smart_brain/model_provider/factory.rb +49 -0
  62. data/lib/smart_brain/model_provider/ollama.rb +60 -0
  63. data/lib/smart_brain/model_provider/openai.rb +60 -0
  64. data/lib/smart_brain/model_provider/stub.rb +26 -0
  65. data/lib/smart_brain/model_provider.rb +7 -0
  66. data/lib/smart_brain/observability/tracker.rb +39 -1
  67. data/lib/smart_brain/retrievers/exact_retriever.rb +6 -0
  68. data/lib/smart_brain/retrievers/memory_retriever.rb +59 -5
  69. data/lib/smart_brain/runtime.rb +306 -16
  70. data/lib/smart_brain/scopes/conflict_resolver.rb +67 -0
  71. data/lib/smart_brain/scopes/registry.rb +133 -0
  72. data/lib/smart_brain/scopes/resolver.rb +32 -0
  73. data/lib/smart_brain/server/http_app.rb +143 -0
  74. data/lib/smart_brain/server/mcp_server.rb +385 -0
  75. data/lib/smart_brain/server/service.rb +129 -0
  76. data/lib/smart_brain/support/levenshtein.rb +35 -0
  77. data/lib/smart_brain/version.rb +5 -5
  78. data/lib/smart_brain.rb +93 -35
  79. metadata +100 -54
data/README.en.md CHANGED
@@ -1,173 +1,206 @@
1
- # SmartBrain
2
-
3
- SmartBrain is an Agent Memory Runtime and Context Composer.
4
-
5
- Core responsibilities:
6
- - `commit_turn`: persist event truth and structured memory
7
- - `compose_context`: build minimal, sufficient context per turn
8
- - integrate with SmartRAG: SmartBrain handles conversation memory, SmartRAG handles resource retrieval
9
-
10
- ## Current Progress
11
-
12
- The repository now includes a runnable v0.1 flow with:
13
- - `commit_turn` / `compose_context` end-to-end pipeline
14
- - retention / consolidation / retrieval / composition policies
15
- - retrievers: exact + relational
16
- - fusion: dedupe, rule-based rerank, diversity, budget truncation
17
- - SmartRAG adapters: `NullClient`, `HttpClient`, `DirectClient`
18
- - traceability via `request_id` / `plan_id` / `context_id`
19
- - RSpec coverage (unit + integration + regression)
20
-
21
- ## Project Layout
22
-
23
- - `lib/smart_brain.rb`: public API
24
- - `lib/smart_brain/runtime.rb`: runtime orchestration
25
- - `lib/smart_brain/contracts/`: RetrievalPlan / EvidencePack / ContextPackage validation
26
- - `lib/smart_brain/observability/`: logs and metrics
27
- - `lib/smart_brain/event_store/`: event storage (in-memory currently)
28
- - `lib/smart_brain/memory_store/`: memory storage (in-memory currently)
29
- - `lib/smart_brain/retrievers/`: exact/relational retrievers
30
- - `lib/smart_brain/fusion/`: multi-source fusion
31
- - `lib/smart_brain/context_composer/`: context assembly
32
- - `lib/smart_brain/adapters/smart_rag/`: SmartRAG adapters
33
- - `config/brain.yml`: policy config
34
- - `example.rb`: SmartBrain + SmartAgent + SmartPrompt + SmartRAG demo
35
- - `docs/`: design and protocol documents
36
-
37
- ## Installation
38
-
39
- ```bash
40
- bundle install
41
- ```
42
-
43
- If you hit permission/shared-gem issues:
44
-
45
- ```bash
46
- bundle config set --local path 'vendor/bundle'
47
- bundle config set --local disable_shared_gems 'true'
48
- ```
49
-
50
- ## Quick Start (SmartBrain Only)
51
-
52
- ```ruby
53
- require_relative 'lib/smart_brain'
54
-
55
- SmartBrain.configure
56
-
57
- SmartBrain.commit_turn(
58
- session_id: 'demo',
59
- turn_events: {
60
- messages: [
61
- { role: 'user', content: 'Remember this: default DB is Postgres.' },
62
- { role: 'assistant', content: 'Saved.' }
63
- ],
64
- decisions: [
65
- { key: 'decision:smartbrain:storage', decision: 'Use Postgres by default' }
66
- ]
67
- }
68
- )
69
-
70
- context = SmartBrain.compose_context(
71
- session_id: 'demo',
72
- user_message: 'Continue and summarize key points'
73
- )
74
-
75
- puts context[:context_id]
76
- puts context.dig(:debug, :trace, :request_id)
77
- puts context.dig(:debug, :trace, :plan_id)
78
- ```
79
-
80
- ## SmartRAG Integration Options
81
-
82
- ### 1) NullClient (default)
83
-
84
- If no SmartRAG client is injected, resource evidence is empty.
85
-
86
- ### 2) HttpClient
87
-
88
- ```ruby
89
- transport = lambda do |plan, timeout_seconds:|
90
- {
91
- plan_id: 'p1',
92
- supports_language_filter: true,
93
- evidences: []
94
- }
95
- end
96
-
97
- client = SmartBrain::Adapters::SmartRag::HttpClient.new(transport: transport, timeout_seconds: 2)
98
- SmartBrain.configure(smart_rag_client: client)
99
- ```
100
-
101
- ### 3) DirectClient (used in `example.rb`)
102
-
103
- ```ruby
104
- require 'smart_rag'
105
- require_relative 'lib/smart_brain/adapters/smart_rag/direct_client'
106
-
107
- rag_config = SmartRAG::Config.load(ENV.fetch('SMARTRAG_CONFIG_PATH'))
108
- rag = SmartRAG::SmartRAG.new(rag_config)
109
- client = SmartBrain::Adapters::SmartRag::DirectClient.new(rag: rag)
110
-
111
- SmartBrain.configure(smart_rag_client: client)
112
- ```
113
-
114
- ## `example.rb` (Updated)
115
-
116
- The example demonstrates the real loop:
117
- 1. SmartBrain `compose_context`
118
- 2. SmartAgent calls SmartPrompt worker via `call_worker`
119
- 3. SmartBrain `commit_turn`
120
- 4. prints `evidence(memory/resource)` so you can verify SmartRAG participation
121
-
122
- Files used by the demo:
123
- - `config/example_agent.yml`
124
- - `config/example_llm.yml`
125
- - `agents/brain_assistant.rb`
126
- - `workers/brain_assistant.rb`
127
- - `templates/brain_assistant.erb`
128
-
129
- Run:
130
-
131
- ```bash
132
- bundle exec ruby example.rb
133
- ```
134
-
135
- ## Core API
136
-
137
- ### `SmartBrain.configure(config_path: nil, smart_rag_client: nil, clock: -> { Time.now.utc })`
138
- Initialize runtime and optionally inject a SmartRAG client.
139
-
140
- ### `SmartBrain.commit_turn(session_id:, turn_events:)`
141
- Persist events, extract memory, resolve conflicts, update summary.
142
-
143
- ### `SmartBrain.compose_context(session_id:, user_message:, agent_state: {})`
144
- Build a `ContextPackage` with planning and fused evidence.
145
-
146
- ### `SmartBrain.diagnostics`
147
- Return observability snapshot for compose/commit logs and metrics.
148
-
149
- ## Test
150
-
151
- ```bash
152
- rspec
153
- ```
154
-
155
- ## Troubleshooting
156
-
157
- ### 1) `cannot load such file -- sequel/extensions/pgvector`
158
- `example.rb` already applies compatibility handling (`Sequel.extension 'pgvector'` and strips `database.extensions` from DB connect config).
159
-
160
- ### 2) `Config file not found: config/llm_config.yml`
161
- `example.rb` injects `config_path: ./config/example_llm.yml` for SmartRAG EmbeddingService startup.
162
-
163
- ### 3) `ruby-lsp: not found`
164
- ```bash
165
- gem install --user-install ruby-lsp debug
166
- ```
167
- and ensure user gem `bin` is in `PATH`.
168
-
169
- ## Roadmap
170
-
171
- - migrate EventStore/MemoryStore from in-memory to Postgres-backed implementations
172
- - integrate real reranker/embedding models
173
- - improve SmartRAG ingest pipeline and cross-session evaluation tooling
1
+ # SmartBrain
2
+
3
+ SmartBrain is an Agent Memory Runtime and Context Composer.
4
+
5
+ Core responsibilities:
6
+ - `commit_turn`: persist event truth and structured memory
7
+ - `compose_context`: build minimal, sufficient context per turn
8
+ - integrate with SmartRAG: SmartBrain handles conversation memory, SmartRAG handles resource retrieval
9
+
10
+ ## Current Progress
11
+
12
+ The repository now includes a runnable v0.1 flow with:
13
+ - `commit_turn` / `compose_context` end-to-end pipeline
14
+ - retention / consolidation / retrieval / composition policies
15
+ - retrievers: exact + relational
16
+ - fusion: dedupe, rule-based rerank, diversity, budget truncation
17
+ - SmartRAG adapters: `NullClient`, `HttpClient`, `DirectClient`
18
+ - traceability via `request_id` / `plan_id` / `context_id`
19
+ - RSpec coverage (unit + integration + regression)
20
+
21
+ ## Project Layout
22
+
23
+ - `lib/smart_brain.rb`: public API
24
+ - `lib/smart_brain/runtime.rb`: runtime orchestration
25
+ - `lib/smart_brain/contracts/`: RetrievalPlan / EvidencePack / ContextPackage validation
26
+ - `lib/smart_brain/observability/`: logs and metrics
27
+ - `lib/smart_brain/event_store/`: event storage (in-memory currently)
28
+ - `lib/smart_brain/memory_store/`: memory storage (in-memory currently)
29
+ - `lib/smart_brain/retrievers/`: exact/relational retrievers
30
+ - `lib/smart_brain/fusion/`: multi-source fusion
31
+ - `lib/smart_brain/context_composer/`: context assembly
32
+ - `lib/smart_brain/adapters/smart_rag/`: SmartRAG adapters
33
+ - `config/brain.yml`: policy config
34
+ - `example.rb`: SmartBrain + SmartAgent + SmartPrompt + SmartRAG demo
35
+ - `docs/`: design and protocol documents
36
+ - `docs/media_memory_schema.md`: media-memory contract, production controls, and SmartRAG migration requirements (Chinese)
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ bundle install
42
+ ```
43
+
44
+ If you hit permission/shared-gem issues:
45
+
46
+ ```bash
47
+ bundle config set --local path 'vendor/bundle'
48
+ bundle config set --local disable_shared_gems 'true'
49
+ ```
50
+
51
+ ## Quick Start (SmartBrain Only)
52
+
53
+ ```ruby
54
+ require_relative 'lib/smart_brain'
55
+
56
+ SmartBrain.configure
57
+
58
+ SmartBrain.commit_turn(
59
+ session_id: 'demo',
60
+ turn_events: {
61
+ messages: [
62
+ { role: 'user', content: 'Remember this: default DB is Postgres.' },
63
+ { role: 'assistant', content: 'Saved.' }
64
+ ],
65
+ decisions: [
66
+ { key: 'decision:smartbrain:storage', decision: 'Use Postgres by default' }
67
+ ]
68
+ }
69
+ )
70
+
71
+ context = SmartBrain.compose_context(
72
+ session_id: 'demo',
73
+ user_message: 'Continue and summarize key points'
74
+ )
75
+
76
+ puts context[:context_id]
77
+ puts context.dig(:debug, :trace, :request_id)
78
+ puts context.dig(:debug, :trace, :plan_id)
79
+ ```
80
+
81
+ ## SmartRAG Integration Options
82
+
83
+ ### 1) NullClient (default)
84
+
85
+ If no SmartRAG client is injected, resource evidence is empty.
86
+
87
+ ### 2) HttpClient
88
+
89
+ ```ruby
90
+ transport = lambda do |plan, timeout_seconds:|
91
+ {
92
+ plan_id: 'p1',
93
+ supports_language_filter: true,
94
+ evidences: []
95
+ }
96
+ end
97
+
98
+ client = SmartBrain::Adapters::SmartRag::HttpClient.new(transport: transport, timeout_seconds: 2)
99
+ SmartBrain.configure(smart_rag_client: client)
100
+ ```
101
+
102
+ For the built-in SmartRAG HTTP API, configure the remote endpoint and Bearer token directly:
103
+
104
+ ```ruby
105
+ client = SmartBrain::Adapters::SmartRag::HttpClient.for_url(
106
+ base_url: 'http://127.0.0.1:9393',
107
+ timeout_seconds: 30,
108
+ headers: { 'Authorization' => "Bearer #{ENV.fetch('SMARTRAG_TOKEN')}" }
109
+ )
110
+ SmartBrain.configure(smart_rag_client: client)
111
+ ```
112
+
113
+ ### 3) DirectClient (used in `example.rb`)
114
+
115
+ ```ruby
116
+ require 'smart_rag'
117
+ require_relative 'lib/smart_brain/adapters/smart_rag/direct_client'
118
+
119
+ rag_config = SmartRAG::Config.load(ENV.fetch('SMARTRAG_CONFIG_PATH'))
120
+ rag = SmartRAG::SmartRAG.new(rag_config)
121
+ client = SmartBrain::Adapters::SmartRag::DirectClient.new(rag: rag)
122
+
123
+ SmartBrain.configure(smart_rag_client: client)
124
+ ```
125
+
126
+ ## Media Queue Production Contract
127
+
128
+ SmartBrain delegates image, audio, and video persistence to SmartRAG. Before deploying the current queue code, migrate the **SmartRAG database** through `017_add_media_job_request_fingerprint`; running `smart_brain migrate` does not apply SmartRAG migrations. Migrations 015 and 016 add leases, shared S3/MinIO object lifecycle, staging protection, and principal-owned documents. Migration 017 backfills and requires a canonical SHA-256 request fingerprint.
129
+
130
+ Use a stable idempotency key for asynchronous retries:
131
+
132
+ ```ruby
133
+ job = SmartBrain.enqueue_media(
134
+ source: '/data/product-demo.mp4',
135
+ options: { media_type: 'video', idempotency_key: 'product-demo-v1' }
136
+ )
137
+ ```
138
+
139
+ For the same authenticated principal, repeating the same operation, source, and canonicalized options returns the original job with `deduplicated: true`. Reusing the key with a different payload returns SmartRAG HTTP `409` and `code: "idempotency_conflict"`. Keep both the original key and payload for network retries; generate a new key when the business payload changes.
140
+
141
+ `HttpClient` converts a non-2xx response into a SmartBrain result with `status: "failed"`; an idempotency conflict is visible in `warnings` as `SmartRAG HTTP 409`. `DirectClient` propagates `SmartRAG::Core::MediaJobQueue::IdempotencyConflict` to the caller.
142
+
143
+ Authenticated SmartRAG retrieval uses defense in depth: it pushes the principal's PostgreSQL-owned document IDs into search and rechecks returned candidates before emitting evidence. Invalid Bearer tokens return 401. For multi-instance workers, configure a shared S3 or MinIO endpoint, bucket, and prefix; retained failed jobs protect their staging objects until pruning.
144
+
145
+ SmartRAG's opt-in real integration suites verify MinIO cross-instance storage and deletion, asynchronous worker materialization, failed-job GC protection, Bearer-token tenant isolation, HTTP 409 behavior, and concurrent idempotency races. See the SmartRAG README section "Real storage and isolation verification" for environment variables and commands.
146
+
147
+ ## `example.rb` (Updated)
148
+
149
+ The example demonstrates the real loop:
150
+ 1. SmartBrain `compose_context`
151
+ 2. SmartAgent calls SmartPrompt worker via `call_worker`
152
+ 3. SmartBrain `commit_turn`
153
+ 4. prints `evidence(memory/resource)` so you can verify SmartRAG participation
154
+
155
+ Files used by the demo:
156
+ - `config/example_agent.yml`
157
+ - `config/example_llm.yml`
158
+ - `agents/brain_assistant.rb`
159
+ - `workers/brain_assistant.rb`
160
+ - `templates/brain_assistant.erb`
161
+
162
+ Run:
163
+
164
+ ```bash
165
+ bundle exec ruby example.rb
166
+ ```
167
+
168
+ ## Core API
169
+
170
+ ### `SmartBrain.configure(config_path: nil, smart_rag_client: nil, clock: -> { Time.now.utc })`
171
+ Initialize runtime and optionally inject a SmartRAG client.
172
+
173
+ ### `SmartBrain.commit_turn(session_id:, turn_events:)`
174
+ Persist events, extract memory, resolve conflicts, update summary.
175
+
176
+ ### `SmartBrain.compose_context(session_id:, user_message:, agent_state: {})`
177
+ Build a `ContextPackage` with planning and fused evidence.
178
+
179
+ ### `SmartBrain.diagnostics`
180
+ Return observability snapshot for compose/commit logs and metrics.
181
+
182
+ ## Test
183
+
184
+ ```bash
185
+ rspec
186
+ ```
187
+
188
+ ## Troubleshooting
189
+
190
+ ### 1) `cannot load such file -- sequel/extensions/pgvector`
191
+ `example.rb` already applies compatibility handling (`Sequel.extension 'pgvector'` and strips `database.extensions` from DB connect config).
192
+
193
+ ### 2) `Config file not found: config/llm_config.yml`
194
+ `example.rb` injects `config_path: ./config/example_llm.yml` for SmartRAG EmbeddingService startup.
195
+
196
+ ### 3) `ruby-lsp: not found`
197
+ ```bash
198
+ gem install --user-install ruby-lsp debug
199
+ ```
200
+ and ensure user gem `bin` is in `PATH`.
201
+
202
+ ## Roadmap
203
+
204
+ - migrate EventStore/MemoryStore from in-memory to Postgres-backed implementations
205
+ - integrate real reranker/embedding models
206
+ - improve SmartRAG ingest pipeline and cross-session evaluation tooling