htm 0.0.32 → 0.1.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 (580) hide show
  1. checksums.yaml +4 -4
  2. data/.architecture/decisions/adrs/005-rag-based-retrieval-with-hybrid-search.md +4 -0
  3. data/.architecture/decisions/adrs/017-bitemporal-event-time.md +78 -0
  4. data/.architecture/decisions/adrs/018-memory-timelines-and-node-links.md +64 -0
  5. data/.architecture/decisions/adrs/019-epistemic-status.md +66 -0
  6. data/.claude.json +11 -0
  7. data/.envrc +9 -7
  8. data/.irbrc +14 -14
  9. data/.reek.yml +104 -0
  10. data/.rubocop.yml +0 -11
  11. data/.ruby-version +1 -0
  12. data/CHANGELOG.md +160 -98
  13. data/README.md +22 -17
  14. data/SETUP.md +49 -46
  15. data/_typos.toml +17 -0
  16. data/bin/htm +18 -0
  17. data/db/migrate/00010_convert_embedding_to_sparsevec.rb +47 -0
  18. data/db/migrate/00011_strip_frontmatter_from_chunks.rb +66 -0
  19. data/db/migrate/00012_add_event_time_to_nodes.rb +110 -0
  20. data/db/migrate/00013_create_node_links.rb +158 -0
  21. data/db/migrate/00014_add_epistemic_status.rb +110 -0
  22. data/db/schema.sql +238 -7
  23. data/db/seed_data/README.md +11 -11
  24. data/db/seeds.rb +11 -11
  25. data/docs/api/database.md +8 -8
  26. data/docs/api/embedding-service.md +138 -262
  27. data/docs/api/htm.md +128 -12
  28. data/docs/api/index.md +8 -8
  29. data/docs/api/long-term-memory.md +8 -19
  30. data/docs/api/working-memory.md +34 -46
  31. data/docs/api/yard/HTM/Admin/Console.md +53 -0
  32. data/docs/api/yard/HTM/Admin/DatabaseCommands/Console.md +38 -0
  33. data/docs/api/yard/HTM/Admin/DatabaseCommands.md +127 -0
  34. data/docs/api/yard/HTM/Admin/EnrichCommands.md +85 -0
  35. data/docs/api/yard/HTM/Admin/Error.md +9 -0
  36. data/docs/api/yard/HTM/Admin/FileCommands/Console.md +50 -0
  37. data/docs/api/yard/HTM/Admin/FileCommands.md +83 -0
  38. data/docs/api/yard/HTM/Admin/MemoryCommands/Base.md +17 -0
  39. data/docs/api/yard/HTM/Admin/MemoryCommands/Edit.md +74 -0
  40. data/docs/api/yard/HTM/Admin/MemoryCommands/Search.md +77 -0
  41. data/docs/api/yard/HTM/Admin/MemoryCommands/TagSearch.md +46 -0
  42. data/docs/api/yard/HTM/Admin/MemoryCommands/WorkingMemory.md +36 -0
  43. data/docs/api/yard/HTM/Admin/MemoryCommands.md +67 -0
  44. data/docs/api/yard/HTM/Admin/TagCommands/Console.md +48 -0
  45. data/docs/api/yard/HTM/Admin/TagCommands.md +105 -0
  46. data/docs/api/yard/HTM/Admin/TagGraph.md +149 -0
  47. data/docs/api/yard/HTM/Admin/YardDocs.md +60 -0
  48. data/docs/api/yard/HTM/Admin.md +102 -0
  49. data/docs/api/yard/HTM/AuthorizationError.md +6 -6
  50. data/docs/api/yard/HTM/CLI/ConfigFile.md +40 -0
  51. data/docs/api/yard/HTM/CLI/Db.md +63 -0
  52. data/docs/api/yard/HTM/CLI/Enrich.md +39 -0
  53. data/docs/api/yard/HTM/CLI/ErrorSuggestion.md +56 -0
  54. data/docs/api/yard/HTM/CLI/Files.md +36 -0
  55. data/docs/api/yard/HTM/CLI/Group/ClassMethods.md +11 -0
  56. data/docs/api/yard/HTM/CLI/Group.md +13 -0
  57. data/docs/api/yard/HTM/CLI/MemoryCommand/ClassMethods.md +20 -0
  58. data/docs/api/yard/HTM/CLI/MemoryCommand.md +9 -0
  59. data/docs/api/yard/HTM/CLI/Robots.md +31 -0
  60. data/docs/api/yard/HTM/CLI/Support.md +9 -0
  61. data/docs/api/yard/HTM/CLI/Tags.md +57 -0
  62. data/docs/api/yard/HTM/CLI/WorkingMemory.md +24 -0
  63. data/docs/api/yard/HTM/CLI.md +84 -0
  64. data/docs/api/yard/HTM/CircuitBreaker/Guarded.md +29 -0
  65. data/docs/api/yard/HTM/CircuitBreaker/Settings.md +21 -0
  66. data/docs/api/yard/HTM/CircuitBreaker/Status.md +42 -0
  67. data/docs/api/yard/HTM/CircuitBreaker.md +54 -49
  68. data/docs/api/yard/HTM/CircuitBreakerOpenError.md +9 -9
  69. data/docs/api/yard/HTM/Config/Builder.md +87 -0
  70. data/docs/api/yard/HTM/Config/Coercion.md +59 -0
  71. data/docs/api/yard/HTM/Config/Database.md +102 -0
  72. data/docs/api/yard/HTM/Config/Readers.md +30 -0
  73. data/docs/api/yard/HTM/Config/RubyLlmSettings.md +32 -0
  74. data/docs/api/yard/HTM/Config/Validator.md +59 -0
  75. data/docs/api/yard/HTM/Config.md +224 -105
  76. data/docs/api/yard/HTM/ConfigurationError.md +20 -0
  77. data/docs/api/yard/HTM/Confirmation.md +22 -0
  78. data/docs/api/yard/HTM/Database/Connection.md +26 -0
  79. data/docs/api/yard/HTM/Database/Migrations.md +32 -0
  80. data/docs/api/yard/HTM/Database/Report.md +26 -0
  81. data/docs/api/yard/HTM/Database/SchemaFile.md +52 -0
  82. data/docs/api/yard/HTM/Database/Teardown.md +15 -0
  83. data/docs/api/yard/HTM/Database.md +58 -70
  84. data/docs/api/yard/HTM/DatabaseDocs.md +67 -0
  85. data/docs/api/yard/HTM/DatabaseError.md +6 -6
  86. data/docs/api/yard/HTM/Deletion.md +32 -0
  87. data/docs/api/yard/HTM/EmbeddingError.md +6 -6
  88. data/docs/api/yard/HTM/EmbeddingService.md +37 -38
  89. data/docs/api/yard/HTM/Epistemics.md +135 -0
  90. data/docs/api/yard/HTM/Error.md +6 -6
  91. data/docs/api/yard/HTM/EventTime.md +110 -0
  92. data/docs/api/yard/HTM/FileMemory.md +76 -0
  93. data/docs/api/yard/HTM/InputValidator.md +82 -0
  94. data/docs/api/yard/HTM/JobAdapter/Job.md +26 -0
  95. data/docs/api/yard/HTM/JobAdapter.md +35 -16
  96. data/docs/api/yard/HTM/Jobs/FailureLogging.md +14 -0
  97. data/docs/api/yard/HTM/Jobs/GenerateEmbeddingJob.md +16 -0
  98. data/docs/api/yard/HTM/Jobs/GeneratePropositionsJob.md +17 -0
  99. data/docs/api/yard/HTM/Jobs/GenerateRelationshipsJob.md +26 -0
  100. data/docs/api/yard/HTM/Jobs/GenerateTagsJob.md +17 -0
  101. data/docs/api/yard/HTM/Jobs/LlmCallTimer.md +58 -0
  102. data/docs/api/yard/HTM/Jobs/NodeLookup.md +14 -0
  103. data/docs/api/yard/HTM/Jobs.md +13 -0
  104. data/docs/api/yard/HTM/Loaders/ChunkSync/Chunk.md +22 -0
  105. data/docs/api/yard/HTM/Loaders/ChunkSync.md +50 -0
  106. data/docs/api/yard/HTM/Loaders/MarkdownChunker/Coalescer.md +24 -0
  107. data/docs/api/yard/HTM/Loaders/MarkdownChunker/Packer.md +20 -0
  108. data/docs/api/yard/HTM/Loaders/MarkdownChunker/Splitter.md +18 -0
  109. data/docs/api/yard/HTM/Loaders/MarkdownChunker.md +83 -0
  110. data/docs/api/yard/HTM/Loaders/MarkdownLoader/Document.md +43 -0
  111. data/docs/api/yard/HTM/Loaders/MarkdownLoader.md +62 -0
  112. data/docs/api/yard/HTM/Loaders.md +5 -0
  113. data/docs/api/yard/HTM/LongTermMemory/FulltextSearch.md +36 -0
  114. data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfMerger.md +25 -0
  115. data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfRows.md +30 -0
  116. data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfSql/Query.md +79 -0
  117. data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfSql/Source.md +45 -0
  118. data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfSql.md +11 -0
  119. data/docs/api/yard/HTM/LongTermMemory/HybridSearch/TagDepth.md +52 -0
  120. data/docs/api/yard/HTM/LongTermMemory/HybridSearch.md +52 -0
  121. data/docs/api/yard/HTM/LongTermMemory/NodeOperations.md +95 -0
  122. data/docs/api/yard/HTM/LongTermMemory/RelevanceScorer/HierarchicalJaccard.md +58 -0
  123. data/docs/api/yard/HTM/LongTermMemory/RelevanceScorer/TagSearch.md +27 -0
  124. data/docs/api/yard/HTM/LongTermMemory/RelevanceScorer.md +81 -0
  125. data/docs/api/yard/HTM/LongTermMemory/RobotOperations.md +22 -0
  126. data/docs/api/yard/HTM/LongTermMemory/TagOperations/ExpiringValue.md +24 -0
  127. data/docs/api/yard/HTM/LongTermMemory/TagOperations/TagMatchSql.md +40 -0
  128. data/docs/api/yard/HTM/LongTermMemory/TagOperations.md +129 -0
  129. data/docs/api/yard/HTM/LongTermMemory/VectorSearch.md +30 -0
  130. data/docs/api/yard/HTM/LongTermMemory.md +279 -31
  131. data/docs/api/yard/HTM/MCP/AssembleContextTool.md +16 -0
  132. data/docs/api/yard/HTM/MCP/ClearGroupWorkingMemoryTool.md +12 -0
  133. data/docs/api/yard/HTM/MCP/ClearWorkingMemoryTool.md +12 -0
  134. data/docs/api/yard/HTM/MCP/ConfigResource.md +12 -0
  135. data/docs/api/yard/HTM/MCP/ConfirmTool.md +12 -0
  136. data/docs/api/yard/HTM/MCP/CreateGroupTool.md +12 -0
  137. data/docs/api/yard/HTM/MCP/EnrichPendingTool.md +16 -0
  138. data/docs/api/yard/HTM/MCP/ExtractPropositionsTool.md +12 -0
  139. data/docs/api/yard/HTM/MCP/FailoverTool.md +12 -0
  140. data/docs/api/yard/HTM/MCP/FileInfoTool.md +13 -0
  141. data/docs/api/yard/HTM/MCP/FileSourcesResource.md +12 -0
  142. data/docs/api/yard/HTM/MCP/FileSupport.md +7 -0
  143. data/docs/api/yard/HTM/MCP/FindByTopicTool.md +12 -0
  144. data/docs/api/yard/HTM/MCP/FirstMentionTool.md +12 -0
  145. data/docs/api/yard/HTM/MCP/ForgetContentTool.md +12 -0
  146. data/docs/api/yard/HTM/MCP/ForgetTool.md +12 -0
  147. data/docs/api/yard/HTM/MCP/GetGroupStatusTool.md +12 -0
  148. data/docs/api/yard/HTM/MCP/GetGroupWorkingMemoryTool.md +12 -0
  149. data/docs/api/yard/HTM/MCP/GetNodeTool.md +12 -0
  150. data/docs/api/yard/HTM/MCP/GetRobotTool.md +12 -0
  151. data/docs/api/yard/HTM/MCP/GetWorkingMemoryTool.md +12 -0
  152. data/docs/api/yard/HTM/MCP/GroupRecallTool.md +12 -0
  153. data/docs/api/yard/HTM/MCP/GroupRememberTool.md +12 -0
  154. data/docs/api/yard/HTM/MCP/GroupSession.md +23 -0
  155. data/docs/api/yard/HTM/MCP/JoinGroupTool.md +12 -0
  156. data/docs/api/yard/HTM/MCP/LeaveGroupTool.md +12 -0
  157. data/docs/api/yard/HTM/MCP/ListDeletedTool.md +12 -0
  158. data/docs/api/yard/HTM/MCP/ListFilesTool.md +13 -0
  159. data/docs/api/yard/HTM/MCP/ListGroupsTool.md +12 -0
  160. data/docs/api/yard/HTM/MCP/ListRobotsTool.md +12 -0
  161. data/docs/api/yard/HTM/MCP/ListTagsTool.md +12 -0
  162. data/docs/api/yard/HTM/MCP/LoadDirectoryTool.md +13 -0
  163. data/docs/api/yard/HTM/MCP/LoadFileTool.md +13 -0
  164. data/docs/api/yard/HTM/MCP/MemoryStatsResource.md +13 -0
  165. data/docs/api/yard/HTM/MCP/PopularTagsTool.md +12 -0
  166. data/docs/api/yard/HTM/MCP/PromoteRobotTool.md +12 -0
  167. data/docs/api/yard/HTM/MCP/PurgeDeletedTool.md +12 -0
  168. data/docs/api/yard/HTM/MCP/RecallTool.md +16 -0
  169. data/docs/api/yard/HTM/MCP/RecentMemoriesResource.md +13 -0
  170. data/docs/api/yard/HTM/MCP/RelatedNodesTool.md +12 -0
  171. data/docs/api/yard/HTM/MCP/RememberTool.md +12 -0
  172. data/docs/api/yard/HTM/MCP/RestoreTool.md +12 -0
  173. data/docs/api/yard/HTM/MCP/RobotGroupsResource.md +13 -0
  174. data/docs/api/yard/HTM/MCP/RobotTeamsStatusTool.md +13 -0
  175. data/docs/api/yard/HTM/MCP/RunRobotTeamsTool.md +13 -0
  176. data/docs/api/yard/HTM/MCP/SearchByTagsTool.md +16 -0
  177. data/docs/api/yard/HTM/MCP/SearchTagsTool.md +12 -0
  178. data/docs/api/yard/HTM/MCP/Server.md +37 -0
  179. data/docs/api/yard/HTM/MCP/Session.md +32 -0
  180. data/docs/api/yard/HTM/MCP/SetRobotTool.md +12 -0
  181. data/docs/api/yard/HTM/MCP/ShutdownGroupTool.md +12 -0
  182. data/docs/api/yard/HTM/MCP/StartupPromptResource.md +16 -0
  183. data/docs/api/yard/HTM/MCP/StatsTool.md +12 -0
  184. data/docs/api/yard/HTM/MCP/SyncFilesTool.md +13 -0
  185. data/docs/api/yard/HTM/MCP/SyncGroupTool.md +12 -0
  186. data/docs/api/yard/HTM/MCP/TagHierarchyResource.md +16 -0
  187. data/docs/api/yard/HTM/MCP/TagNodeTool.md +12 -0
  188. data/docs/api/yard/HTM/MCP/TagTreeTool.md +22 -0
  189. data/docs/api/yard/HTM/MCP/TeamNames.md +7 -0
  190. data/docs/api/yard/HTM/MCP/TimelineTool.md +12 -0
  191. data/docs/api/yard/HTM/MCP/Tool.md +24 -0
  192. data/docs/api/yard/HTM/MCP/ToolSupport.md +17 -0
  193. data/docs/api/yard/HTM/MCP/TopicRelationshipsTool.md +12 -0
  194. data/docs/api/yard/HTM/MCP/TransferWorkingMemoryTool.md +12 -0
  195. data/docs/api/yard/HTM/MCP/UnloadFileTool.md +13 -0
  196. data/docs/api/yard/HTM/MCP/UntagNodeTool.md +12 -0
  197. data/docs/api/yard/HTM/MCP.md +30 -0
  198. data/docs/api/yard/HTM/Migration.md +44 -0
  199. data/docs/api/yard/HTM/Models/FileSource.md +66 -0
  200. data/docs/api/yard/HTM/Models/Node/Scopes.md +74 -0
  201. data/docs/api/yard/HTM/Models/Node/SoftDeletion.md +22 -0
  202. data/docs/api/yard/HTM/Models/Node/VectorSimilarity.md +28 -0
  203. data/docs/api/yard/HTM/Models/Node.md +113 -0
  204. data/docs/api/yard/HTM/Models/NodeLink.md +65 -0
  205. data/docs/api/yard/HTM/Models/NodeRelationship.md +31 -0
  206. data/docs/api/yard/HTM/Models/NodeTag.md +38 -0
  207. data/docs/api/yard/HTM/Models/Robot.md +50 -0
  208. data/docs/api/yard/HTM/Models/RobotNode.md +35 -0
  209. data/docs/api/yard/HTM/Models/Tag/Scopes.md +32 -0
  210. data/docs/api/yard/HTM/Models/Tag.md +112 -0
  211. data/docs/api/yard/HTM/Models.md +5 -0
  212. data/docs/api/yard/HTM/NodeEnrichment.md +36 -0
  213. data/docs/api/yard/HTM/NodeView.md +113 -0
  214. data/docs/api/yard/HTM/NotFoundError.md +6 -5
  215. data/docs/api/yard/HTM/Observability.md +58 -40
  216. data/docs/api/yard/HTM/PropositionError.md +6 -6
  217. data/docs/api/yard/HTM/PropositionService.md +63 -29
  218. data/docs/api/yard/HTM/QueryCache/KeyNormalizer.md +25 -0
  219. data/docs/api/yard/HTM/QueryCache/NullStore.md +19 -0
  220. data/docs/api/yard/HTM/QueryCache/Store.md +43 -0
  221. data/docs/api/yard/HTM/QueryCache.md +41 -46
  222. data/docs/api/yard/HTM/QueryTimeoutError.md +9 -8
  223. data/docs/api/yard/HTM/Railtie.md +11 -7
  224. data/docs/api/yard/HTM/RecallQuery.md +111 -0
  225. data/docs/api/yard/HTM/ResourceExhaustedError.md +6 -6
  226. data/docs/api/yard/HTM/RobotGroup/CacheSync.md +35 -0
  227. data/docs/api/yard/HTM/RobotGroup/Membership.md +96 -0
  228. data/docs/api/yard/HTM/RobotGroup/TransferOptions.md +14 -0
  229. data/docs/api/yard/HTM/RobotGroup/WorkingMemoryLedger.md +65 -0
  230. data/docs/api/yard/HTM/RobotGroup.md +116 -360
  231. data/docs/api/yard/HTM/Robots/Actions/TagMove.md +31 -0
  232. data/docs/api/yard/HTM/Robots/Actions.md +153 -0
  233. data/docs/api/yard/HTM/Robots/Neighbors.md +20 -0
  234. data/docs/api/yard/HTM/Robots/Supervisor/Idler.md +26 -0
  235. data/docs/api/yard/HTM/Robots/Supervisor/Roster.md +26 -0
  236. data/docs/api/yard/HTM/Robots/Supervisor.md +42 -0
  237. data/docs/api/yard/HTM/Robots/Team.md +60 -0
  238. data/docs/api/yard/HTM/Robots/Teams/Archivist.md +43 -0
  239. data/docs/api/yard/HTM/Robots/Teams/Consolidator.md +29 -0
  240. data/docs/api/yard/HTM/Robots/Teams/ContradictionDetector.md +33 -0
  241. data/docs/api/yard/HTM/Robots/Teams/TagCurator.md +37 -0
  242. data/docs/api/yard/HTM/Robots/Teams.md +5 -0
  243. data/docs/api/yard/HTM/Robots/Tools/ArchiveNodes.md +12 -0
  244. data/docs/api/yard/HTM/Robots/Tools/Base.md +16 -0
  245. data/docs/api/yard/HTM/Robots/Tools/MergeNodes.md +12 -0
  246. data/docs/api/yard/HTM/Robots/Tools/MergeTags.md +12 -0
  247. data/docs/api/yard/HTM/Robots/Tools/Pass.md +12 -0
  248. data/docs/api/yard/HTM/Robots/Tools/RecordConflict.md +12 -0
  249. data/docs/api/yard/HTM/Robots/Tools/SupersedeNode.md +12 -0
  250. data/docs/api/yard/HTM/Robots/Tools.md +14 -0
  251. data/docs/api/yard/HTM/Robots.md +72 -0
  252. data/docs/api/yard/HTM/SearchFilters.md +82 -0
  253. data/docs/api/yard/HTM/SequelConfig.md +97 -0
  254. data/docs/api/yard/HTM/Settings.md +39 -0
  255. data/docs/api/yard/HTM/Sinatra/Helpers.md +37 -0
  256. data/docs/api/yard/HTM/Sinatra/Middleware.md +29 -0
  257. data/docs/api/yard/HTM/Sinatra.md +44 -0
  258. data/docs/api/yard/HTM/SqlBuilder/Sparsevec.md +69 -0
  259. data/docs/api/yard/HTM/SqlBuilder.md +62 -75
  260. data/docs/api/yard/HTM/StartupPrompt.md +45 -0
  261. data/docs/api/yard/HTM/TagError.md +6 -6
  262. data/docs/api/yard/HTM/TagService.md +100 -37
  263. data/docs/api/yard/HTM/TagTree/Branch.md +43 -0
  264. data/docs/api/yard/HTM/TagTree/SvgRenderer/Layout.md +51 -0
  265. data/docs/api/yard/HTM/TagTree/SvgRenderer.md +25 -0
  266. data/docs/api/yard/HTM/TagTree.md +65 -0
  267. data/docs/api/yard/HTM/Telemetry/NullInstrument.md +12 -9
  268. data/docs/api/yard/HTM/Telemetry/NullMeter.md +17 -9
  269. data/docs/api/yard/HTM/Telemetry.md +53 -50
  270. data/docs/api/yard/HTM/Timeframe/Result.md +13 -16
  271. data/docs/api/yard/HTM/Timeframe.md +17 -20
  272. data/docs/api/yard/HTM/TimeframeExtractor/Patterns.md +18 -0
  273. data/docs/api/yard/HTM/TimeframeExtractor/Result.md +13 -16
  274. data/docs/api/yard/HTM/TimeframeExtractor.md +27 -16
  275. data/docs/api/yard/HTM/Timeline.md +113 -0
  276. data/docs/api/yard/HTM/ValidationError.md +6 -5
  277. data/docs/api/yard/HTM/Workflows/RememberWorkflow/NodeState.md +73 -0
  278. data/docs/api/yard/HTM/Workflows/RememberWorkflow.md +80 -0
  279. data/docs/api/yard/HTM/Workflows.md +5 -0
  280. data/docs/api/yard/HTM/WorkingMemory/Entry.md +67 -0
  281. data/docs/api/yard/HTM/WorkingMemory/Store.md +54 -0
  282. data/docs/api/yard/HTM/WorkingMemory.md +113 -87
  283. data/docs/api/yard/HTM/WorkingMemoryChannel/Subscribers.md +28 -0
  284. data/docs/api/yard/HTM/WorkingMemoryChannel.md +108 -102
  285. data/docs/api/yard/HTM.md +483 -5
  286. data/docs/api/yard/README.md +211 -0
  287. data/docs/api/yard/Sinatra/Base.md +30 -0
  288. data/docs/api/yard/Sinatra.md +7 -0
  289. data/docs/api/yard/index.csv +1834 -181
  290. data/docs/api/yard-reference.md +228 -9
  291. data/docs/architecture/adrs/005-rag-retrieval.md +3 -0
  292. data/docs/architecture/adrs/index.md +1 -1
  293. data/docs/architecture/index.md +2 -2
  294. data/docs/architecture/overview.md +3 -3
  295. data/docs/assets/images/project-structure.svg +2 -2
  296. data/docs/database/INDEX.md +113 -0
  297. data/docs/database/README.md +60 -176
  298. data/docs/database/file_sources.md +51 -0
  299. data/docs/database/file_sources.svg +120 -0
  300. data/docs/database/naming-convention.md +12 -12
  301. data/docs/database/node_links.md +65 -0
  302. data/docs/database/node_links.svg +171 -0
  303. data/docs/database/node_relationships.md +62 -0
  304. data/docs/database/node_relationships.svg +124 -0
  305. data/docs/database/node_tags.md +50 -0
  306. data/docs/database/node_tags.svg +125 -0
  307. data/docs/database/nodes.md +120 -0
  308. data/docs/database/nodes.svg +394 -0
  309. data/docs/database/robot_nodes.md +57 -0
  310. data/docs/database/robot_nodes.svg +155 -0
  311. data/docs/database/robots.md +40 -0
  312. data/docs/database/robots.svg +131 -0
  313. data/docs/database/schema.svg +384 -275
  314. data/docs/database/schema_migrations.md +19 -0
  315. data/docs/database/schema_migrations.svg +31 -0
  316. data/docs/database/tags.md +47 -0
  317. data/docs/database/tags.svg +90 -0
  318. data/docs/development/asgard-tasks.md +114 -0
  319. data/docs/development/contributing.md +6 -6
  320. data/docs/development/index.md +15 -17
  321. data/docs/development/schema.md +43 -14
  322. data/docs/development/setup.md +60 -70
  323. data/docs/development/testing.md +57 -65
  324. data/docs/examples/basic-usage.md +9 -9
  325. data/docs/examples/config-files.md +8 -8
  326. data/docs/examples/file-loading.md +12 -12
  327. data/docs/examples/index.md +15 -8
  328. data/docs/examples/llm-configuration.md +13 -9
  329. data/docs/examples/mcp-client.md +61 -59
  330. data/docs/examples/rails-integration.md +5 -4
  331. data/docs/examples/sinatra-integration.md +5 -4
  332. data/docs/examples/standalone-app.md +17 -16
  333. data/docs/getting-started/index.md +3 -3
  334. data/docs/getting-started/installation.md +76 -83
  335. data/docs/getting-started/quick-start.md +24 -22
  336. data/docs/guides/adding-memories.md +14 -3
  337. data/docs/guides/cli.md +458 -0
  338. data/docs/guides/configuration.md +72 -37
  339. data/docs/guides/epistemic-status.md +138 -0
  340. data/docs/guides/event-time.md +106 -0
  341. data/docs/guides/file-loading.md +26 -22
  342. data/docs/guides/getting-started.md +21 -17
  343. data/docs/guides/long-term-memory.md +1 -1
  344. data/docs/guides/mcp-server.md +416 -173
  345. data/docs/guides/propositions.md +18 -29
  346. data/docs/guides/recalling-memories.md +22 -7
  347. data/docs/guides/robot-teams.md +96 -0
  348. data/docs/guides/search-strategies.md +10 -7
  349. data/docs/guides/tags.md +19 -19
  350. data/docs/guides/timeline.md +106 -0
  351. data/docs/index.md +7 -7
  352. data/docs/llms.txt +35 -0
  353. data/docs/multi_framework_support.md +13 -13
  354. data/docs/robots/robot-groups.md +9 -9
  355. data/docs/robots/two-tier-memory.md +13 -26
  356. data/docs/setup_local_database.md +33 -31
  357. data/examples/00_create_examples_db.rb +20 -7
  358. data/examples/01_basic_usage.rb +20 -18
  359. data/examples/02_config_file_example/README.md +13 -12
  360. data/examples/02_config_file_example/config/htm.local.yml +8 -8
  361. data/examples/02_config_file_example/show_config.rb +3 -4
  362. data/examples/03_custom_llm_configuration.rb +12 -12
  363. data/examples/04_file_loader_usage.rb +15 -21
  364. data/examples/05_timeframe_demo.rb +282 -234
  365. data/examples/06_example_app/.loki +36 -0
  366. data/examples/06_example_app/app.rb +21 -33
  367. data/examples/07_cli_app/README.md +18 -18
  368. data/examples/07_cli_app/htm_cli.rb +25 -19
  369. data/examples/08_sinatra_app/Gemfile +1 -0
  370. data/examples/08_sinatra_app/Gemfile.lock +101 -67
  371. data/examples/08_sinatra_app/app.rb +64 -62
  372. data/examples/09_mcp_client.rb +92 -119
  373. data/examples/10_telemetry/README.md +3 -3
  374. data/examples/10_telemetry/SETUP_README.md +2 -2
  375. data/examples/10_telemetry/demo.rb +5 -5
  376. data/examples/11_robot_groups/README.md +5 -4
  377. data/examples/11_robot_groups/lib/robot_worker.rb +0 -5
  378. data/examples/11_robot_groups/multi_process.rb +5 -4
  379. data/examples/11_robot_groups/same_process.rb +18 -17
  380. data/examples/12_rails_app/Gemfile +1 -1
  381. data/examples/12_rails_app/Gemfile.lock +146 -97
  382. data/examples/12_rails_app/README.md +21 -17
  383. data/examples/12_rails_app/app/controllers/chats_controller.rb +33 -63
  384. data/examples/12_rails_app/app/controllers/memories_controller.rb +7 -1
  385. data/examples/12_rails_app/app/controllers/messages_controller.rb +21 -58
  386. data/examples/12_rails_app/app/controllers/search_controller.rb +7 -2
  387. data/examples/12_rails_app/app/models/chat.rb +0 -33
  388. data/examples/12_rails_app/app/models/message.rb +0 -2
  389. data/examples/12_rails_app/app/views/chats/show.html.erb +2 -2
  390. data/examples/12_rails_app/app/views/files/new.html.erb +1 -1
  391. data/examples/12_rails_app/app/views/memories/_memory_card.html.erb +1 -1
  392. data/examples/12_rails_app/app/views/memories/new.html.erb +12 -0
  393. data/examples/12_rails_app/app/views/memories/show.html.erb +13 -0
  394. data/examples/12_rails_app/app/views/search/index.html.erb +18 -2
  395. data/examples/12_rails_app/config/initializers/ruby_llm.rb +11 -15
  396. data/examples/12_rails_app/db/migrate/20261205061932_create_ruby_llm_records.rb +160 -0
  397. data/examples/12_rails_app/db/migrate/20261205061933_create_chats.rb +13 -0
  398. data/examples/12_rails_app/db/migrate/20261205061934_create_messages.rb +23 -0
  399. data/examples/12_rails_app/db/schema.rb +163 -20
  400. data/examples/README.md +53 -44
  401. data/examples/examples_helper.rb +29 -5
  402. data/htm.gemspec +68 -0
  403. data/lib/htm/admin/database_commands.rb +454 -0
  404. data/lib/htm/admin/enrich_commands.rb +209 -0
  405. data/lib/htm/admin/file_commands.rb +323 -0
  406. data/lib/htm/admin/memory_commands/edit.rb +157 -0
  407. data/lib/htm/admin/memory_commands/search.rb +178 -0
  408. data/lib/htm/admin/memory_commands/tag_search.rb +98 -0
  409. data/lib/htm/admin/memory_commands/text.rb +164 -0
  410. data/lib/htm/admin/memory_commands/working_memory.rb +71 -0
  411. data/lib/htm/admin/memory_commands.rb +179 -0
  412. data/lib/htm/admin/tag_commands.rb +352 -0
  413. data/lib/htm/admin/tag_graph.rb +290 -0
  414. data/lib/htm/admin/templates/tag_graph.html +295 -0
  415. data/lib/htm/admin/yard_docs.rb +206 -0
  416. data/lib/htm/admin.rb +253 -0
  417. data/lib/htm/circuit_breaker.rb +142 -68
  418. data/lib/htm/class_methods.rb +136 -0
  419. data/lib/htm/cli/config_file.rb +86 -0
  420. data/lib/htm/cli/db.rb +77 -0
  421. data/lib/htm/cli/enrich.rb +44 -0
  422. data/lib/htm/cli/environment.rb +74 -0
  423. data/lib/htm/cli/error_suggestion.rb +97 -0
  424. data/lib/htm/cli/files.rb +41 -0
  425. data/lib/htm/cli/group.rb +32 -0
  426. data/lib/htm/cli/memory.rb +320 -0
  427. data/lib/htm/cli/memory_command.rb +71 -0
  428. data/lib/htm/cli/robots.rb +71 -0
  429. data/lib/htm/cli/support.rb +46 -0
  430. data/lib/htm/cli/tags.rb +103 -0
  431. data/lib/htm/cli/working_memory.rb +41 -0
  432. data/lib/htm/cli.rb +75 -0
  433. data/lib/htm/config/builder.rb +99 -68
  434. data/lib/htm/config/coercion.rb +91 -0
  435. data/lib/htm/config/database.rb +81 -52
  436. data/lib/htm/config/defaults.yml +52 -16
  437. data/lib/htm/config/readers.rb +85 -0
  438. data/lib/htm/config/ruby_llm_settings.rb +58 -0
  439. data/lib/htm/config/validator.rb +45 -26
  440. data/lib/htm/config.rb +112 -297
  441. data/lib/htm/database.rb +305 -396
  442. data/lib/htm/database_docs.rb +149 -0
  443. data/lib/htm/embedding_service.rb +26 -66
  444. data/lib/htm/epistemics.rb +254 -0
  445. data/lib/htm/errors.rb +4 -4
  446. data/lib/htm/event_time.rb +201 -0
  447. data/lib/htm/file_memory.rb +106 -0
  448. data/lib/htm/input_validator.rb +158 -0
  449. data/lib/htm/integrations/sinatra.rb +43 -31
  450. data/lib/htm/job_adapter.rb +78 -83
  451. data/lib/htm/jobs/failure_logging.rb +49 -0
  452. data/lib/htm/jobs/generate_embedding_job.rb +21 -28
  453. data/lib/htm/jobs/generate_propositions_job.rb +56 -28
  454. data/lib/htm/jobs/generate_relationships_job.rb +28 -24
  455. data/lib/htm/jobs/generate_tags_job.rb +32 -37
  456. data/lib/htm/jobs/llm_call_timer.rb +53 -0
  457. data/lib/htm/jobs/node_lookup.rb +27 -0
  458. data/lib/htm/knowledge_memory.rb +153 -0
  459. data/lib/htm/loaders/chunk_sync.rb +168 -0
  460. data/lib/htm/loaders/markdown_chunker.rb +207 -36
  461. data/lib/htm/loaders/markdown_loader.rb +76 -120
  462. data/lib/htm/long_term_memory/fulltext_search.rb +15 -36
  463. data/lib/htm/long_term_memory/hybrid_search.rb +471 -544
  464. data/lib/htm/long_term_memory/node_operations.rb +110 -81
  465. data/lib/htm/long_term_memory/relevance_scorer.rb +232 -237
  466. data/lib/htm/long_term_memory/tag_operations.rb +201 -130
  467. data/lib/htm/long_term_memory/vector_search.rb +33 -61
  468. data/lib/htm/long_term_memory.rb +5 -17
  469. data/lib/htm/mcp/file_tools.rb +190 -0
  470. data/lib/htm/mcp/group_tools.rb +223 -233
  471. data/lib/htm/mcp/node_tools.rb +350 -0
  472. data/lib/htm/mcp/resources.rb +102 -28
  473. data/lib/htm/mcp/robot_team_tools.rb +119 -0
  474. data/lib/htm/mcp/server.rb +26 -14
  475. data/lib/htm/mcp/tag_tools.rb +130 -0
  476. data/lib/htm/mcp/tool.rb +40 -0
  477. data/lib/htm/mcp/tool_support.rb +88 -0
  478. data/lib/htm/mcp/tools.rb +232 -283
  479. data/lib/htm/models/file_source.rb +35 -20
  480. data/lib/htm/models/node.rb +287 -193
  481. data/lib/htm/models/node_link.rb +97 -0
  482. data/lib/htm/models/node_relationship.rb +3 -2
  483. data/lib/htm/models/node_tag.rb +22 -2
  484. data/lib/htm/models/robot.rb +4 -8
  485. data/lib/htm/models/robot_node.rb +5 -2
  486. data/lib/htm/models/tag.rb +53 -207
  487. data/lib/htm/node_enrichment.rb +75 -0
  488. data/lib/htm/node_view.rb +295 -0
  489. data/lib/htm/observability.rb +114 -98
  490. data/lib/htm/proposition_service.rb +38 -74
  491. data/lib/htm/query_cache.rb +145 -91
  492. data/lib/htm/railtie.rb +3 -7
  493. data/lib/htm/request_options.rb +149 -0
  494. data/lib/htm/robot_group/cache_sync.rb +69 -0
  495. data/lib/htm/robot_group/membership.rb +147 -0
  496. data/lib/htm/robot_group/working_memory_ledger.rb +111 -0
  497. data/lib/htm/robot_group.rb +128 -521
  498. data/lib/htm/robots/actions.rb +371 -0
  499. data/lib/htm/robots/neighbors.rb +63 -0
  500. data/lib/htm/robots/node_brief.rb +49 -0
  501. data/lib/htm/robots/supervisor.rb +140 -0
  502. data/lib/htm/robots/team.rb +124 -0
  503. data/lib/htm/robots/teams/archivist.rb +88 -0
  504. data/lib/htm/robots/teams/consolidator.rb +52 -0
  505. data/lib/htm/robots/teams/contradiction_detector.rb +67 -0
  506. data/lib/htm/robots/teams/tag_curator.rb +75 -0
  507. data/lib/htm/robots/tools.rb +127 -0
  508. data/lib/htm/robots.rb +125 -0
  509. data/lib/htm/search_filters.rb +116 -0
  510. data/lib/htm/sequel_config.rb +95 -59
  511. data/lib/htm/sql_builder.rb +162 -53
  512. data/lib/htm/startup_prompt.rb +73 -0
  513. data/lib/htm/tag_service.rb +104 -109
  514. data/lib/htm/tag_tree.rb +206 -0
  515. data/lib/htm/telemetry.rb +15 -16
  516. data/lib/htm/timeframe.rb +27 -9
  517. data/lib/htm/timeframe_extractor.rb +77 -55
  518. data/lib/htm/timeline.rb +230 -0
  519. data/lib/htm/version.rb +1 -1
  520. data/lib/htm/workflows/remember_workflow.rb +145 -136
  521. data/lib/htm/working_memory/entry.rb +53 -0
  522. data/lib/htm/working_memory/store.rb +97 -0
  523. data/lib/htm/working_memory.rb +137 -139
  524. data/lib/htm/working_memory_channel.rb +90 -40
  525. data/lib/htm.rb +177 -501
  526. data/mkdocs.yml +100 -23
  527. data/scripts/install_local_database.sh +7 -6
  528. metadata +1032 -594
  529. data/.tbls.yml +0 -31
  530. data/Rakefile +0 -240
  531. data/bin/htm_mcp +0 -27
  532. data/docs/api/yard/HTM/ActiveRecordConfig.md +0 -29
  533. data/docs/api/yard/HTM/ConfigSection.md +0 -28
  534. data/docs/database/public.file_sources.md +0 -42
  535. data/docs/database/public.file_sources.svg +0 -219
  536. data/docs/database/public.node_stats.md +0 -48
  537. data/docs/database/public.node_stats.svg +0 -41
  538. data/docs/database/public.node_tags.md +0 -41
  539. data/docs/database/public.node_tags.svg +0 -251
  540. data/docs/database/public.nodes.md +0 -61
  541. data/docs/database/public.nodes.svg +0 -283
  542. data/docs/database/public.nodes_tags.md +0 -39
  543. data/docs/database/public.nodes_tags.svg +0 -112
  544. data/docs/database/public.ontology_structure.md +0 -48
  545. data/docs/database/public.ontology_structure.svg +0 -38
  546. data/docs/database/public.operations_log.md +0 -42
  547. data/docs/database/public.operations_log.svg +0 -130
  548. data/docs/database/public.relationships.md +0 -39
  549. data/docs/database/public.relationships.svg +0 -41
  550. data/docs/database/public.robot_activity.md +0 -46
  551. data/docs/database/public.robot_activity.svg +0 -35
  552. data/docs/database/public.robot_nodes.md +0 -48
  553. data/docs/database/public.robot_nodes.svg +0 -251
  554. data/docs/database/public.robots.md +0 -34
  555. data/docs/database/public.robots.svg +0 -165
  556. data/docs/database/public.schema_migrations.md +0 -29
  557. data/docs/database/public.schema_migrations.svg +0 -26
  558. data/docs/database/public.tags.md +0 -38
  559. data/docs/database/public.tags.svg +0 -147
  560. data/docs/database/public.topic_relationships.md +0 -45
  561. data/docs/database/public.topic_relationships.svg +0 -32
  562. data/docs/database/schema.json +0 -1814
  563. data/docs/database_rake_tasks.md +0 -345
  564. data/docs/development/rake-tasks.md +0 -1113
  565. data/docs/using_rake_tasks_in_your_app.md +0 -383
  566. data/examples/06_example_app/Rakefile +0 -71
  567. data/examples/12_rails_app/app/models/model.rb +0 -5
  568. data/examples/12_rails_app/app/models/tool_call.rb +0 -5
  569. data/examples/12_rails_app/db/migrate/20250124000001_create_ruby_llm_tables.rb +0 -34
  570. data/examples/12_rails_app/db/migrate/20250124000002_create_models_table.rb +0 -28
  571. data/lib/htm/mcp/cli.rb +0 -583
  572. data/lib/htm/tasks.rb +0 -79
  573. data/lib/tasks/db.rake +0 -15
  574. data/lib/tasks/doc.rake +0 -301
  575. data/lib/tasks/files.rake +0 -285
  576. data/lib/tasks/htm.rake +0 -703
  577. data/lib/tasks/jobs.rake +0 -429
  578. data/lib/tasks/tags.rake +0 -184
  579. data/scripts/backfill_parent_tags.rb +0 -376
  580. data/scripts/normalize_plural_tags.rb +0 -335
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "working_memory/entry"
4
+ require_relative "working_memory/store"
5
+
3
6
  class HTM
4
7
  # Working Memory - Token-limited active context for immediate LLM use
5
8
  #
@@ -7,19 +10,43 @@ class HTM
7
10
  # When full, it evicts less important or older nodes back to long-term storage.
8
11
  #
9
12
  # Thread Safety: All public methods are protected by a mutex to ensure
10
- # safe concurrent access from multiple threads.
13
+ # safe concurrent access from multiple threads. The node bookkeeping
14
+ # itself lives in {Store}, which is not thread-safe on its own.
11
15
  #
12
16
  class WorkingMemory
13
17
  attr_reader :max_tokens
14
18
 
19
+ # Values of entries, in order, that fit within a token budget. Stops at
20
+ # the first entry that would exceed it.
21
+ #
22
+ # @param entries [Array<Entry>] Ordered entries
23
+ # @param budget [Integer] Maximum total tokens
24
+ # @return [Array<String>] Entry values
25
+ #
26
+ def self.fit_to_budget(entries, budget)
27
+ used = 0
28
+ entries.take_while { (used += it.token_count) <= budget }.map(&:value)
29
+ end
30
+
31
+ # How many leading token counts it takes to reach a target. Counts are
32
+ # taken until their sum is at least the target.
33
+ #
34
+ # @param counts [Array<Integer>] Token counts, in eviction order
35
+ # @param target [Integer] Tokens needed
36
+ # @return [Integer] Number of leading counts to take
37
+ #
38
+ def self.count_to_reach(counts, target)
39
+ freed = 0
40
+ counts.take_while { freed < target && (freed += it) }.size
41
+ end
42
+
15
43
  # Initialize working memory
16
44
  #
17
45
  # @param max_tokens [Integer] Maximum tokens allowed in working memory
18
46
  #
19
47
  def initialize(max_tokens:)
20
48
  @max_tokens = max_tokens
21
- @nodes = {}
22
- @access_order = []
49
+ @store = Store.new
23
50
  @mutex = Mutex.new
24
51
  end
25
52
 
@@ -29,22 +56,22 @@ class HTM
29
56
  # @param value [String] Node content
30
57
  # @param token_count [Integer] Number of tokens in this node
31
58
  # @param access_count [Integer] Access count from long-term memory (default: 0)
32
- # @param last_accessed [Time, nil] Last access time from long-term memory
33
- # @param from_recall [Boolean] Whether this node was recalled from long-term memory
34
59
  # @return [void]
35
60
  #
36
- def add(key, value, token_count:, access_count: 0, last_accessed: nil, from_recall: false)
37
- @mutex.synchronize do
38
- @nodes[key] = {
39
- value: value,
40
- token_count: token_count,
41
- access_count: access_count,
42
- last_accessed: last_accessed || Time.now,
43
- added_at: Time.now,
44
- from_recall: from_recall
45
- }
46
- update_access_unlocked(key)
47
- end
61
+ def add(key, value, token_count:, access_count: 0)
62
+ now = Time.now
63
+ add_entry(key, Entry.new(value:, token_count:, access_count:, last_accessed: now, added_at: now, origin: :local))
64
+ end
65
+
66
+ # Add a prepared entry, such as one recalled from long-term memory
67
+ # (see {Entry.recalled})
68
+ #
69
+ # @param key [Object] Node identifier
70
+ # @param entry [Entry] The node
71
+ # @return [void]
72
+ #
73
+ def add_entry(key, entry)
74
+ @mutex.synchronize { @store.put(key, entry) }
48
75
  end
49
76
 
50
77
  # Remove a node from working memory
@@ -53,10 +80,7 @@ class HTM
53
80
  # @return [void]
54
81
  #
55
82
  def remove(key)
56
- @mutex.synchronize do
57
- @nodes.delete(key)
58
- @access_order.delete(key)
59
- end
83
+ @mutex.synchronize { @store.delete(key) }
60
84
  end
61
85
 
62
86
  # Check if there's space for a node
@@ -65,49 +89,19 @@ class HTM
65
89
  # @return [Boolean] true if space available
66
90
  #
67
91
  def has_space?(token_count)
68
- @mutex.synchronize do
69
- current_tokens_unlocked + token_count <= @max_tokens
70
- end
92
+ @mutex.synchronize { @store.tokens + token_count <= @max_tokens }
71
93
  end
72
94
 
73
95
  # Evict nodes to make space
74
96
  #
75
- # Uses LFU + LRU strategy: Least Frequently Used + Least Recently Used
76
- # Nodes with low access count and old timestamps are evicted first
97
+ # Uses LFU + LRU strategy: Least Frequently Used + Least Recently Used,
98
+ # combining access count and time since last access into one score.
77
99
  #
78
100
  # @param needed_tokens [Integer] Number of tokens needed
79
101
  # @return [Array<Hash>] Evicted nodes
80
102
  #
81
103
  def evict_to_make_space(needed_tokens)
82
- @mutex.synchronize do
83
- evicted = []
84
- tokens_freed = 0
85
-
86
- # Sort by access frequency + recency (lower score = more evictable)
87
- candidates = @nodes.sort_by do |_key, node|
88
- access_frequency = node[:access_count] || 0
89
- time_since_accessed = Time.now - (node[:last_accessed] || node[:added_at])
90
-
91
- # Combined score: lower is more evictable
92
- # Frequently accessed = higher score (keep)
93
- # Recently accessed = higher score (keep)
94
- access_score = Math.log(1 + access_frequency)
95
- recency_score = 1.0 / (1 + (time_since_accessed / 3600.0))
96
-
97
- -(access_score + recency_score) # Negative for ascending sort
98
- end
99
-
100
- candidates.each do |key, node|
101
- break if tokens_freed >= needed_tokens
102
-
103
- evicted << { key: key, value: node[:value] }
104
- tokens_freed += node[:token_count]
105
- @nodes.delete(key)
106
- @access_order.delete(key)
107
- end
108
-
109
- evicted
110
- end
104
+ @mutex.synchronize { @store.evict(needed_tokens) }
111
105
  end
112
106
 
113
107
  # Assemble context string for LLM
@@ -116,24 +110,62 @@ class HTM
116
110
  # - :recent - Most recently accessed (LRU)
117
111
  # - :frequent - Most frequently accessed (LFU)
118
112
  # - :balanced - Combines frequency × recency
119
- # @param max_tokens [Integer, nil] Optional token limit
120
- # @return [String] Assembled context
113
+ # @param max_tokens [Integer] Optional token limit (default: this memory's limit)
114
+ # @return [String] Assembled context. Each node is prefixed with how it
115
+ # is known and when, e.g. "[stated 2026-11-21]" or
116
+ # "[inferred from #88, 2026-11-22, confidence 0.60]" (see
117
+ # HTM::Epistemics.labels). A node retired since it entered working
118
+ # memory (superseded, merged, archived) also gets a note saying so,
119
+ # e.g. "(superseded by #41 on 2026-03-03: moved)".
120
+ #
121
+ def assemble_context(strategy:, max_tokens: @max_tokens)
122
+ pairs = @mutex.synchronize { @store.ordered_pairs(strategy) }
123
+ klass = self.class
124
+ prefixes = klass.context_prefixes(pairs.map(&:first))
125
+ entries = pairs.map do |key, entry|
126
+ prefix = prefixes.filter_map { it[key] }
127
+ prefix.empty? ? entry : entry.with(value: [*prefix, entry.value].join(' '))
128
+ end
129
+ klass.fit_to_budget(entries, max_tokens).join("\n\n")
130
+ end
131
+
132
+ # The notes assemble_context puts before each node's text
121
133
  #
122
- def assemble_context(strategy:, max_tokens: nil)
123
- @mutex.synchronize do
124
- max = max_tokens || @max_tokens
125
- nodes = sorted_nodes_by_strategy(strategy)
134
+ # @param keys [Array] working-memory keys (node ids)
135
+ # @return [Array<Hash>] knowledge_labels and retirement_notes for +keys+
136
+ #
137
+ def self.context_prefixes(keys) = [knowledge_labels(keys), retirement_notes(keys)]
126
138
 
127
- context_parts = []
128
- current_tokens = 0
129
- nodes.each do |node|
130
- break if current_tokens + node[:token_count] > max
131
- context_parts << node[:value]
132
- current_tokens += node[:token_count]
133
- end
139
+ # Epistemic labels for the nodes among +keys+ (node ids); empty when
140
+ # there are none or the database cannot be read
141
+ #
142
+ # @param keys [Array] working memory keys
143
+ # @return [Hash{Integer => String}]
144
+ #
145
+ def self.knowledge_labels(keys)
146
+ ids = keys.grep(Integer)
147
+ return {} if ids.empty?
134
148
 
135
- context_parts.join("\n\n")
136
- end
149
+ HTM::Epistemics.labels(ids)
150
+ rescue StandardError => e
151
+ HTM.logger.debug "WorkingMemory: no knowledge labels (#{e.class}: #{e.message})"
152
+ {}
153
+ end
154
+
155
+ # Timeline notes for the retired nodes among +keys+ (node ids); empty
156
+ # when there are none or the database cannot be read
157
+ #
158
+ # @param keys [Array] working memory keys
159
+ # @return [Hash{Integer => String}]
160
+ #
161
+ def self.retirement_notes(keys)
162
+ ids = keys.grep(Integer)
163
+ return {} if ids.empty?
164
+
165
+ HTM::Timeline.retirement_notes(ids)
166
+ rescue StandardError => e
167
+ HTM.logger.debug "WorkingMemory: no retirement notes (#{e.class}: #{e.message})"
168
+ {}
137
169
  end
138
170
 
139
171
  # Get current token count
@@ -141,29 +173,21 @@ class HTM
141
173
  # @return [Integer] Total tokens in working memory
142
174
  #
143
175
  def token_count
144
- @mutex.synchronize do
145
- current_tokens_unlocked
146
- end
176
+ @mutex.synchronize { @store.tokens }
147
177
  end
148
178
 
149
179
  # Get utilization percentage
150
180
  #
151
181
  # @return [Float] Percentage of working memory used
152
182
  #
153
- def utilization_percentage
154
- @mutex.synchronize do
155
- (current_tokens_unlocked.to_f / @max_tokens * 100).round(2)
156
- end
157
- end
183
+ def utilization_percentage = (token_count.to_f / @max_tokens * 100).round(2)
158
184
 
159
185
  # Get node count
160
186
  #
161
187
  # @return [Integer] Number of nodes in working memory
162
188
  #
163
189
  def node_count
164
- @mutex.synchronize do
165
- @nodes.size
166
- end
190
+ @mutex.synchronize { @store.size }
167
191
  end
168
192
 
169
193
  # Clear all nodes from working memory
@@ -171,10 +195,7 @@ class HTM
171
195
  # @return [void]
172
196
  #
173
197
  def clear
174
- @mutex.synchronize do
175
- @nodes.clear
176
- @access_order.clear
177
- end
198
+ @mutex.synchronize { @store.clear }
178
199
  end
179
200
 
180
201
  # ===========================================================================
@@ -193,21 +214,11 @@ class HTM
193
214
  # @return [void]
194
215
  #
195
216
  def add_from_sync(id:, content:, token_count:, created_at:)
196
- @mutex.synchronize do
197
- key = id.to_s
198
- return if @nodes.key?(key) # Already have this node
199
-
200
- @nodes[key] = {
201
- value: content,
202
- token_count: token_count,
203
- access_count: 0,
204
- last_accessed: Time.now,
205
- added_at: created_at,
206
- from_recall: false,
207
- from_sync: true
208
- }
209
- update_access_unlocked(key)
210
- end
217
+ # Key on the integer node id, as HTM#add_to_working_memory does
218
+ key = Integer(id)
219
+ entry = Entry.new(value: content, token_count:, access_count: 0,
220
+ last_accessed: Time.now, added_at: created_at, origin: :sync)
221
+ @mutex.synchronize { @store.put(key, entry) unless @store.key?(key) }
211
222
  end
212
223
 
213
224
  # Remove a node from sync notification
@@ -217,13 +228,7 @@ class HTM
217
228
  # @param node_id [Integer] Node database ID
218
229
  # @return [void]
219
230
  #
220
- def remove_from_sync(node_id)
221
- @mutex.synchronize do
222
- key = node_id.to_s
223
- @nodes.delete(key)
224
- @access_order.delete(key)
225
- end
226
- end
231
+ def remove_from_sync(node_id) = remove(Integer(node_id))
227
232
 
228
233
  # Clear all nodes from sync notification
229
234
  #
@@ -231,42 +236,35 @@ class HTM
231
236
  #
232
237
  # @return [void]
233
238
  #
234
- def clear_from_sync
235
- @mutex.synchronize do
236
- @nodes.clear
237
- @access_order.clear
238
- end
239
- end
240
-
241
- private
239
+ def clear_from_sync = clear
242
240
 
243
- def sorted_nodes_by_strategy(strategy)
244
- case strategy
245
- when :recent
246
- @access_order.reverse.map { |k| @nodes[k]&.dup }.compact
247
- when :frequent
248
- @nodes.sort_by { |_k, v| -(v[:access_count] || 0) }.map { |_, v| v.dup }
249
- when :balanced
250
- sorted = @nodes.sort_by do |_k, v|
251
- freq = v[:access_count] || 0
252
- age = Time.now - (v[:last_accessed] || v[:added_at])
253
- -(Math.log(1 + freq) * (1.0 / (1 + (age / 3600.0))))
254
- end
255
- sorted.map { |_, v| v.dup }
256
- else
257
- raise ArgumentError, "Unknown strategy: #{strategy}. Use :recent, :frequent, or :balanced"
241
+ # Refill from the database: the nodes it marks as in +robot_id+'s
242
+ # working memory, oldest first, while they fit the token budget. A new
243
+ # process (the MCP server, the command line) calls this to pick up the
244
+ # context a robot built up earlier.
245
+ #
246
+ # @param robot_id [Integer]
247
+ # @return [Integer] nodes now in working memory
248
+ #
249
+ def restore(robot_id)
250
+ self.class.restorable_entries(robot_id).each do |entry|
251
+ add_from_sync(**entry) if has_space?(entry[:token_count])
258
252
  end
253
+ node_count
259
254
  end
260
255
 
261
- # Internal unlocked version - must be called within @mutex.synchronize
262
- def current_tokens_unlocked
263
- @nodes.values.sum { |n| n[:token_count] }
264
- end
265
-
266
- # Internal unlocked version - must be called within @mutex.synchronize
267
- def update_access_unlocked(key)
268
- @access_order.delete(key)
269
- @access_order << key
256
+ # The nodes a robot's working memory held, as add_from_sync arguments,
257
+ # least recently remembered first
258
+ #
259
+ # @param robot_id [Integer]
260
+ # @return [Array<Hash>] { id:, content:, token_count:, created_at: }
261
+ #
262
+ def self.restorable_entries(robot_id)
263
+ HTM::Models::RobotNode.where(robot_id:).in_working_memory
264
+ .eager(:node).order(:last_remembered_at).all
265
+ .filter_map(&:node).map do |node|
266
+ { id: node.id, content: node.content, token_count: node.token_count.to_i, created_at: node.created_at }
267
+ end
270
268
  end
271
269
  end
272
270
  end
@@ -1,4 +1,3 @@
1
- # examples/robot_groups/lib/htm/working_memory_channel.rb
2
1
  # frozen_string_literal: true
3
2
 
4
3
  class HTM
@@ -38,9 +37,56 @@ class HTM
38
37
  # @return [String]
39
38
  CHANNEL_PREFIX = 'htm_wm'
40
39
 
41
- # Number of notifications received since channel was created
40
+ # PostgreSQL identifier limit (NAMEDATALEN - 1); pg_notify rejects longer channels
41
+ # @return [Integer]
42
+ MAX_CHANNEL_BYTES = 63
43
+
44
+ # Longest group name that fits in a channel name
42
45
  # @return [Integer]
43
- attr_reader :notifications_received
46
+ MAX_GROUP_NAME_LENGTH = MAX_CHANNEL_BYTES - CHANNEL_PREFIX.length - 1
47
+
48
+ # Thread-safe registry of change callbacks. Decodes each notification
49
+ # payload, counts it, and passes it to every registered callback.
50
+ class Subscribers
51
+ # Number of notifications dispatched so far
52
+ # @return [Integer]
53
+ attr_reader :received
54
+
55
+ def initialize
56
+ @callbacks = []
57
+ @received = 0
58
+ @mutex = Mutex.new
59
+ end
60
+
61
+ # Registers a callback for (event, node_id, robot_id)
62
+ #
63
+ # @return [void]
64
+ #
65
+ def add(callback)
66
+ @mutex.synchronize { @callbacks << callback }
67
+ end
68
+
69
+ # Decodes a JSON notification payload and calls every callback with it.
70
+ # Logs and ignores a payload that is not valid JSON.
71
+ #
72
+ # @param payload [String] JSON payload from pg_notify
73
+ # @return [void]
74
+ #
75
+ def dispatch(payload)
76
+ data = JSON.parse(payload, symbolize_names: true)
77
+ args = [data[:event].to_sym, data[:node_id], data[:robot_id]]
78
+
79
+ @mutex.synchronize do
80
+ @received += 1
81
+ @callbacks.each { it.call(*args) }
82
+ end
83
+ rescue JSON::ParserError => e
84
+ HTM.logger.error "Invalid notification payload: #{e.message}"
85
+ end
86
+ end
87
+
88
+ # Thread-local key the listener thread checks to know it should stop
89
+ STOP_KEY = :htm_wm_stop_requested
44
90
 
45
91
  # Creates a new working memory channel for a robot group.
46
92
  #
@@ -54,22 +100,30 @@ class HTM
54
100
  # @option db_config [String] :dbname Database name
55
101
  # @option db_config [String] :user Database user
56
102
  # @option db_config [String] :password Database password (optional)
103
+ # @raise [ArgumentError] if the group name is longer than {MAX_GROUP_NAME_LENGTH} characters
57
104
  #
58
105
  # @example
59
106
  # db_config = { host: 'localhost', port: 5432, dbname: 'htm_dev', user: 'postgres' }
60
107
  # channel = HTM::WorkingMemoryChannel.new('customer-support', db_config)
61
108
  #
62
109
  def initialize(group_name, db_config)
63
- @group_name = group_name
64
- @channel = "#{CHANNEL_PREFIX}_#{group_name.gsub(/[^a-z0-9_]/i, '_')}"
65
- @db_config = db_config
66
- @listeners = []
67
- @listen_thread = nil
68
- @stop_requested = false
69
- @notifications_received = 0
70
- @mutex = Mutex.new
110
+ @channel = "#{CHANNEL_PREFIX}_#{group_name.gsub(/[^a-z0-9_]/i, '_')}"
111
+ if @channel.bytesize > MAX_CHANNEL_BYTES
112
+ raise ArgumentError,
113
+ "Robot group name is too long (#{group_name.length} characters); " \
114
+ "the maximum is #{MAX_GROUP_NAME_LENGTH} so the PostgreSQL channel name fits in #{MAX_CHANNEL_BYTES} bytes"
115
+ end
116
+ @db_config = db_config
117
+ @subscribers = Subscribers.new
118
+ @listen_thread = nil
71
119
  end
72
120
 
121
+ # Number of notifications received since channel was created
122
+ #
123
+ # @return [Integer]
124
+ #
125
+ def notifications_received = @subscribers.received
126
+
73
127
  # @!group Publishing
74
128
 
75
129
  # Broadcasts a working memory change notification to all listeners.
@@ -122,7 +176,7 @@ class HTM
122
176
  # end
123
177
  #
124
178
  def on_change(&callback)
125
- @mutex.synchronize { @listeners << callback }
179
+ @subscribers.add(callback)
126
180
  end
127
181
 
128
182
  # Starts listening for notifications in a background thread.
@@ -138,10 +192,7 @@ class HTM
138
192
  # puts "Listening: #{channel.listening?}" # => true
139
193
  #
140
194
  def start_listening
141
- @stop_requested = false
142
- @listen_thread = Thread.new do
143
- listen_loop
144
- end
195
+ @listen_thread = Thread.new { listen_loop }
145
196
  @listen_thread.abort_on_exception = true
146
197
  @listen_thread
147
198
  end
@@ -159,11 +210,21 @@ class HTM
159
210
  # puts "Listening: #{channel.listening?}" # => false
160
211
  #
161
212
  def stop_listening
162
- @stop_requested = true
163
- # Give the thread a moment to exit cleanly
164
- @listen_thread&.join(0.5)
165
- @listen_thread&.kill if @listen_thread&.alive?
213
+ thread = @listen_thread
166
214
  @listen_thread = nil
215
+ self.class.stop_thread(thread) if thread
216
+ end
217
+
218
+ # Asks a listener thread to stop, waits up to 0.5 seconds for it to exit
219
+ # cleanly, then kills it if it is still running.
220
+ #
221
+ # @param thread [Thread] Listener thread started by {#start_listening}
222
+ # @return [void]
223
+ #
224
+ def self.stop_thread(thread)
225
+ thread[STOP_KEY] = true
226
+ thread.join(0.5)
227
+ thread.kill if thread.alive?
167
228
  end
168
229
 
169
230
  # @!endgroup
@@ -207,14 +268,14 @@ class HTM
207
268
  conn = PG.connect(@db_config)
208
269
  conn.exec("LISTEN #{conn.escape_identifier(@channel)}")
209
270
 
210
- until @stop_requested
211
- # Wait for notification with timeout (allows checking @stop_requested)
271
+ until stop_requested?
272
+ # Wait for notification with timeout (allows checking for a stop request)
212
273
  conn.wait_for_notify(0.5) do |_channel, _pid, payload|
213
- handle_notification(payload)
274
+ @subscribers.dispatch(payload)
214
275
  end
215
276
  end
216
277
  rescue PG::Error => e
217
- unless @stop_requested
278
+ unless stop_requested?
218
279
  HTM.logger.error "WorkingMemoryChannel error: #{e.message}"
219
280
  sleep 1
220
281
  retry
@@ -223,22 +284,11 @@ class HTM
223
284
  conn&.close
224
285
  end
225
286
 
226
- def handle_notification(payload)
227
- data = JSON.parse(payload, symbolize_names: true)
228
-
229
- @mutex.synchronize do
230
- @notifications_received += 1
231
- @listeners.each do |callback|
232
- callback.call(
233
- data[:event].to_sym,
234
- data[:node_id],
235
- data[:robot_id]
236
- )
237
- end
238
- end
239
- rescue JSON::ParserError => e
240
- HTM.logger.error "Invalid notification payload: #{e.message}"
241
- end
287
+ # Whether {#stop_listening} has asked the current listener thread to stop
288
+ #
289
+ # @return [Boolean]
290
+ #
291
+ def stop_requested? = Thread.current[STOP_KEY] == true
242
292
 
243
293
  def with_connection
244
294
  conn = PG.connect(@db_config)