htm 0.0.1 → 0.0.10

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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/.aigcm_msg +1 -0
  3. data/.architecture/reviews/comprehensive-codebase-review.md +577 -0
  4. data/.claude/settings.local.json +92 -0
  5. data/.envrc +1 -0
  6. data/.irbrc +283 -80
  7. data/.tbls.yml +31 -0
  8. data/CHANGELOG.md +314 -16
  9. data/CLAUDE.md +603 -0
  10. data/README.md +76 -5
  11. data/Rakefile +5 -0
  12. data/SETUP.md +132 -101
  13. data/db/migrate/{20250101000001_enable_extensions.rb → 00001_enable_extensions.rb} +0 -1
  14. data/db/migrate/00002_create_robots.rb +11 -0
  15. data/db/migrate/00003_create_file_sources.rb +20 -0
  16. data/db/migrate/00004_create_nodes.rb +65 -0
  17. data/db/migrate/00005_create_tags.rb +13 -0
  18. data/db/migrate/00006_create_node_tags.rb +18 -0
  19. data/db/migrate/00007_create_robot_nodes.rb +26 -0
  20. data/db/migrate/00009_add_working_memory_to_robot_nodes.rb +12 -0
  21. data/db/schema.sql +390 -36
  22. data/docs/api/database.md +19 -232
  23. data/docs/api/embedding-service.md +1 -7
  24. data/docs/api/htm.md +305 -364
  25. data/docs/api/index.md +1 -7
  26. data/docs/api/long-term-memory.md +342 -590
  27. data/docs/api/yard/HTM/ActiveRecordConfig.md +23 -0
  28. data/docs/api/yard/HTM/AuthorizationError.md +11 -0
  29. data/docs/api/yard/HTM/CircuitBreaker.md +92 -0
  30. data/docs/api/yard/HTM/CircuitBreakerOpenError.md +34 -0
  31. data/docs/api/yard/HTM/Configuration.md +175 -0
  32. data/docs/api/yard/HTM/Database.md +99 -0
  33. data/docs/api/yard/HTM/DatabaseError.md +14 -0
  34. data/docs/api/yard/HTM/EmbeddingError.md +18 -0
  35. data/docs/api/yard/HTM/EmbeddingService.md +58 -0
  36. data/docs/api/yard/HTM/Error.md +11 -0
  37. data/docs/api/yard/HTM/JobAdapter.md +39 -0
  38. data/docs/api/yard/HTM/LongTermMemory.md +342 -0
  39. data/docs/api/yard/HTM/NotFoundError.md +17 -0
  40. data/docs/api/yard/HTM/Observability.md +107 -0
  41. data/docs/api/yard/HTM/QueryTimeoutError.md +19 -0
  42. data/docs/api/yard/HTM/Railtie.md +27 -0
  43. data/docs/api/yard/HTM/ResourceExhaustedError.md +13 -0
  44. data/docs/api/yard/HTM/TagError.md +18 -0
  45. data/docs/api/yard/HTM/TagService.md +67 -0
  46. data/docs/api/yard/HTM/Timeframe/Result.md +24 -0
  47. data/docs/api/yard/HTM/Timeframe.md +40 -0
  48. data/docs/api/yard/HTM/TimeframeExtractor/Result.md +24 -0
  49. data/docs/api/yard/HTM/TimeframeExtractor.md +45 -0
  50. data/docs/api/yard/HTM/ValidationError.md +20 -0
  51. data/docs/api/yard/HTM/WorkingMemory.md +131 -0
  52. data/docs/api/yard/HTM.md +80 -0
  53. data/docs/api/yard/index.csv +179 -0
  54. data/docs/api/yard-reference.md +51 -0
  55. data/docs/architecture/adrs/001-postgresql-timescaledb.md +1 -1
  56. data/docs/architecture/adrs/003-ollama-embeddings.md +1 -1
  57. data/docs/architecture/adrs/010-redis-working-memory-rejected.md +2 -27
  58. data/docs/architecture/adrs/index.md +2 -13
  59. data/docs/architecture/hive-mind.md +165 -166
  60. data/docs/architecture/index.md +2 -2
  61. data/docs/architecture/overview.md +5 -171
  62. data/docs/architecture/two-tier-memory.md +1 -35
  63. data/docs/assets/images/adr-010-current-architecture.svg +37 -0
  64. data/docs/assets/images/adr-010-proposed-architecture.svg +48 -0
  65. data/docs/assets/images/adr-dependency-tree.svg +93 -0
  66. data/docs/assets/images/class-hierarchy.svg +55 -0
  67. data/docs/assets/images/exception-hierarchy.svg +45 -0
  68. data/docs/assets/images/htm-architecture-overview.svg +83 -0
  69. data/docs/assets/images/htm-complete-memory-flow.svg +160 -0
  70. data/docs/assets/images/htm-context-assembly-flow.svg +148 -0
  71. data/docs/assets/images/htm-eviction-process.svg +141 -0
  72. data/docs/assets/images/htm-memory-addition-flow.svg +138 -0
  73. data/docs/assets/images/htm-memory-recall-flow.svg +152 -0
  74. data/docs/assets/images/htm-node-states.svg +123 -0
  75. data/docs/assets/images/project-structure.svg +78 -0
  76. data/docs/assets/images/test-directory-structure.svg +38 -0
  77. data/{dbdoc → docs/database}/README.md +127 -125
  78. data/docs/database/public.file_sources.md +42 -0
  79. data/docs/database/public.file_sources.svg +211 -0
  80. data/{dbdoc → docs/database}/public.node_tags.md +7 -8
  81. data/docs/database/public.node_tags.svg +239 -0
  82. data/{dbdoc → docs/database}/public.nodes.md +22 -17
  83. data/docs/database/public.nodes.svg +271 -0
  84. data/docs/database/public.robot_nodes.md +46 -0
  85. data/docs/database/public.robot_nodes.svg +243 -0
  86. data/{dbdoc → docs/database}/public.robots.md +2 -3
  87. data/docs/database/public.robots.svg +161 -0
  88. data/docs/database/public.tags.svg +139 -0
  89. data/{dbdoc → docs/database}/schema.json +941 -630
  90. data/docs/database/schema.svg +282 -0
  91. data/docs/development/index.md +1 -29
  92. data/docs/development/schema.md +134 -309
  93. data/docs/development/testing.md +1 -9
  94. data/docs/getting-started/index.md +47 -0
  95. data/docs/{installation.md → getting-started/installation.md} +2 -2
  96. data/docs/{quick-start.md → getting-started/quick-start.md} +5 -5
  97. data/docs/guides/adding-memories.md +295 -643
  98. data/docs/guides/recalling-memories.md +36 -1
  99. data/docs/guides/search-strategies.md +85 -51
  100. data/docs/images/htm-er-diagram.svg +156 -0
  101. data/docs/index.md +16 -31
  102. data/docs/multi_framework_support.md +4 -4
  103. data/examples/README.md +280 -0
  104. data/examples/basic_usage.rb +18 -16
  105. data/examples/cli_app/htm_cli.rb +146 -8
  106. data/examples/cli_app/temp.log +93 -0
  107. data/examples/custom_llm_configuration.rb +1 -2
  108. data/examples/example_app/app.rb +11 -14
  109. data/examples/file_loader_usage.rb +177 -0
  110. data/examples/robot_groups/lib/robot_group.rb +419 -0
  111. data/examples/robot_groups/lib/working_memory_channel.rb +140 -0
  112. data/examples/robot_groups/multi_process.rb +286 -0
  113. data/examples/robot_groups/robot_worker.rb +136 -0
  114. data/examples/robot_groups/same_process.rb +229 -0
  115. data/examples/sinatra_app/Gemfile +1 -0
  116. data/examples/sinatra_app/Gemfile.lock +166 -0
  117. data/examples/sinatra_app/app.rb +219 -24
  118. data/examples/timeframe_demo.rb +276 -0
  119. data/lib/htm/active_record_config.rb +10 -3
  120. data/lib/htm/circuit_breaker.rb +202 -0
  121. data/lib/htm/configuration.rb +313 -80
  122. data/lib/htm/database.rb +67 -36
  123. data/lib/htm/embedding_service.rb +39 -2
  124. data/lib/htm/errors.rb +131 -11
  125. data/lib/htm/{sinatra.rb → integrations/sinatra.rb} +87 -12
  126. data/lib/htm/job_adapter.rb +10 -3
  127. data/lib/htm/jobs/generate_embedding_job.rb +5 -4
  128. data/lib/htm/jobs/generate_tags_job.rb +4 -0
  129. data/lib/htm/loaders/markdown_loader.rb +263 -0
  130. data/lib/htm/loaders/paragraph_chunker.rb +112 -0
  131. data/lib/htm/long_term_memory.rb +601 -321
  132. data/lib/htm/models/file_source.rb +99 -0
  133. data/lib/htm/models/node.rb +116 -12
  134. data/lib/htm/models/robot.rb +53 -4
  135. data/lib/htm/models/robot_node.rb +51 -0
  136. data/lib/htm/models/tag.rb +302 -0
  137. data/lib/htm/observability.rb +395 -0
  138. data/lib/htm/tag_service.rb +60 -3
  139. data/lib/htm/tasks.rb +29 -0
  140. data/lib/htm/timeframe.rb +194 -0
  141. data/lib/htm/timeframe_extractor.rb +307 -0
  142. data/lib/htm/version.rb +1 -1
  143. data/lib/htm/working_memory.rb +165 -70
  144. data/lib/htm.rb +352 -133
  145. data/lib/tasks/doc.rake +300 -0
  146. data/lib/tasks/files.rake +299 -0
  147. data/lib/tasks/htm.rake +188 -2
  148. data/lib/tasks/jobs.rake +10 -12
  149. data/lib/tasks/tags.rake +194 -0
  150. data/mkdocs.yml +91 -9
  151. data/notes/ARCHITECTURE_REVIEW.md +1167 -0
  152. data/notes/IMPLEMENTATION_SUMMARY.md +606 -0
  153. data/notes/MULTI_FRAMEWORK_IMPLEMENTATION.md +451 -0
  154. data/notes/next_steps.md +100 -0
  155. data/notes/plan.md +627 -0
  156. data/notes/tag_ontology_enhancement_ideas.md +222 -0
  157. data/notes/timescaledb_removal_summary.md +200 -0
  158. metadata +177 -37
  159. data/db/migrate/20250101000002_create_robots.rb +0 -14
  160. data/db/migrate/20250101000003_create_nodes.rb +0 -42
  161. data/db/migrate/20250101000005_create_tags.rb +0 -38
  162. data/db/migrate/20250101000007_add_node_vector_indexes.rb +0 -30
  163. data/dbdoc/public.node_tags.svg +0 -112
  164. data/dbdoc/public.nodes.svg +0 -118
  165. data/dbdoc/public.robots.svg +0 -90
  166. data/dbdoc/public.tags.svg +0 -60
  167. data/dbdoc/schema.svg +0 -154
  168. data/{dbdoc → docs/database}/public.node_stats.md +0 -0
  169. data/{dbdoc → docs/database}/public.node_stats.svg +0 -0
  170. data/{dbdoc → docs/database}/public.nodes_tags.md +0 -0
  171. data/{dbdoc → docs/database}/public.nodes_tags.svg +0 -0
  172. data/{dbdoc → docs/database}/public.ontology_structure.md +0 -0
  173. data/{dbdoc → docs/database}/public.ontology_structure.svg +0 -0
  174. data/{dbdoc → docs/database}/public.operations_log.md +0 -0
  175. data/{dbdoc → docs/database}/public.operations_log.svg +0 -0
  176. data/{dbdoc → docs/database}/public.relationships.md +0 -0
  177. data/{dbdoc → docs/database}/public.relationships.svg +0 -0
  178. data/{dbdoc → docs/database}/public.robot_activity.md +0 -0
  179. data/{dbdoc → docs/database}/public.robot_activity.svg +0 -0
  180. data/{dbdoc → docs/database}/public.schema_migrations.md +0 -0
  181. data/{dbdoc → docs/database}/public.schema_migrations.svg +0 -0
  182. data/{dbdoc → docs/database}/public.tags.md +3 -3
  183. /data/{dbdoc → docs/database}/public.topic_relationships.md +0 -0
  184. /data/{dbdoc → docs/database}/public.topic_relationships.svg +0 -0
data/notes/plan.md ADDED
@@ -0,0 +1,627 @@
1
+ # HTM Multi-Framework Support Implementation Plan
2
+
3
+ **Goal:** Enable HTM gem to work seamlessly in CLI, Sinatra, and Rails applications
4
+
5
+ **Date:** 2025-11-09
6
+
7
+ ---
8
+
9
+ ## Executive Summary
10
+
11
+ The HTM gem is currently well-architected but uses simple `Thread.new` for background jobs, which is insufficient for production web applications. This plan outlines the changes needed to support three application types:
12
+
13
+ 1. **Standalone CLI Applications** - Synchronous job execution, progress feedback
14
+ 2. **Sinatra-based Web Apps** - Sidekiq/inline job backends, thread safety
15
+ 3. **Rails-based Web Apps** - ActiveJob integration, Rails conventions
16
+
17
+ ## Current State Analysis
18
+
19
+ ### Strengths
20
+ - Library-based design (not monolithic)
21
+ - Environment detection (`RAILS_ENV || RACK_ENV`)
22
+ - Configurable logger, embedding, and tag services
23
+ - Connection pooling configured
24
+ - ActiveRecord for database abstraction
25
+
26
+ ### Critical Gap
27
+ Background job processing uses `Thread.new` (lib/htm.rb:278-280, 298-300), which:
28
+ - Threads may die when request completes in some Rack servers
29
+ - No job persistence/retry
30
+ - No monitoring/observability
31
+ - Not suitable for production web applications
32
+
33
+ ---
34
+
35
+ ## Required Changes by Application Type
36
+
37
+ ### 1. Standalone CLI Applications ✅ Mostly Ready
38
+
39
+ **Current Support:**
40
+ - Already works via `examples/basic_usage.rb`
41
+ - Direct database connection via `HTM_DBURL`
42
+ - Synchronous operation possible
43
+
44
+ **Needs:**
45
+ - **Job Processing Option**: Add synchronous mode for CLI
46
+ - **Progress Indicators**: CLI-friendly output for background operations
47
+ - **Executable Binary**: Optional `exe/htm` for CLI commands
48
+ - **Documentation**: CLI usage guide with examples
49
+
50
+ **Implementation Priority:** Medium
51
+
52
+ ---
53
+
54
+ ### 2. Sinatra-based Web Applications ⚠️ Needs Work
55
+
56
+ **Current Support:**
57
+ - Library can be required
58
+ - Configuration system works
59
+
60
+ **Critical Needs:**
61
+
62
+ **A. Background Job Integration** ⭐ **CRITICAL**
63
+ - Pluggable job backend (Sidekiq, inline, thread)
64
+ - Thread safety verification
65
+ - Connection pooling validation
66
+
67
+ **B. Rack Middleware** (Optional but Recommended)
68
+ - Automatic HTM instance per request
69
+ - Session-based robot identification
70
+
71
+ **C. Example Sinatra App**
72
+ - Full working example with Sidekiq
73
+ - Best practices documentation
74
+
75
+ **Implementation Priority:** **HIGH**
76
+
77
+ ---
78
+
79
+ ### 3. Rails-based Web Applications ⚠️ Needs Significant Work
80
+
81
+ **Current Support:**
82
+ - ActiveRecord already used internally
83
+ - Environment detection works
84
+ - Rake tasks exist
85
+
86
+ **Critical Needs:**
87
+
88
+ **A. ActiveJob Integration** ⭐ **CRITICAL**
89
+ - Job classes inheriting from ActiveJob::Base
90
+ - Queue configuration
91
+ - Rails job conventions
92
+
93
+ **B. Rails Connection Sharing**
94
+ - Detect and use Rails' database connection
95
+ - Avoid duplicate connection pools
96
+
97
+ **C. Rails Engine/Railtie**
98
+ - Auto-configuration on Rails boot
99
+ - Logger integration
100
+ - Rake tasks auto-loading
101
+
102
+ **D. Rails Generator**
103
+ - `rails generate htm:install` command
104
+ - Creates initializer and migrations
105
+
106
+ **E. Test Environment Handling**
107
+ - Synchronous job execution in tests
108
+ - Test helpers
109
+
110
+ **F. Example Rails App**
111
+ - Full Rails 7 application
112
+ - Best practices
113
+
114
+ **Implementation Priority:** **HIGH**
115
+
116
+ ---
117
+
118
+ ## Cross-Cutting Improvements
119
+
120
+ ### 1. Pluggable Job Backend ⭐ **HIGHEST PRIORITY**
121
+
122
+ **Create abstraction for background jobs:**
123
+
124
+ ```ruby
125
+ # lib/htm/job_adapter.rb
126
+ module HTM
127
+ module JobAdapter
128
+ def self.enqueue(job_class, **params)
129
+ case HTM.configuration.job_backend
130
+ when :active_job
131
+ job_class.perform_later(**params)
132
+ when :sidekiq
133
+ job_class.perform_async(**params)
134
+ when :inline
135
+ job_class.perform(**params)
136
+ when :thread
137
+ Thread.new { job_class.perform(**params) }
138
+ else
139
+ raise "Unknown job backend: #{HTM.configuration.job_backend}"
140
+ end
141
+ end
142
+ end
143
+ end
144
+ ```
145
+
146
+ **Configuration:**
147
+ ```ruby
148
+ HTM.configure do |c|
149
+ c.job_backend = :active_job # or :sidekiq, :inline, :thread
150
+ end
151
+ ```
152
+
153
+ **Auto-detection:**
154
+ - Detect ActiveJob if defined
155
+ - Detect Sidekiq if defined
156
+ - Use :inline for test environments
157
+ - Default to :thread for standalone apps
158
+
159
+ ---
160
+
161
+ ### 2. Environment Auto-Detection
162
+
163
+ ```ruby
164
+ # lib/htm/configuration.rb
165
+ def initialize
166
+ @job_backend = detect_job_backend
167
+ @logger = detect_logger
168
+ end
169
+
170
+ private
171
+
172
+ def detect_job_backend
173
+ if defined?(ActiveJob)
174
+ :active_job
175
+ elsif defined?(Sidekiq)
176
+ :sidekiq
177
+ elsif ENV['RACK_ENV'] == 'test' || ENV['RAILS_ENV'] == 'test'
178
+ :inline
179
+ else
180
+ :thread
181
+ end
182
+ end
183
+
184
+ def detect_logger
185
+ if defined?(Rails)
186
+ Rails.logger
187
+ elsif defined?(Sinatra::Base)
188
+ Sinatra::Base.logger
189
+ else
190
+ default_logger
191
+ end
192
+ end
193
+ ```
194
+
195
+ ---
196
+
197
+ ### 3. Thread Safety Audit
198
+
199
+ **Verify these components are thread-safe:**
200
+ - `HTM::WorkingMemory` - Per-instance state ✅
201
+ - `HTM::LongTermMemory` - Uses connection pool ✅
202
+ - `HTM::Configuration` - Global singleton ⚠️
203
+
204
+ **Add thread-safety tests:**
205
+ ```ruby
206
+ # test/thread_safety_test.rb
207
+ def test_concurrent_remember
208
+ threads = 10.times.map do |i|
209
+ Thread.new { htm.remember("Message #{i}") }
210
+ end
211
+ threads.each(&:join)
212
+ assert_equal 10, HTM::Models::Node.count
213
+ end
214
+ ```
215
+
216
+ ---
217
+
218
+ ### 4. Rails-Specific Database Integration
219
+
220
+ **Create abstract base class:**
221
+ ```ruby
222
+ # lib/htm/models/base.rb
223
+ module HTM
224
+ module Models
225
+ class Base < ActiveRecord::Base
226
+ self.abstract_class = true
227
+
228
+ def self.establish_connection_if_needed
229
+ unless connected?
230
+ if defined?(Rails)
231
+ establish_connection(Rails.configuration.database_configuration[Rails.env])
232
+ else
233
+ HTM::ActiveRecordConfig.establish_connection!
234
+ end
235
+ end
236
+ end
237
+ end
238
+ end
239
+ end
240
+ ```
241
+
242
+ **Update all models:**
243
+ ```ruby
244
+ class Robot < HTM::Models::Base
245
+ # ...
246
+ end
247
+ ```
248
+
249
+ ---
250
+
251
+ ### 5. Documentation & Examples
252
+
253
+ **Framework-Specific Documentation:**
254
+ - `docs/cli_usage.md` - CLI application guide
255
+ - `docs/sinatra_integration.md` - Sinatra integration guide
256
+ - `docs/rails_integration.md` - Rails integration guide
257
+ - `docs/job_backends.md` - Job backend configuration
258
+
259
+ **Working Example Apps:**
260
+ - `examples/cli_app/` - CLI tool with synchronous jobs
261
+ - `examples/sinatra_app/` - Sinatra + Sidekiq
262
+ - `examples/rails_app/` - Rails 7 + ActiveJob
263
+
264
+ ---
265
+
266
+ ## Implementation Roadmap
267
+
268
+ ### Phase 1: Job Backend Abstraction (Week 1) ⭐ **CRITICAL**
269
+
270
+ **Tasks:**
271
+ - [ ] Create `HTM::JobAdapter` with pluggable backends
272
+ - [ ] Add `job_backend` configuration option
273
+ - [ ] Update job enqueueing in `lib/htm.rb`
274
+ - [ ] Support: `:active_job`, `:sidekiq`, `:inline`, `:thread`
275
+ - [ ] Add environment auto-detection
276
+ - [ ] Create job adapter tests
277
+ - [ ] Update existing job classes
278
+
279
+ **Files to Create:**
280
+ - `lib/htm/job_adapter.rb`
281
+ - `test/job_adapter_test.rb`
282
+
283
+ **Files to Modify:**
284
+ - `lib/htm/configuration.rb`
285
+ - `lib/htm.rb`
286
+ - `lib/htm/jobs/generate_embedding_job.rb`
287
+ - `lib/htm/jobs/generate_tags_job.rb`
288
+
289
+ **Impact:** Enables proper Sinatra and Rails integration
290
+
291
+ ---
292
+
293
+ ### Phase 2: Rails Integration (Week 2)
294
+
295
+ **Tasks:**
296
+ - [ ] Create `HTM::Railtie` for auto-configuration
297
+ - [ ] Add Rails connection sharing logic
298
+ - [ ] Convert jobs to ActiveJob::Base (when in Rails)
299
+ - [ ] Create Rails generator (`rails g htm:install`)
300
+ - [ ] Add test environment inline jobs
301
+ - [ ] Create example Rails app
302
+ - [ ] Write Rails integration docs
303
+
304
+ **Files to Create:**
305
+ - `lib/htm/railtie.rb`
306
+ - `lib/htm/models/base.rb`
307
+ - `lib/generators/htm/install_generator.rb`
308
+ - `lib/generators/htm/templates/initializer.rb`
309
+ - `examples/rails_app/` (full Rails app)
310
+ - `docs/rails_integration.md`
311
+
312
+ **Files to Modify:**
313
+ - `lib/htm.rb` (require railtie)
314
+ - `lib/htm/active_record_config.rb`
315
+ - `lib/htm/models/*.rb` (inherit from Base)
316
+ - `README.md` (add Rails section)
317
+
318
+ **Impact:** Production-ready Rails support
319
+
320
+ ---
321
+
322
+ ### Phase 3: Sinatra Integration (Week 2)
323
+
324
+ **Tasks:**
325
+ - [ ] Create Rack middleware (optional)
326
+ - [ ] Create Sinatra helpers module
327
+ - [ ] Create example Sinatra app with Sidekiq
328
+ - [ ] Write Sinatra integration docs
329
+ - [ ] Add Sinatra-specific tests
330
+
331
+ **Files to Create:**
332
+ - `lib/htm/middleware.rb`
333
+ - `lib/htm/sinatra.rb` (helpers)
334
+ - `examples/sinatra_app/` (full Sinatra app)
335
+ - `docs/sinatra_integration.md`
336
+ - `test/sinatra_integration_test.rb`
337
+
338
+ **Files to Modify:**
339
+ - `README.md` (add Sinatra section)
340
+
341
+ **Impact:** Production-ready Sinatra support
342
+
343
+ ---
344
+
345
+ ### Phase 4: CLI Enhancements (Week 3)
346
+
347
+ **Tasks:**
348
+ - [ ] Add synchronous mode option
349
+ - [ ] Create CLI executable (`exe/htm`)
350
+ - [ ] Add progress indicators
351
+ - [ ] Create CLI example app
352
+ - [ ] Write CLI usage documentation
353
+
354
+ **Files to Create:**
355
+ - `exe/htm`
356
+ - `examples/cli_app/` (CLI tool)
357
+ - `docs/cli_usage.md`
358
+ - `lib/htm/cli.rb` (command classes)
359
+
360
+ **Files to Modify:**
361
+ - `htm.gemspec` (add executables)
362
+ - `README.md` (add CLI section)
363
+
364
+ **Impact:** Better CLI developer experience
365
+
366
+ ---
367
+
368
+ ### Phase 5: Thread Safety & Testing (Week 3)
369
+
370
+ **Tasks:**
371
+ - [ ] Thread-safety audit
372
+ - [ ] Concurrent request tests
373
+ - [ ] Load testing
374
+ - [ ] Framework integration tests
375
+ - [ ] Job backend tests for all modes
376
+
377
+ **Files to Create:**
378
+ - `test/thread_safety_test.rb`
379
+ - `test/concurrent_requests_test.rb`
380
+ - `test/job_backends/active_job_test.rb`
381
+ - `test/job_backends/sidekiq_test.rb`
382
+ - `test/job_backends/inline_test.rb`
383
+ - `test/job_backends/thread_test.rb`
384
+
385
+ **Impact:** Confidence in production deployment
386
+
387
+ ---
388
+
389
+ ## Summary of Required Changes
390
+
391
+ | Component | Change | Priority | Effort |
392
+ |-----------|--------|----------|--------|
393
+ | Job Backend Abstraction | Create `HTM::JobAdapter` | **CRITICAL** | Medium |
394
+ | Rails Railtie | Auto-configuration | High | Medium |
395
+ | Rails Connection Sharing | Detect & use Rails DB | High | Low |
396
+ | ActiveJob Integration | Job classes | High | Low |
397
+ | Sidekiq Support | Job backend option | High | Low |
398
+ | Inline/Sync Mode | For CLI & tests | Medium | Low |
399
+ | Thread Safety Tests | Concurrent tests | Medium | Low |
400
+ | Sinatra Example | Full app | Medium | Medium |
401
+ | Rails Example | Full app | Medium | High |
402
+ | Rails Generator | Install generator | Low | Medium |
403
+ | CLI Executable | Binary wrapper | Low | Low |
404
+ | Rack Middleware | Per-request HTM | Low | Medium |
405
+
406
+ **Total Estimated Effort:** 2-3 weeks for full implementation
407
+
408
+ **Minimum Viable Changes** (1 week):
409
+ 1. Job backend abstraction with ActiveJob + Sidekiq + inline support
410
+ 2. Rails Railtie for auto-config
411
+ 3. Basic thread-safety tests
412
+ 4. Updated documentation
413
+
414
+ ---
415
+
416
+ ## File Structure After Implementation
417
+
418
+ ```
419
+ htm/
420
+ ├── lib/
421
+ │ ├── htm/
422
+ │ │ ├── job_adapter.rb # NEW: Pluggable job backends
423
+ │ │ ├── railtie.rb # NEW: Rails auto-configuration
424
+ │ │ ├── middleware.rb # NEW: Rack middleware
425
+ │ │ ├── sinatra.rb # NEW: Sinatra helpers
426
+ │ │ ├── cli.rb # NEW: CLI commands
427
+ │ │ ├── models/
428
+ │ │ │ ├── base.rb # NEW: Abstract base class
429
+ │ │ │ ├── robot.rb # MODIFIED: Inherit from Base
430
+ │ │ │ ├── node.rb # MODIFIED: Inherit from Base
431
+ │ │ │ ├── tag.rb # MODIFIED: Inherit from Base
432
+ │ │ │ └── node_tag.rb # MODIFIED: Inherit from Base
433
+ │ │ ├── jobs/
434
+ │ │ │ ├── generate_embedding_job.rb # MODIFIED: Use JobAdapter
435
+ │ │ │ └── generate_tags_job.rb # MODIFIED: Use JobAdapter
436
+ │ │ ├── configuration.rb # MODIFIED: Add job_backend
437
+ │ │ └── active_record_config.rb # MODIFIED: Rails detection
438
+ │ └── generators/
439
+ │ └── htm/
440
+ │ ├── install_generator.rb # NEW: Rails generator
441
+ │ └── templates/
442
+ │ └── initializer.rb # NEW: Initializer template
443
+ ├── exe/
444
+ │ └── htm # NEW: CLI executable
445
+ ├── examples/
446
+ │ ├── cli_app/ # NEW: CLI example
447
+ │ ├── sinatra_app/ # NEW: Sinatra example
448
+ │ └── rails_app/ # NEW: Rails example
449
+ ├── docs/
450
+ │ ├── cli_usage.md # NEW: CLI guide
451
+ │ ├── sinatra_integration.md # NEW: Sinatra guide
452
+ │ ├── rails_integration.md # NEW: Rails guide
453
+ │ └── job_backends.md # NEW: Job backend guide
454
+ ├── test/
455
+ │ ├── job_adapter_test.rb # NEW: Job adapter tests
456
+ │ ├── thread_safety_test.rb # NEW: Thread safety tests
457
+ │ ├── concurrent_requests_test.rb # NEW: Concurrency tests
458
+ │ ├── sinatra_integration_test.rb # NEW: Sinatra tests
459
+ │ └── job_backends/ # NEW: Backend-specific tests
460
+ │ ├── active_job_test.rb
461
+ │ ├── sidekiq_test.rb
462
+ │ ├── inline_test.rb
463
+ │ └── thread_test.rb
464
+ └── README.md # MODIFIED: Add framework sections
465
+ ```
466
+
467
+ ---
468
+
469
+ ## Testing Strategy
470
+
471
+ ### Unit Tests
472
+ - Job adapter with all backends
473
+ - Configuration auto-detection
474
+ - Model base class connection logic
475
+
476
+ ### Integration Tests
477
+ - Rails app integration
478
+ - Sinatra app integration
479
+ - CLI app integration
480
+
481
+ ### Thread Safety Tests
482
+ - Concurrent remember() calls
483
+ - Concurrent recall() calls
484
+ - Connection pool stress test
485
+
486
+ ### Performance Tests
487
+ - Job enqueueing overhead
488
+ - Connection pool efficiency
489
+ - Memory usage under load
490
+
491
+ ---
492
+
493
+ ## Documentation Deliverables
494
+
495
+ ### User Documentation
496
+ 1. **README.md** - Updated with framework sections
497
+ 2. **docs/cli_usage.md** - Standalone CLI applications
498
+ 3. **docs/sinatra_integration.md** - Sinatra web applications
499
+ 4. **docs/rails_integration.md** - Rails web applications
500
+ 5. **docs/job_backends.md** - Job backend configuration
501
+
502
+ ### Developer Documentation
503
+ 1. **CONTRIBUTING.md** - Updated with testing guidelines
504
+ 2. **docs/architecture.md** - Job adapter architecture
505
+ 3. **docs/thread_safety.md** - Thread safety guarantees
506
+
507
+ ### Examples
508
+ 1. **examples/cli_app/** - Working CLI application
509
+ 2. **examples/sinatra_app/** - Working Sinatra app
510
+ 3. **examples/rails_app/** - Working Rails app
511
+
512
+ ---
513
+
514
+ ## Success Criteria
515
+
516
+ ### CLI Applications
517
+ - [ ] Can run synchronously without background threads
518
+ - [ ] Clear progress indicators
519
+ - [ ] Works without Rails/Sinatra dependencies
520
+ - [ ] Example app runs successfully
521
+
522
+ ### Sinatra Applications
523
+ - [ ] Works with Sidekiq in production
524
+ - [ ] Thread-safe for concurrent requests
525
+ - [ ] Example app with realistic usage
526
+ - [ ] Documentation covers deployment
527
+
528
+ ### Rails Applications
529
+ - [ ] Auto-configures on Rails boot
530
+ - [ ] Uses ActiveJob seamlessly
531
+ - [ ] Shares Rails database connection
532
+ - [ ] Generator creates working setup
533
+ - [ ] Example app demonstrates best practices
534
+ - [ ] Test environment runs synchronously
535
+
536
+ ### All Frameworks
537
+ - [ ] Zero breaking changes to existing API
538
+ - [ ] Comprehensive test coverage (>90%)
539
+ - [ ] Complete documentation
540
+ - [ ] Performance regression tests pass
541
+
542
+ ---
543
+
544
+ ## Migration Path for Existing Users
545
+
546
+ ### No Breaking Changes
547
+ All changes are backwards-compatible:
548
+ - Current `Thread.new` behavior remains default for standalone apps
549
+ - Existing configurations continue to work
550
+ - Auto-detection happens transparently
551
+
552
+ ### Optional Migration
553
+ Users can opt into new features:
554
+ ```ruby
555
+ # Sinatra app
556
+ HTM.configure do |c|
557
+ c.job_backend = :sidekiq
558
+ end
559
+
560
+ # Rails app (auto-detected, but can override)
561
+ HTM.configure do |c|
562
+ c.job_backend = :active_job # Already the default in Rails
563
+ end
564
+
565
+ # CLI app (run synchronously)
566
+ HTM.configure do |c|
567
+ c.job_backend = :inline
568
+ end
569
+ ```
570
+
571
+ ---
572
+
573
+ ## Risk Assessment
574
+
575
+ ### Low Risk
576
+ - Job adapter abstraction (well-defined interface)
577
+ - Rails Railtie (optional, doesn't affect existing users)
578
+ - Documentation and examples
579
+
580
+ ### Medium Risk
581
+ - Thread safety verification (requires thorough testing)
582
+ - Connection sharing with Rails (needs careful implementation)
583
+
584
+ ### Mitigation Strategies
585
+ - Comprehensive test suite before release
586
+ - Beta release for early adopters
587
+ - Gradual rollout (job adapter first, then framework integrations)
588
+ - Maintain backwards compatibility at all costs
589
+
590
+ ---
591
+
592
+ ## Timeline
593
+
594
+ **Week 1:** Job Backend Abstraction
595
+ - Days 1-2: Create JobAdapter, update configuration
596
+ - Days 3-4: Convert jobs to use adapter
597
+ - Day 5: Tests and documentation
598
+
599
+ **Week 2:** Rails & Sinatra Integration
600
+ - Days 1-3: Rails Railtie, connection sharing, generator
601
+ - Days 4-5: Sinatra helpers, middleware
602
+
603
+ **Week 3:** Examples, CLI, Testing
604
+ - Days 1-2: Example applications
605
+ - Days 3-4: CLI enhancements
606
+ - Day 5: Thread safety and performance tests
607
+
608
+ ---
609
+
610
+ ## Next Steps
611
+
612
+ 1. **Review and Approve** this plan
613
+ 2. **Create Feature Branch** (`git checkout -b feature/multi-framework-support`)
614
+ 3. **Phase 1 Implementation** - Job Backend Abstraction
615
+ 4. **Iterative Development** - Implement, test, document each phase
616
+ 5. **Beta Release** - Get feedback from early adopters
617
+ 6. **Production Release** - After thorough testing
618
+
619
+ ---
620
+
621
+ ## Conclusion
622
+
623
+ This implementation will transform HTM from a library that *works* in multiple frameworks to one that *excels* in each framework's ecosystem. The pluggable job backend is the critical enabler, with framework-specific integrations providing the polish that makes HTM feel native to each environment.
624
+
625
+ **Total effort: 2-3 weeks**
626
+ **Risk level: Low-Medium**
627
+ **Value: High - enables production use in web applications**