htm 0.0.31 → 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.
- checksums.yaml +4 -4
- data/.architecture/decisions/adrs/005-rag-based-retrieval-with-hybrid-search.md +4 -0
- data/.architecture/decisions/adrs/017-bitemporal-event-time.md +78 -0
- data/.architecture/decisions/adrs/018-memory-timelines-and-node-links.md +64 -0
- data/.architecture/decisions/adrs/019-epistemic-status.md +66 -0
- data/.claude.json +11 -0
- data/.envrc +9 -7
- data/.irbrc +16 -17
- data/.reek.yml +104 -0
- data/.rubocop.yml +173 -0
- data/.ruby-version +1 -0
- data/CHANGELOG.md +162 -54
- data/README.md +24 -17
- data/SETUP.md +49 -46
- data/_typos.toml +17 -0
- data/bin/htm +18 -0
- data/db/migrate/00008_create_node_relationships.rb +54 -0
- data/db/migrate/00009_fix_node_relationships_column_types.rb +17 -0
- data/db/migrate/00010_convert_embedding_to_sparsevec.rb +47 -0
- data/db/migrate/00011_strip_frontmatter_from_chunks.rb +66 -0
- data/db/migrate/00012_add_event_time_to_nodes.rb +110 -0
- data/db/migrate/00013_create_node_links.rb +158 -0
- data/db/migrate/00014_add_epistemic_status.rb +110 -0
- data/db/schema.sql +361 -7
- data/db/seed_data/README.md +11 -11
- data/db/seeds.rb +11 -11
- data/docs/api/database.md +43 -65
- data/docs/api/embedding-service.md +139 -263
- data/docs/api/htm.md +128 -12
- data/docs/api/index.md +34 -23
- data/docs/api/long-term-memory.md +8 -19
- data/docs/api/working-memory.md +42 -54
- data/docs/api/yard/HTM/Admin/Console.md +53 -0
- data/docs/api/yard/HTM/Admin/DatabaseCommands/Console.md +38 -0
- data/docs/api/yard/HTM/Admin/DatabaseCommands.md +127 -0
- data/docs/api/yard/HTM/Admin/EnrichCommands.md +85 -0
- data/docs/api/yard/HTM/Admin/Error.md +9 -0
- data/docs/api/yard/HTM/Admin/FileCommands/Console.md +50 -0
- data/docs/api/yard/HTM/Admin/FileCommands.md +83 -0
- data/docs/api/yard/HTM/Admin/MemoryCommands/Base.md +17 -0
- data/docs/api/yard/HTM/Admin/MemoryCommands/Edit.md +74 -0
- data/docs/api/yard/HTM/Admin/MemoryCommands/Search.md +77 -0
- data/docs/api/yard/HTM/Admin/MemoryCommands/TagSearch.md +46 -0
- data/docs/api/yard/HTM/Admin/MemoryCommands/WorkingMemory.md +36 -0
- data/docs/api/yard/HTM/Admin/MemoryCommands.md +67 -0
- data/docs/api/yard/HTM/Admin/TagCommands/Console.md +48 -0
- data/docs/api/yard/HTM/Admin/TagCommands.md +105 -0
- data/docs/api/yard/HTM/Admin/TagGraph.md +149 -0
- data/docs/api/yard/HTM/Admin/YardDocs.md +60 -0
- data/docs/api/yard/HTM/Admin.md +102 -0
- data/docs/api/yard/HTM/AuthorizationError.md +6 -6
- data/docs/api/yard/HTM/CLI/ConfigFile.md +40 -0
- data/docs/api/yard/HTM/CLI/Db.md +63 -0
- data/docs/api/yard/HTM/CLI/Enrich.md +39 -0
- data/docs/api/yard/HTM/CLI/ErrorSuggestion.md +56 -0
- data/docs/api/yard/HTM/CLI/Files.md +36 -0
- data/docs/api/yard/HTM/CLI/Group/ClassMethods.md +11 -0
- data/docs/api/yard/HTM/CLI/Group.md +13 -0
- data/docs/api/yard/HTM/CLI/MemoryCommand/ClassMethods.md +20 -0
- data/docs/api/yard/HTM/CLI/MemoryCommand.md +9 -0
- data/docs/api/yard/HTM/CLI/Robots.md +31 -0
- data/docs/api/yard/HTM/CLI/Support.md +9 -0
- data/docs/api/yard/HTM/CLI/Tags.md +57 -0
- data/docs/api/yard/HTM/CLI/WorkingMemory.md +24 -0
- data/docs/api/yard/HTM/CLI.md +84 -0
- data/docs/api/yard/HTM/CircuitBreaker/Guarded.md +29 -0
- data/docs/api/yard/HTM/CircuitBreaker/Settings.md +21 -0
- data/docs/api/yard/HTM/CircuitBreaker/Status.md +42 -0
- data/docs/api/yard/HTM/CircuitBreaker.md +54 -49
- data/docs/api/yard/HTM/CircuitBreakerOpenError.md +9 -9
- data/docs/api/yard/HTM/Config/Builder.md +87 -0
- data/docs/api/yard/HTM/Config/Coercion.md +59 -0
- data/docs/api/yard/HTM/Config/Database.md +102 -0
- data/docs/api/yard/HTM/Config/Readers.md +30 -0
- data/docs/api/yard/HTM/Config/RubyLlmSettings.md +32 -0
- data/docs/api/yard/HTM/Config/Validator.md +59 -0
- data/docs/api/yard/HTM/Config.md +224 -105
- data/docs/api/yard/HTM/ConfigurationError.md +20 -0
- data/docs/api/yard/HTM/Confirmation.md +22 -0
- data/docs/api/yard/HTM/Database/Connection.md +26 -0
- data/docs/api/yard/HTM/Database/Migrations.md +32 -0
- data/docs/api/yard/HTM/Database/Report.md +26 -0
- data/docs/api/yard/HTM/Database/SchemaFile.md +52 -0
- data/docs/api/yard/HTM/Database/Teardown.md +15 -0
- data/docs/api/yard/HTM/Database.md +58 -70
- data/docs/api/yard/HTM/DatabaseDocs.md +67 -0
- data/docs/api/yard/HTM/DatabaseError.md +6 -6
- data/docs/api/yard/HTM/Deletion.md +32 -0
- data/docs/api/yard/HTM/EmbeddingError.md +6 -6
- data/docs/api/yard/HTM/EmbeddingService.md +37 -38
- data/docs/api/yard/HTM/Epistemics.md +135 -0
- data/docs/api/yard/HTM/Error.md +6 -6
- data/docs/api/yard/HTM/EventTime.md +110 -0
- data/docs/api/yard/HTM/FileMemory.md +76 -0
- data/docs/api/yard/HTM/InputValidator.md +82 -0
- data/docs/api/yard/HTM/JobAdapter/Job.md +26 -0
- data/docs/api/yard/HTM/JobAdapter.md +35 -16
- data/docs/api/yard/HTM/Jobs/FailureLogging.md +14 -0
- data/docs/api/yard/HTM/Jobs/GenerateEmbeddingJob.md +16 -0
- data/docs/api/yard/HTM/Jobs/GeneratePropositionsJob.md +17 -0
- data/docs/api/yard/HTM/Jobs/GenerateRelationshipsJob.md +26 -0
- data/docs/api/yard/HTM/Jobs/GenerateTagsJob.md +17 -0
- data/docs/api/yard/HTM/Jobs/LlmCallTimer.md +58 -0
- data/docs/api/yard/HTM/Jobs/NodeLookup.md +14 -0
- data/docs/api/yard/HTM/Jobs.md +13 -0
- data/docs/api/yard/HTM/Loaders/ChunkSync/Chunk.md +22 -0
- data/docs/api/yard/HTM/Loaders/ChunkSync.md +50 -0
- data/docs/api/yard/HTM/Loaders/MarkdownChunker/Coalescer.md +24 -0
- data/docs/api/yard/HTM/Loaders/MarkdownChunker/Packer.md +20 -0
- data/docs/api/yard/HTM/Loaders/MarkdownChunker/Splitter.md +18 -0
- data/docs/api/yard/HTM/Loaders/MarkdownChunker.md +83 -0
- data/docs/api/yard/HTM/Loaders/MarkdownLoader/Document.md +43 -0
- data/docs/api/yard/HTM/Loaders/MarkdownLoader.md +62 -0
- data/docs/api/yard/HTM/Loaders.md +5 -0
- data/docs/api/yard/HTM/LongTermMemory/FulltextSearch.md +36 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfMerger.md +25 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfRows.md +30 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfSql/Query.md +79 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfSql/Source.md +45 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch/RrfSql.md +11 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch/TagDepth.md +52 -0
- data/docs/api/yard/HTM/LongTermMemory/HybridSearch.md +52 -0
- data/docs/api/yard/HTM/LongTermMemory/NodeOperations.md +95 -0
- data/docs/api/yard/HTM/LongTermMemory/RelevanceScorer/HierarchicalJaccard.md +58 -0
- data/docs/api/yard/HTM/LongTermMemory/RelevanceScorer/TagSearch.md +27 -0
- data/docs/api/yard/HTM/LongTermMemory/RelevanceScorer.md +81 -0
- data/docs/api/yard/HTM/LongTermMemory/RobotOperations.md +22 -0
- data/docs/api/yard/HTM/LongTermMemory/TagOperations/ExpiringValue.md +24 -0
- data/docs/api/yard/HTM/LongTermMemory/TagOperations/TagMatchSql.md +40 -0
- data/docs/api/yard/HTM/LongTermMemory/TagOperations.md +129 -0
- data/docs/api/yard/HTM/LongTermMemory/VectorSearch.md +30 -0
- data/docs/api/yard/HTM/LongTermMemory.md +279 -31
- data/docs/api/yard/HTM/MCP/AssembleContextTool.md +16 -0
- data/docs/api/yard/HTM/MCP/ClearGroupWorkingMemoryTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ClearWorkingMemoryTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ConfigResource.md +12 -0
- data/docs/api/yard/HTM/MCP/ConfirmTool.md +12 -0
- data/docs/api/yard/HTM/MCP/CreateGroupTool.md +12 -0
- data/docs/api/yard/HTM/MCP/EnrichPendingTool.md +16 -0
- data/docs/api/yard/HTM/MCP/ExtractPropositionsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/FailoverTool.md +12 -0
- data/docs/api/yard/HTM/MCP/FileInfoTool.md +13 -0
- data/docs/api/yard/HTM/MCP/FileSourcesResource.md +12 -0
- data/docs/api/yard/HTM/MCP/FileSupport.md +7 -0
- data/docs/api/yard/HTM/MCP/FindByTopicTool.md +12 -0
- data/docs/api/yard/HTM/MCP/FirstMentionTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ForgetContentTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ForgetTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GetGroupStatusTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GetGroupWorkingMemoryTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GetNodeTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GetRobotTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GetWorkingMemoryTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GroupRecallTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GroupRememberTool.md +12 -0
- data/docs/api/yard/HTM/MCP/GroupSession.md +23 -0
- data/docs/api/yard/HTM/MCP/JoinGroupTool.md +12 -0
- data/docs/api/yard/HTM/MCP/LeaveGroupTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ListDeletedTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ListFilesTool.md +13 -0
- data/docs/api/yard/HTM/MCP/ListGroupsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ListRobotsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ListTagsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/LoadDirectoryTool.md +13 -0
- data/docs/api/yard/HTM/MCP/LoadFileTool.md +13 -0
- data/docs/api/yard/HTM/MCP/MemoryStatsResource.md +13 -0
- data/docs/api/yard/HTM/MCP/PopularTagsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/PromoteRobotTool.md +12 -0
- data/docs/api/yard/HTM/MCP/PurgeDeletedTool.md +12 -0
- data/docs/api/yard/HTM/MCP/RecallTool.md +16 -0
- data/docs/api/yard/HTM/MCP/RecentMemoriesResource.md +13 -0
- data/docs/api/yard/HTM/MCP/RelatedNodesTool.md +12 -0
- data/docs/api/yard/HTM/MCP/RememberTool.md +12 -0
- data/docs/api/yard/HTM/MCP/RestoreTool.md +12 -0
- data/docs/api/yard/HTM/MCP/RobotGroupsResource.md +13 -0
- data/docs/api/yard/HTM/MCP/RobotTeamsStatusTool.md +13 -0
- data/docs/api/yard/HTM/MCP/RunRobotTeamsTool.md +13 -0
- data/docs/api/yard/HTM/MCP/SearchByTagsTool.md +16 -0
- data/docs/api/yard/HTM/MCP/SearchTagsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/Server.md +37 -0
- data/docs/api/yard/HTM/MCP/Session.md +32 -0
- data/docs/api/yard/HTM/MCP/SetRobotTool.md +12 -0
- data/docs/api/yard/HTM/MCP/ShutdownGroupTool.md +12 -0
- data/docs/api/yard/HTM/MCP/StartupPromptResource.md +16 -0
- data/docs/api/yard/HTM/MCP/StatsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/SyncFilesTool.md +13 -0
- data/docs/api/yard/HTM/MCP/SyncGroupTool.md +12 -0
- data/docs/api/yard/HTM/MCP/TagHierarchyResource.md +16 -0
- data/docs/api/yard/HTM/MCP/TagNodeTool.md +12 -0
- data/docs/api/yard/HTM/MCP/TagTreeTool.md +22 -0
- data/docs/api/yard/HTM/MCP/TeamNames.md +7 -0
- data/docs/api/yard/HTM/MCP/TimelineTool.md +12 -0
- data/docs/api/yard/HTM/MCP/Tool.md +24 -0
- data/docs/api/yard/HTM/MCP/ToolSupport.md +17 -0
- data/docs/api/yard/HTM/MCP/TopicRelationshipsTool.md +12 -0
- data/docs/api/yard/HTM/MCP/TransferWorkingMemoryTool.md +12 -0
- data/docs/api/yard/HTM/MCP/UnloadFileTool.md +13 -0
- data/docs/api/yard/HTM/MCP/UntagNodeTool.md +12 -0
- data/docs/api/yard/HTM/MCP.md +30 -0
- data/docs/api/yard/HTM/Migration.md +44 -0
- data/docs/api/yard/HTM/Models/FileSource.md +66 -0
- data/docs/api/yard/HTM/Models/Node/Scopes.md +74 -0
- data/docs/api/yard/HTM/Models/Node/SoftDeletion.md +22 -0
- data/docs/api/yard/HTM/Models/Node/VectorSimilarity.md +28 -0
- data/docs/api/yard/HTM/Models/Node.md +113 -0
- data/docs/api/yard/HTM/Models/NodeLink.md +65 -0
- data/docs/api/yard/HTM/Models/NodeRelationship.md +31 -0
- data/docs/api/yard/HTM/Models/NodeTag.md +38 -0
- data/docs/api/yard/HTM/Models/Robot.md +50 -0
- data/docs/api/yard/HTM/Models/RobotNode.md +35 -0
- data/docs/api/yard/HTM/Models/Tag/Scopes.md +32 -0
- data/docs/api/yard/HTM/Models/Tag.md +112 -0
- data/docs/api/yard/HTM/Models.md +5 -0
- data/docs/api/yard/HTM/NodeEnrichment.md +36 -0
- data/docs/api/yard/HTM/NodeView.md +113 -0
- data/docs/api/yard/HTM/NotFoundError.md +6 -5
- data/docs/api/yard/HTM/Observability.md +58 -40
- data/docs/api/yard/HTM/PropositionError.md +6 -6
- data/docs/api/yard/HTM/PropositionService.md +63 -29
- data/docs/api/yard/HTM/QueryCache/KeyNormalizer.md +25 -0
- data/docs/api/yard/HTM/QueryCache/NullStore.md +19 -0
- data/docs/api/yard/HTM/QueryCache/Store.md +43 -0
- data/docs/api/yard/HTM/QueryCache.md +41 -46
- data/docs/api/yard/HTM/QueryTimeoutError.md +9 -8
- data/docs/api/yard/HTM/Railtie.md +11 -7
- data/docs/api/yard/HTM/RecallQuery.md +111 -0
- data/docs/api/yard/HTM/ResourceExhaustedError.md +6 -6
- data/docs/api/yard/HTM/RobotGroup/CacheSync.md +35 -0
- data/docs/api/yard/HTM/RobotGroup/Membership.md +96 -0
- data/docs/api/yard/HTM/RobotGroup/TransferOptions.md +14 -0
- data/docs/api/yard/HTM/RobotGroup/WorkingMemoryLedger.md +65 -0
- data/docs/api/yard/HTM/RobotGroup.md +116 -360
- data/docs/api/yard/HTM/Robots/Actions/TagMove.md +31 -0
- data/docs/api/yard/HTM/Robots/Actions.md +153 -0
- data/docs/api/yard/HTM/Robots/Neighbors.md +20 -0
- data/docs/api/yard/HTM/Robots/Supervisor/Idler.md +26 -0
- data/docs/api/yard/HTM/Robots/Supervisor/Roster.md +26 -0
- data/docs/api/yard/HTM/Robots/Supervisor.md +42 -0
- data/docs/api/yard/HTM/Robots/Team.md +60 -0
- data/docs/api/yard/HTM/Robots/Teams/Archivist.md +43 -0
- data/docs/api/yard/HTM/Robots/Teams/Consolidator.md +29 -0
- data/docs/api/yard/HTM/Robots/Teams/ContradictionDetector.md +33 -0
- data/docs/api/yard/HTM/Robots/Teams/TagCurator.md +37 -0
- data/docs/api/yard/HTM/Robots/Teams.md +5 -0
- data/docs/api/yard/HTM/Robots/Tools/ArchiveNodes.md +12 -0
- data/docs/api/yard/HTM/Robots/Tools/Base.md +16 -0
- data/docs/api/yard/HTM/Robots/Tools/MergeNodes.md +12 -0
- data/docs/api/yard/HTM/Robots/Tools/MergeTags.md +12 -0
- data/docs/api/yard/HTM/Robots/Tools/Pass.md +12 -0
- data/docs/api/yard/HTM/Robots/Tools/RecordConflict.md +12 -0
- data/docs/api/yard/HTM/Robots/Tools/SupersedeNode.md +12 -0
- data/docs/api/yard/HTM/Robots/Tools.md +14 -0
- data/docs/api/yard/HTM/Robots.md +72 -0
- data/docs/api/yard/HTM/SearchFilters.md +82 -0
- data/docs/api/yard/HTM/SequelConfig.md +97 -0
- data/docs/api/yard/HTM/Settings.md +39 -0
- data/docs/api/yard/HTM/Sinatra/Helpers.md +37 -0
- data/docs/api/yard/HTM/Sinatra/Middleware.md +29 -0
- data/docs/api/yard/HTM/Sinatra.md +44 -0
- data/docs/api/yard/HTM/SqlBuilder/Sparsevec.md +69 -0
- data/docs/api/yard/HTM/SqlBuilder.md +62 -75
- data/docs/api/yard/HTM/StartupPrompt.md +45 -0
- data/docs/api/yard/HTM/TagError.md +6 -6
- data/docs/api/yard/HTM/TagService.md +100 -37
- data/docs/api/yard/HTM/TagTree/Branch.md +43 -0
- data/docs/api/yard/HTM/TagTree/SvgRenderer/Layout.md +51 -0
- data/docs/api/yard/HTM/TagTree/SvgRenderer.md +25 -0
- data/docs/api/yard/HTM/TagTree.md +65 -0
- data/docs/api/yard/HTM/Telemetry/NullInstrument.md +12 -9
- data/docs/api/yard/HTM/Telemetry/NullMeter.md +17 -9
- data/docs/api/yard/HTM/Telemetry.md +53 -50
- data/docs/api/yard/HTM/Timeframe/Result.md +13 -16
- data/docs/api/yard/HTM/Timeframe.md +17 -20
- data/docs/api/yard/HTM/TimeframeExtractor/Patterns.md +18 -0
- data/docs/api/yard/HTM/TimeframeExtractor/Result.md +13 -16
- data/docs/api/yard/HTM/TimeframeExtractor.md +27 -16
- data/docs/api/yard/HTM/Timeline.md +113 -0
- data/docs/api/yard/HTM/ValidationError.md +6 -5
- data/docs/api/yard/HTM/Workflows/RememberWorkflow/NodeState.md +73 -0
- data/docs/api/yard/HTM/Workflows/RememberWorkflow.md +80 -0
- data/docs/api/yard/HTM/Workflows.md +5 -0
- data/docs/api/yard/HTM/WorkingMemory/Entry.md +67 -0
- data/docs/api/yard/HTM/WorkingMemory/Store.md +54 -0
- data/docs/api/yard/HTM/WorkingMemory.md +113 -87
- data/docs/api/yard/HTM/WorkingMemoryChannel/Subscribers.md +28 -0
- data/docs/api/yard/HTM/WorkingMemoryChannel.md +108 -102
- data/docs/api/yard/HTM.md +483 -5
- data/docs/api/yard/README.md +211 -0
- data/docs/api/yard/Sinatra/Base.md +30 -0
- data/docs/api/yard/Sinatra.md +7 -0
- data/docs/api/yard/index.csv +1834 -181
- data/docs/api/yard-reference.md +228 -9
- data/docs/architecture/adrs/005-rag-retrieval.md +3 -0
- data/docs/architecture/adrs/index.md +1 -1
- data/docs/architecture/index.md +7 -9
- data/docs/architecture/overview.md +8 -11
- data/docs/assets/images/htm-architecture-overview.svg +1 -1
- data/docs/assets/images/htm-context-assembly-flow.svg +2 -2
- data/docs/assets/images/htm-layered-architecture.svg +3 -3
- data/docs/assets/images/project-structure.svg +2 -2
- data/docs/assets/images/two-tier-memory-architecture.svg +1 -1
- data/docs/database/INDEX.md +113 -0
- data/docs/database/README.md +60 -175
- data/docs/database/file_sources.md +51 -0
- data/docs/database/file_sources.svg +120 -0
- data/docs/database/naming-convention.md +12 -12
- data/docs/database/node_links.md +65 -0
- data/docs/database/node_links.svg +171 -0
- data/docs/database/node_relationships.md +62 -0
- data/docs/database/node_relationships.svg +124 -0
- data/docs/database/node_tags.md +50 -0
- data/docs/database/node_tags.svg +125 -0
- data/docs/database/nodes.md +120 -0
- data/docs/database/nodes.svg +394 -0
- data/docs/database/robot_nodes.md +57 -0
- data/docs/database/robot_nodes.svg +155 -0
- data/docs/database/robots.md +40 -0
- data/docs/database/robots.svg +131 -0
- data/docs/database/schema.svg +384 -275
- data/docs/database/schema_migrations.md +19 -0
- data/docs/database/schema_migrations.svg +31 -0
- data/docs/database/tags.md +47 -0
- data/docs/database/tags.svg +90 -0
- data/docs/development/asgard-tasks.md +114 -0
- data/docs/development/contributing.md +11 -11
- data/docs/development/index.md +19 -24
- data/docs/development/schema.md +113 -14
- data/docs/development/setup.md +99 -151
- data/docs/development/testing.md +58 -66
- data/docs/examples/basic-usage.md +9 -9
- data/docs/examples/config-files.md +8 -8
- data/docs/examples/file-loading.md +16 -16
- data/docs/examples/index.md +15 -8
- data/docs/examples/llm-configuration.md +13 -9
- data/docs/examples/mcp-client.md +61 -59
- data/docs/examples/rails-integration.md +5 -4
- data/docs/examples/sinatra-integration.md +5 -4
- data/docs/examples/standalone-app.md +17 -16
- data/docs/getting-started/index.md +3 -3
- data/docs/getting-started/installation.md +76 -83
- data/docs/getting-started/quick-start.md +28 -26
- data/docs/guides/adding-memories.md +28 -4
- data/docs/guides/cli.md +458 -0
- data/docs/guides/configuration.md +77 -42
- data/docs/guides/context-assembly.md +4 -4
- data/docs/guides/epistemic-status.md +138 -0
- data/docs/guides/event-time.md +106 -0
- data/docs/guides/file-loading.md +36 -32
- data/docs/guides/getting-started.md +23 -19
- data/docs/guides/long-term-memory.md +8 -28
- data/docs/guides/mcp-server.md +416 -173
- data/docs/guides/propositions.md +30 -40
- data/docs/guides/recalling-memories.md +27 -12
- data/docs/guides/robot-teams.md +96 -0
- data/docs/guides/search-strategies.md +10 -7
- data/docs/guides/tags.md +37 -32
- data/docs/guides/timeline.md +106 -0
- data/docs/index.md +7 -7
- data/docs/llms.txt +35 -0
- data/docs/multi_framework_support.md +14 -14
- data/docs/robots/hive-mind.md +1 -1
- data/docs/robots/multi-robot.md +2 -2
- data/docs/robots/robot-groups.md +10 -10
- data/docs/robots/two-tier-memory.md +85 -120
- data/docs/setup_local_database.md +41 -85
- data/examples/00_create_examples_db.rb +20 -7
- data/examples/01_basic_usage.rb +21 -18
- data/examples/02_config_file_example/README.md +13 -12
- data/examples/02_config_file_example/config/htm.local.yml +8 -8
- data/examples/02_config_file_example/show_config.rb +3 -4
- data/examples/03_custom_llm_configuration.rb +13 -12
- data/examples/04_file_loader_usage.rb +16 -21
- data/examples/05_timeframe_demo.rb +283 -234
- data/examples/06_example_app/.loki +36 -0
- data/examples/06_example_app/app.rb +22 -33
- data/examples/07_cli_app/README.md +18 -18
- data/examples/07_cli_app/htm_cli.rb +26 -19
- data/examples/08_sinatra_app/Gemfile +1 -0
- data/examples/08_sinatra_app/Gemfile.lock +101 -67
- data/examples/08_sinatra_app/app.rb +64 -62
- data/examples/09_mcp_client.rb +93 -119
- data/examples/10_telemetry/README.md +3 -3
- data/examples/10_telemetry/SETUP_README.md +2 -2
- data/examples/10_telemetry/demo.rb +6 -5
- data/examples/11_robot_groups/README.md +5 -4
- data/examples/11_robot_groups/lib/robot_worker.rb +0 -5
- data/examples/11_robot_groups/multi_process.rb +6 -4
- data/examples/11_robot_groups/same_process.rb +19 -17
- data/examples/12_rails_app/.envrc +12 -0
- data/examples/12_rails_app/Gemfile +8 -3
- data/examples/12_rails_app/Gemfile.lock +226 -172
- data/examples/12_rails_app/README.md +77 -22
- data/examples/12_rails_app/app/controllers/application_controller.rb +6 -0
- data/examples/12_rails_app/app/controllers/chats_controller.rb +275 -0
- data/examples/12_rails_app/app/controllers/dashboard_controller.rb +3 -0
- data/examples/12_rails_app/app/controllers/files_controller.rb +17 -2
- data/examples/12_rails_app/app/controllers/home_controller.rb +8 -0
- data/examples/12_rails_app/app/controllers/memories_controller.rb +16 -5
- data/examples/12_rails_app/app/controllers/messages_controller.rb +177 -0
- data/examples/12_rails_app/app/controllers/robots_controller.rb +11 -1
- data/examples/12_rails_app/app/controllers/search_controller.rb +7 -2
- data/examples/12_rails_app/app/controllers/tags_controller.rb +14 -1
- data/examples/12_rails_app/app/javascript/application.js +1 -1
- data/examples/12_rails_app/app/models/application_record.rb +5 -0
- data/examples/12_rails_app/app/models/chat.rb +3 -0
- data/examples/12_rails_app/app/models/message.rb +3 -0
- data/examples/12_rails_app/app/views/chats/index.html.erb +61 -0
- data/examples/12_rails_app/app/views/chats/show.html.erb +213 -0
- data/examples/12_rails_app/app/views/dashboard/index.html.erb +3 -0
- data/examples/12_rails_app/app/views/files/index.html.erb +10 -5
- data/examples/12_rails_app/app/views/files/new.html.erb +5 -3
- data/examples/12_rails_app/app/views/files/show.html.erb +19 -3
- data/examples/12_rails_app/app/views/home/index.html.erb +45 -0
- data/examples/12_rails_app/app/views/layouts/application.html.erb +20 -18
- data/examples/12_rails_app/app/views/memories/_memory_card.html.erb +2 -2
- data/examples/12_rails_app/app/views/memories/deleted.html.erb +3 -1
- data/examples/12_rails_app/app/views/memories/edit.html.erb +2 -0
- data/examples/12_rails_app/app/views/memories/index.html.erb +2 -0
- data/examples/12_rails_app/app/views/memories/new.html.erb +14 -0
- data/examples/12_rails_app/app/views/memories/show.html.erb +17 -2
- data/examples/12_rails_app/app/views/messages/_message.html.erb +20 -0
- data/examples/12_rails_app/app/views/robots/index.html.erb +2 -0
- data/examples/12_rails_app/app/views/robots/new.html.erb +2 -0
- data/examples/12_rails_app/app/views/robots/show.html.erb +2 -0
- data/examples/12_rails_app/app/views/search/index.html.erb +77 -10
- data/examples/12_rails_app/app/views/shared/_navbar.html.erb +75 -29
- data/examples/12_rails_app/app/views/tags/index.html.erb +2 -0
- data/examples/12_rails_app/app/views/tags/show.html.erb +3 -1
- data/examples/12_rails_app/config/application.rb +1 -1
- data/examples/12_rails_app/config/database.yml +9 -5
- data/examples/12_rails_app/config/importmap.rb +1 -1
- data/examples/12_rails_app/config/initializers/htm.rb +9 -2
- data/examples/12_rails_app/config/initializers/ruby_llm.rb +29 -0
- data/examples/12_rails_app/config/routes.rb +39 -23
- data/examples/12_rails_app/db/migrate/20261205061932_create_ruby_llm_records.rb +160 -0
- data/examples/12_rails_app/db/migrate/20261205061933_create_chats.rb +13 -0
- data/examples/12_rails_app/db/migrate/20261205061934_create_messages.rb +23 -0
- data/examples/12_rails_app/db/schema.rb +210 -0
- data/examples/README.md +53 -44
- data/examples/examples_helper.rb +52 -3
- data/htm.gemspec +68 -0
- data/lib/htm/admin/database_commands.rb +454 -0
- data/lib/htm/admin/enrich_commands.rb +209 -0
- data/lib/htm/admin/file_commands.rb +323 -0
- data/lib/htm/admin/memory_commands/edit.rb +157 -0
- data/lib/htm/admin/memory_commands/search.rb +178 -0
- data/lib/htm/admin/memory_commands/tag_search.rb +98 -0
- data/lib/htm/admin/memory_commands/text.rb +164 -0
- data/lib/htm/admin/memory_commands/working_memory.rb +71 -0
- data/lib/htm/admin/memory_commands.rb +179 -0
- data/lib/htm/admin/tag_commands.rb +352 -0
- data/lib/htm/admin/tag_graph.rb +290 -0
- data/lib/htm/admin/templates/tag_graph.html +295 -0
- data/lib/htm/admin/yard_docs.rb +206 -0
- data/lib/htm/admin.rb +253 -0
- data/lib/htm/circuit_breaker.rb +142 -69
- data/lib/htm/class_methods.rb +136 -0
- data/lib/htm/cli/config_file.rb +86 -0
- data/lib/htm/cli/db.rb +77 -0
- data/lib/htm/cli/enrich.rb +44 -0
- data/lib/htm/cli/environment.rb +74 -0
- data/lib/htm/cli/error_suggestion.rb +97 -0
- data/lib/htm/cli/files.rb +41 -0
- data/lib/htm/cli/group.rb +32 -0
- data/lib/htm/cli/memory.rb +320 -0
- data/lib/htm/cli/memory_command.rb +71 -0
- data/lib/htm/cli/robots.rb +71 -0
- data/lib/htm/cli/support.rb +46 -0
- data/lib/htm/cli/tags.rb +103 -0
- data/lib/htm/cli/working_memory.rb +41 -0
- data/lib/htm/cli.rb +75 -0
- data/lib/htm/config/builder.rb +106 -75
- data/lib/htm/config/coercion.rb +91 -0
- data/lib/htm/config/database.rb +94 -71
- data/lib/htm/config/defaults.yml +52 -16
- data/lib/htm/config/readers.rb +85 -0
- data/lib/htm/config/ruby_llm_settings.rb +58 -0
- data/lib/htm/config/validator.rb +47 -34
- data/lib/htm/config.rb +122 -296
- data/lib/htm/database.rb +330 -427
- data/lib/htm/database_docs.rb +149 -0
- data/lib/htm/embedding_service.rb +29 -74
- data/lib/htm/epistemics.rb +254 -0
- data/lib/htm/errors.rb +4 -4
- data/lib/htm/event_time.rb +201 -0
- data/lib/htm/file_memory.rb +106 -0
- data/lib/htm/input_validator.rb +158 -0
- data/lib/htm/integrations/sinatra.rb +45 -33
- data/lib/htm/job_adapter.rb +79 -91
- data/lib/htm/jobs/failure_logging.rb +49 -0
- data/lib/htm/jobs/generate_embedding_job.rb +28 -51
- data/lib/htm/jobs/generate_propositions_job.rb +59 -57
- data/lib/htm/jobs/generate_relationships_job.rb +141 -0
- data/lib/htm/jobs/generate_tags_job.rb +44 -71
- data/lib/htm/jobs/llm_call_timer.rb +53 -0
- data/lib/htm/jobs/node_lookup.rb +27 -0
- data/lib/htm/knowledge_memory.rb +153 -0
- data/lib/htm/loaders/chunk_sync.rb +168 -0
- data/lib/htm/loaders/markdown_chunker.rb +207 -36
- data/lib/htm/loaders/markdown_loader.rb +99 -190
- data/lib/htm/long_term_memory/fulltext_search.rb +16 -37
- data/lib/htm/long_term_memory/hybrid_search.rb +484 -385
- data/lib/htm/long_term_memory/node_operations.rb +111 -82
- data/lib/htm/long_term_memory/relevance_scorer.rb +254 -227
- data/lib/htm/long_term_memory/tag_operations.rb +225 -187
- data/lib/htm/long_term_memory/vector_search.rb +34 -62
- data/lib/htm/long_term_memory.rb +5 -16
- data/lib/htm/mcp/file_tools.rb +190 -0
- data/lib/htm/mcp/group_tools.rb +223 -233
- data/lib/htm/mcp/node_tools.rb +350 -0
- data/lib/htm/mcp/resources.rb +102 -28
- data/lib/htm/mcp/robot_team_tools.rb +119 -0
- data/lib/htm/mcp/server.rb +26 -15
- data/lib/htm/mcp/tag_tools.rb +130 -0
- data/lib/htm/mcp/tool.rb +40 -0
- data/lib/htm/mcp/tool_support.rb +88 -0
- data/lib/htm/mcp/tools.rb +230 -287
- data/lib/htm/migration.rb +10 -10
- data/lib/htm/models/file_source.rb +35 -20
- data/lib/htm/models/node.rb +288 -195
- data/lib/htm/models/node_link.rb +97 -0
- data/lib/htm/models/node_relationship.rb +73 -0
- data/lib/htm/models/node_tag.rb +24 -4
- data/lib/htm/models/robot.rb +4 -8
- data/lib/htm/models/robot_node.rb +7 -4
- data/lib/htm/models/tag.rb +54 -195
- data/lib/htm/node_enrichment.rb +75 -0
- data/lib/htm/node_view.rb +295 -0
- data/lib/htm/observability.rb +125 -115
- data/lib/htm/proposition_service.rb +41 -81
- data/lib/htm/query_cache.rb +148 -96
- data/lib/htm/railtie.rb +4 -9
- data/lib/htm/request_options.rb +149 -0
- data/lib/htm/robot_group/cache_sync.rb +69 -0
- data/lib/htm/robot_group/membership.rb +147 -0
- data/lib/htm/robot_group/working_memory_ledger.rb +111 -0
- data/lib/htm/robot_group.rb +130 -523
- data/lib/htm/robots/actions.rb +371 -0
- data/lib/htm/robots/neighbors.rb +63 -0
- data/lib/htm/robots/node_brief.rb +49 -0
- data/lib/htm/robots/supervisor.rb +140 -0
- data/lib/htm/robots/team.rb +124 -0
- data/lib/htm/robots/teams/archivist.rb +88 -0
- data/lib/htm/robots/teams/consolidator.rb +52 -0
- data/lib/htm/robots/teams/contradiction_detector.rb +67 -0
- data/lib/htm/robots/teams/tag_curator.rb +75 -0
- data/lib/htm/robots/tools.rb +127 -0
- data/lib/htm/robots.rb +125 -0
- data/lib/htm/search_filters.rb +116 -0
- data/lib/htm/sequel_config.rb +96 -59
- data/lib/htm/sql_builder.rb +162 -53
- data/lib/htm/startup_prompt.rb +73 -0
- data/lib/htm/tag_service.rb +105 -114
- data/lib/htm/tag_tree.rb +206 -0
- data/lib/htm/telemetry.rb +15 -16
- data/lib/htm/timeframe.rb +30 -13
- data/lib/htm/timeframe_extractor.rb +104 -123
- data/lib/htm/timeline.rb +230 -0
- data/lib/htm/version.rb +1 -1
- data/lib/htm/workflows/remember_workflow.rb +147 -141
- data/lib/htm/working_memory/entry.rb +53 -0
- data/lib/htm/working_memory/store.rb +97 -0
- data/lib/htm/working_memory.rb +135 -142
- data/lib/htm/working_memory_channel.rb +90 -40
- data/lib/htm.rb +185 -522
- data/mkdocs.yml +100 -23
- data/scripts/install_local_database.sh +7 -6
- metadata +1032 -669
- data/.tbls.yml +0 -31
- data/Rakefile +0 -159
- data/bin/htm_mcp +0 -27
- data/docs/api/yard/HTM/ActiveRecordConfig.md +0 -29
- data/docs/api/yard/HTM/ConfigSection.md +0 -28
- data/docs/database/public.file_sources.md +0 -42
- data/docs/database/public.file_sources.svg +0 -219
- data/docs/database/public.node_stats.md +0 -48
- data/docs/database/public.node_stats.svg +0 -41
- data/docs/database/public.node_tags.md +0 -41
- data/docs/database/public.node_tags.svg +0 -251
- data/docs/database/public.nodes.md +0 -61
- data/docs/database/public.nodes.svg +0 -283
- data/docs/database/public.nodes_tags.md +0 -39
- data/docs/database/public.nodes_tags.svg +0 -112
- data/docs/database/public.ontology_structure.md +0 -48
- data/docs/database/public.ontology_structure.svg +0 -38
- data/docs/database/public.operations_log.md +0 -42
- data/docs/database/public.operations_log.svg +0 -130
- data/docs/database/public.relationships.md +0 -39
- data/docs/database/public.relationships.svg +0 -41
- data/docs/database/public.robot_activity.md +0 -46
- data/docs/database/public.robot_activity.svg +0 -35
- data/docs/database/public.robot_nodes.md +0 -48
- data/docs/database/public.robot_nodes.svg +0 -251
- data/docs/database/public.robots.md +0 -34
- data/docs/database/public.robots.svg +0 -165
- data/docs/database/public.schema_migrations.md +0 -29
- data/docs/database/public.schema_migrations.svg +0 -26
- data/docs/database/public.tags.md +0 -38
- data/docs/database/public.tags.svg +0 -147
- data/docs/database/public.topic_relationships.md +0 -45
- data/docs/database/public.topic_relationships.svg +0 -32
- data/docs/database/schema.json +0 -1814
- data/docs/database_rake_tasks.md +0 -353
- data/docs/development/rake-tasks.md +0 -1113
- data/docs/using_rake_tasks_in_your_app.md +0 -383
- data/examples/06_example_app/Rakefile +0 -71
- data/lib/htm/mcp/cli.rb +0 -582
- data/lib/htm/tasks.rb +0 -79
- data/lib/tasks/db.rake +0 -17
- data/lib/tasks/doc.rake +0 -300
- data/lib/tasks/files.rake +0 -292
- data/lib/tasks/htm.rake +0 -704
- data/lib/tasks/jobs.rake +0 -435
- data/lib/tasks/tags.rake +0 -189
- data/scripts/backfill_parent_tags.rb +0 -376
- data/scripts/normalize_plural_tags.rb +0 -335
|
@@ -4,11 +4,16 @@ class HTM
|
|
|
4
4
|
class LongTermMemory
|
|
5
5
|
# Hybrid search using Reciprocal Rank Fusion (RRF)
|
|
6
6
|
#
|
|
7
|
-
# Performs three independent searches
|
|
8
|
-
#
|
|
7
|
+
# Performs up to three independent searches over the whole corpus and
|
|
8
|
+
# merges the results:
|
|
9
|
+
# 1. Vector similarity search for semantic matching (nearest neighbours
|
|
10
|
+
# of the query embedding)
|
|
9
11
|
# 2. Full-text search for keyword matching
|
|
10
12
|
# 3. Tag-based search for hierarchical category matching
|
|
11
13
|
#
|
|
14
|
+
# No search filters another: a node that is semantically close to the
|
|
15
|
+
# query but shares no keyword or tag with it is still found.
|
|
16
|
+
#
|
|
12
17
|
# Results are merged using RRF scoring. Nodes appearing in multiple
|
|
13
18
|
# searches receive boosted scores, making them rank higher.
|
|
14
19
|
#
|
|
@@ -33,347 +38,337 @@ class HTM
|
|
|
33
38
|
# We fetch more candidates than requested to ensure good fusion
|
|
34
39
|
CANDIDATE_MULTIPLIER = 3
|
|
35
40
|
|
|
41
|
+
# The single-CTE SQL for hybrid search
|
|
42
|
+
module RrfSql
|
|
43
|
+
# One ranked search in the RRF query
|
|
44
|
+
#
|
|
45
|
+
# @!attribute name [String] Table alias in rrf_scores
|
|
46
|
+
# @!attribute table [String] Ranked CTE
|
|
47
|
+
# @!attribute from [String] Candidates CTE the ranking reads
|
|
48
|
+
# @!attribute ranked_column [String] Column the ranked CTE carries along
|
|
49
|
+
# @!attribute order [String] Column ranked on, highest first
|
|
50
|
+
# @!attribute score_fields [Array<String>] Its fields in rrf_scores
|
|
51
|
+
# @!attribute select_fields [Array<String>] Its fields in the final SELECT
|
|
52
|
+
Source = Data.define(:name, :table, :from, :ranked_column, :order, :score_fields, :select_fields) do
|
|
53
|
+
# @return [String] the ranked CTE
|
|
54
|
+
def ranked_cte
|
|
55
|
+
<<~SQL.chomp
|
|
56
|
+
#{table} AS (
|
|
57
|
+
SELECT id, #{ranked_column}, ROW_NUMBER() OVER (ORDER BY #{order} DESC) as rank
|
|
58
|
+
FROM #{from}
|
|
59
|
+
)
|
|
60
|
+
SQL
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# @return [String] the source's id column in rrf_scores
|
|
64
|
+
def id = "#{name}.id"
|
|
65
|
+
|
|
66
|
+
# @return [String] the source's RRF term: 1/(k + rank), 0 when it did not rank the node
|
|
67
|
+
def rank_term = "COALESCE(1.0/(#{RRF_K} + #{name}.rank), 0)"
|
|
68
|
+
|
|
69
|
+
# @param joined_id [String, nil] the id of the sources before this one;
|
|
70
|
+
# nil for the first source
|
|
71
|
+
# @return [String] the source's part of the FROM clause of rrf_scores
|
|
72
|
+
def from_entry(joined_id)
|
|
73
|
+
table_alias = "#{table} #{name}"
|
|
74
|
+
joined_id ? "FULL OUTER JOIN #{table_alias} ON #{joined_id} = #{id}" : table_alias
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The ranked searches, in the order the query joins them
|
|
79
|
+
SOURCES = {
|
|
80
|
+
fulltext: Source.new(name: 'fr', table: 'fulltext_ranked', from: 'fulltext_candidates',
|
|
81
|
+
ranked_column: 'text_rank', order: 'text_rank',
|
|
82
|
+
score_fields: ['fr.rank as fulltext_rank', 'fr.text_rank'],
|
|
83
|
+
select_fields: ['rrf.fulltext_rank', 'COALESCE(rrf.text_rank, 0.0) as text_rank']),
|
|
84
|
+
tags: Source.new(name: 'tr', table: 'tag_ranked', from: 'tag_candidates',
|
|
85
|
+
ranked_column: 'matched_tags', order: 'tag_match_count',
|
|
86
|
+
score_fields: ['tr.rank as tag_rank', 'tr.matched_tags'],
|
|
87
|
+
select_fields: ['rrf.tag_rank', 'rrf.matched_tags']),
|
|
88
|
+
vector: Source.new(name: 'vr', table: 'vector_ranked', from: 'vector_candidates',
|
|
89
|
+
ranked_column: 'similarity', order: 'similarity',
|
|
90
|
+
score_fields: ['vr.rank as vector_rank', 'vr.similarity'],
|
|
91
|
+
select_fields: ['rrf.vector_rank', 'COALESCE(rrf.similarity, 0.0) as similarity'])
|
|
92
|
+
}.freeze
|
|
93
|
+
|
|
94
|
+
# The query, including or leaving out CTEs by the components available:
|
|
95
|
+
# - Always: fulltext (tsvector + trigram) candidates
|
|
96
|
+
# - With tag_literals: tag candidates
|
|
97
|
+
# - With embedding_literal: vector candidates (nearest neighbours)
|
|
98
|
+
#
|
|
99
|
+
# @!attribute query_literal [String] SQL-escaped query string
|
|
100
|
+
# @!attribute embedding_literal [String, nil] SQL-escaped embedding vector (nil to skip vector)
|
|
101
|
+
# @!attribute tag_literals [String, nil] Comma-separated SQL-escaped tag names (nil to skip tags)
|
|
102
|
+
# @!attribute additional_sql [String] Extra WHERE conditions (no table alias)
|
|
103
|
+
# @!attribute additional_sql_n [String] Extra WHERE conditions (with 'n.' alias)
|
|
104
|
+
# @!attribute candidate_limit [Integer] Max candidates per source
|
|
105
|
+
# @!attribute limit [Integer] Final result limit
|
|
106
|
+
Query = Data.define(:query_literal, :embedding_literal, :tag_literals,
|
|
107
|
+
:additional_sql, :additional_sql_n, :candidate_limit, :limit) do
|
|
108
|
+
# @return [Boolean] true when tag candidates take part
|
|
109
|
+
def tags? = !tag_literals.nil?
|
|
110
|
+
|
|
111
|
+
# @return [Boolean] true when vector similarity takes part
|
|
112
|
+
def embedding? = !embedding_literal.nil?
|
|
113
|
+
|
|
114
|
+
# @return [Array<Source>] the sources taking part, in join order
|
|
115
|
+
def sources = SOURCES.values_at(*[:fulltext, (:tags if tags?), (:vector if embedding?)].compact)
|
|
116
|
+
|
|
117
|
+
# @return [String] Complete SQL query
|
|
118
|
+
def to_sql
|
|
119
|
+
<<~SQL
|
|
120
|
+
WITH #{ctes.join(",\n")}
|
|
121
|
+
SELECT #{select_fields.join(",\n ")}
|
|
122
|
+
FROM rrf_scores rrf
|
|
123
|
+
JOIN nodes n ON n.id = rrf.id
|
|
124
|
+
ORDER BY rrf.rrf_score DESC
|
|
125
|
+
LIMIT #{limit}
|
|
126
|
+
SQL
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
# @return [Array<String>] the CTEs, in the order the query needs them
|
|
130
|
+
def ctes
|
|
131
|
+
[*fulltext_ctes, tag_candidates_cte, vector_candidates_cte,
|
|
132
|
+
*sources.map(&:ranked_cte), rrf_scores_cte].compact
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# @return [Array<String>] tsvector_matches, trigram_matches and fulltext_candidates
|
|
136
|
+
def fulltext_ctes
|
|
137
|
+
[<<~SQL.chomp, <<~SQL.chomp, <<~SQL.chomp]
|
|
138
|
+
tsvector_matches AS (
|
|
139
|
+
SELECT id,
|
|
140
|
+
(1.0 + ts_rank(to_tsvector('english', content), plainto_tsquery('english', #{query_literal}))) as text_rank
|
|
141
|
+
FROM nodes
|
|
142
|
+
WHERE deleted_at IS NULL
|
|
143
|
+
AND to_tsvector('english', content) @@ plainto_tsquery('english', #{query_literal})
|
|
144
|
+
#{additional_sql}
|
|
145
|
+
)
|
|
146
|
+
SQL
|
|
147
|
+
trigram_matches AS (
|
|
148
|
+
SELECT id,
|
|
149
|
+
similarity(content, #{query_literal}) as text_rank
|
|
150
|
+
FROM nodes
|
|
151
|
+
WHERE deleted_at IS NULL
|
|
152
|
+
AND similarity(content, #{query_literal}) >= 0.1
|
|
153
|
+
AND id NOT IN (SELECT id FROM tsvector_matches)
|
|
154
|
+
#{additional_sql}
|
|
155
|
+
)
|
|
156
|
+
SQL
|
|
157
|
+
fulltext_candidates AS (
|
|
158
|
+
SELECT * FROM tsvector_matches
|
|
159
|
+
UNION ALL
|
|
160
|
+
SELECT * FROM trigram_matches
|
|
161
|
+
ORDER BY text_rank DESC
|
|
162
|
+
LIMIT #{candidate_limit}
|
|
163
|
+
)
|
|
164
|
+
SQL
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# @return [String, nil] the tag_candidates CTE; nil without tags
|
|
168
|
+
def tag_candidates_cte
|
|
169
|
+
return unless tags?
|
|
170
|
+
|
|
171
|
+
<<~SQL.chomp
|
|
172
|
+
tag_candidates AS (
|
|
173
|
+
SELECT n.id, array_agg(t.name) as matched_tags, count(t.name) as tag_match_count
|
|
174
|
+
FROM nodes n
|
|
175
|
+
JOIN node_tags nt ON nt.node_id = n.id
|
|
176
|
+
JOIN tags t ON t.id = nt.tag_id
|
|
177
|
+
WHERE n.deleted_at IS NULL
|
|
178
|
+
AND t.name IN (#{tag_literals})
|
|
179
|
+
#{additional_sql_n}
|
|
180
|
+
GROUP BY n.id
|
|
181
|
+
LIMIT #{candidate_limit}
|
|
182
|
+
)
|
|
183
|
+
SQL
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# The nearest neighbours of the query embedding across all nodes,
|
|
187
|
+
# independent of the fulltext and tag candidates. It has the same
|
|
188
|
+
# ORDER BY distance / LIMIT shape as the :vector strategy, so on a
|
|
189
|
+
# large table PostgreSQL can answer it from the HNSW index.
|
|
190
|
+
#
|
|
191
|
+
# @return [String, nil] the vector_candidates CTE; nil without an embedding
|
|
192
|
+
def vector_candidates_cte
|
|
193
|
+
return unless embedding?
|
|
194
|
+
|
|
195
|
+
<<~SQL.chomp
|
|
196
|
+
vector_candidates AS (
|
|
197
|
+
SELECT id,
|
|
198
|
+
1 - (embedding <=> #{embedding_literal}::sparsevec) as similarity
|
|
199
|
+
FROM nodes
|
|
200
|
+
WHERE deleted_at IS NULL
|
|
201
|
+
AND embedding IS NOT NULL
|
|
202
|
+
#{additional_sql}
|
|
203
|
+
ORDER BY embedding <=> #{embedding_literal}::sparsevec
|
|
204
|
+
LIMIT #{candidate_limit}
|
|
205
|
+
)
|
|
206
|
+
SQL
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# @return [String] the rrf_scores CTE, joining the ranked sources
|
|
210
|
+
def rrf_scores_cte
|
|
211
|
+
fields = ["COALESCE(#{source_ids.join(', ')}) as id",
|
|
212
|
+
"#{sources.map(&:rank_term).join(' + ')} as rrf_score",
|
|
213
|
+
*sources.flat_map(&:score_fields)]
|
|
214
|
+
<<~SQL.chomp
|
|
215
|
+
rrf_scores AS (
|
|
216
|
+
SELECT #{fields.join(",\n ")}
|
|
217
|
+
FROM #{from_clause}
|
|
218
|
+
)
|
|
219
|
+
SQL
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
# @return [Array<String>] the id column of each source, in join order
|
|
223
|
+
def source_ids = sources.map(&:id)
|
|
224
|
+
|
|
225
|
+
# @return [String] the ranked sources, each joined (FULL OUTER JOIN) on the ids before it
|
|
226
|
+
def from_clause
|
|
227
|
+
sources.each_with_index.map { |source, index| source.from_entry(join_key(source_ids.first(index))) }.join("\n ")
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# @param ids [Array<String>] id columns of the sources already joined
|
|
231
|
+
# @return [String, nil] nil before any source, the one id after one,
|
|
232
|
+
# else the first id that is not NULL
|
|
233
|
+
def join_key(ids)
|
|
234
|
+
return ids.first unless ids.size > 1
|
|
235
|
+
|
|
236
|
+
"COALESCE(#{ids.join(', ')})"
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# @return [Array<String>] the columns of the final SELECT
|
|
240
|
+
def select_fields
|
|
241
|
+
["rrf.id", "n.content", "n.access_count", "n.created_at", "n.occurred_at", "n.token_count",
|
|
242
|
+
"rrf.rrf_score", *sources.flat_map(&:select_fields)]
|
|
243
|
+
end
|
|
244
|
+
end
|
|
245
|
+
end
|
|
246
|
+
|
|
36
247
|
# Hybrid search using Reciprocal Rank Fusion
|
|
37
248
|
#
|
|
38
|
-
# @param timeframe [Range] Time range to search
|
|
39
249
|
# @param query [String] Search query
|
|
40
250
|
# @param limit [Integer] Maximum results (capped at MAX_HYBRID_LIMIT)
|
|
41
251
|
# @param embedding_service [Object] Service to generate embeddings
|
|
42
|
-
# @param
|
|
43
|
-
#
|
|
252
|
+
# @param candidate_limit [Integer] Base candidates per search; each search
|
|
253
|
+
# (fulltext, tags, vector) takes candidate_limit * CANDIDATE_MULTIPLIER
|
|
254
|
+
# @param filters [HTM::SearchFilters] timeframe, metadata, time axis and as_of
|
|
44
255
|
# @return [Array<Hash>] Matching nodes
|
|
45
256
|
#
|
|
46
|
-
def search_hybrid(
|
|
257
|
+
def search_hybrid(query:, limit:, embedding_service:, candidate_limit: 100, filters: HTM::SearchFilters.none)
|
|
47
258
|
# Enforce limits to prevent DoS
|
|
48
|
-
safe_limit =
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
embedding_service: embedding_service,
|
|
58
|
-
candidate_limit: safe_prefilter * CANDIDATE_MULTIPLIER,
|
|
59
|
-
metadata: metadata
|
|
60
|
-
)
|
|
259
|
+
safe_limit = limit.to_i.clamp(1, MAX_HYBRID_LIMIT)
|
|
260
|
+
safe_candidates = [candidate_limit.to_i, 1].max
|
|
261
|
+
|
|
262
|
+
HTM::Telemetry.measure(HTM::Telemetry.search_latency, 'strategy' => 'hybrid') do
|
|
263
|
+
@cache.fetch(:hybrid, query, safe_limit, safe_candidates, *filters.cache_key) do
|
|
264
|
+
search_hybrid_rrf(query, embedding_service,
|
|
265
|
+
filter_sql: build_rrf_filter_sql(filters),
|
|
266
|
+
limits: { candidate_limit: safe_candidates * CANDIDATE_MULTIPLIER, limit: safe_limit })
|
|
267
|
+
end
|
|
61
268
|
end
|
|
62
|
-
elapsed_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000).round
|
|
63
|
-
HTM::Telemetry.search_latency.record(elapsed_ms, attributes: { 'strategy' => 'hybrid' })
|
|
64
|
-
result
|
|
65
269
|
end
|
|
66
270
|
|
|
67
271
|
private
|
|
68
272
|
|
|
69
273
|
# Hybrid search using Reciprocal Rank Fusion
|
|
70
274
|
#
|
|
71
|
-
#
|
|
72
|
-
#
|
|
73
|
-
#
|
|
275
|
+
# Uses a single SQL CTE query instead of three round-trips:
|
|
276
|
+
# 1. Fulltext, tag and vector candidates are each retrieved from the
|
|
277
|
+
# whole corpus (top candidate_limit per search)
|
|
278
|
+
# 2. Each list is ranked on its own score
|
|
279
|
+
# 3. RRF scoring merges the rankings; a node in more than one list
|
|
280
|
+
# gets a term from each, so it ranks above nodes found once
|
|
74
281
|
#
|
|
75
|
-
# @param timeframe [nil, Range, Array<Range>] Time range(s) to search
|
|
76
282
|
# @param query [String] Search query
|
|
77
|
-
# @param limit [Integer] Maximum results
|
|
78
283
|
# @param embedding_service [Object] Service to generate query embedding
|
|
79
|
-
# @param
|
|
80
|
-
# @param
|
|
284
|
+
# @param filter_sql [Hash] additional_sql:, additional_sql_n: (see #build_rrf_filter_sql)
|
|
285
|
+
# @param limits [Hash] candidate_limit: (per search), limit: (results)
|
|
81
286
|
# @return [Array<Hash>] Merged results with RRF scores
|
|
82
287
|
#
|
|
83
|
-
def search_hybrid_rrf(
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
embedding_service: embedding_service,
|
|
88
|
-
timeframe: timeframe,
|
|
89
|
-
metadata: metadata,
|
|
90
|
-
limit: candidate_limit
|
|
91
|
-
)
|
|
92
|
-
|
|
93
|
-
fulltext_results = fetch_fulltext_candidates(
|
|
94
|
-
query: query,
|
|
95
|
-
timeframe: timeframe,
|
|
96
|
-
metadata: metadata,
|
|
97
|
-
limit: candidate_limit
|
|
98
|
-
)
|
|
99
|
-
|
|
100
|
-
# Extract tags from query and find matching nodes
|
|
101
|
-
tag_results = fetch_tag_candidates(
|
|
102
|
-
query: query,
|
|
103
|
-
timeframe: timeframe,
|
|
104
|
-
metadata: metadata,
|
|
105
|
-
limit: candidate_limit
|
|
106
|
-
)
|
|
107
|
-
|
|
108
|
-
# Merge using RRF
|
|
109
|
-
merged = merge_with_rrf(vector_results, fulltext_results, tag_results)
|
|
110
|
-
|
|
111
|
-
# Take top results
|
|
112
|
-
top_results = merged.first(limit)
|
|
113
|
-
|
|
114
|
-
# Track access for retrieved nodes
|
|
115
|
-
node_ids = top_results.map { |r| r['id'] }
|
|
116
|
-
track_access(node_ids)
|
|
288
|
+
def search_hybrid_rrf(query, embedding_service, filter_sql:, limits:)
|
|
289
|
+
tag_info = extract_rrf_tag_info(query)
|
|
290
|
+
literals = build_rrf_literals(query, tag_info[:search_tags], embedding_service.embed(query))
|
|
291
|
+
sql = build_hybrid_cte_sql(**literals, **filter_sql, **limits.transform_values(&:to_i))
|
|
117
292
|
|
|
293
|
+
top_results = post_process_rrf_results(HTM.db.fetch(sql).all, tag_info[:tag_depth_map])
|
|
294
|
+
track_access(top_results.map { it['id'] })
|
|
118
295
|
top_results
|
|
119
296
|
end
|
|
120
297
|
|
|
121
|
-
# Fetch candidates using vector similarity search
|
|
122
|
-
#
|
|
123
298
|
# @param query [String] Search query
|
|
124
|
-
# @
|
|
125
|
-
#
|
|
126
|
-
# @param metadata [Hash] Metadata filter
|
|
127
|
-
# @param limit [Integer] Maximum candidates
|
|
128
|
-
# @return [Array<Hash>] Results with similarity scores
|
|
299
|
+
# @return [Hash] search_tags: (the stored tags matching the query's
|
|
300
|
+
# extracted tags, else the extracted tags), tag_depth_map: (see #build_tag_depth_map)
|
|
129
301
|
#
|
|
130
|
-
def
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
padded_embedding = HTM::SqlBuilder.pad_embedding(query_embedding)
|
|
140
|
-
embedding_str = HTM::SqlBuilder.sanitize_embedding(padded_embedding)
|
|
141
|
-
|
|
142
|
-
# Build filter conditions
|
|
143
|
-
timeframe_condition = HTM::SqlBuilder.timeframe_condition(timeframe)
|
|
144
|
-
metadata_condition = HTM::SqlBuilder.metadata_condition(metadata)
|
|
145
|
-
|
|
146
|
-
conditions = ["embedding IS NOT NULL", "deleted_at IS NULL"]
|
|
147
|
-
conditions << timeframe_condition if timeframe_condition
|
|
148
|
-
conditions << metadata_condition if metadata_condition
|
|
149
|
-
|
|
150
|
-
where_clause = "WHERE #{conditions.join(' AND ')}"
|
|
151
|
-
|
|
152
|
-
# Note: Using Sequel.lit for the vector comparison since it needs special handling
|
|
153
|
-
embedding_literal = HTM.db.literal(embedding_str)
|
|
154
|
-
sql = <<~SQL
|
|
155
|
-
SELECT id, content, access_count, created_at, token_count,
|
|
156
|
-
1 - (embedding <=> #{embedding_literal}::vector) as similarity
|
|
157
|
-
FROM nodes
|
|
158
|
-
#{where_clause}
|
|
159
|
-
ORDER BY embedding <=> #{embedding_literal}::vector
|
|
160
|
-
LIMIT ?
|
|
161
|
-
SQL
|
|
162
|
-
|
|
163
|
-
HTM.db.fetch(sql, limit).all.map { |r| r.transform_keys(&:to_s) }
|
|
302
|
+
def extract_rrf_tag_info(query)
|
|
303
|
+
extraction = query_tag_matches(query)
|
|
304
|
+
extracted_tags = extraction[:extracted] || []
|
|
305
|
+
matched_db_tags = extraction[:matched] || []
|
|
306
|
+
{
|
|
307
|
+
search_tags: matched_db_tags.any? ? matched_db_tags : extracted_tags,
|
|
308
|
+
tag_depth_map: build_tag_depth_map(extracted_tags)
|
|
309
|
+
}
|
|
164
310
|
end
|
|
165
311
|
|
|
166
|
-
# Fetch candidates using full-text search
|
|
167
|
-
#
|
|
168
312
|
# @param query [String] Search query
|
|
169
|
-
# @param
|
|
170
|
-
# @param
|
|
171
|
-
# @
|
|
172
|
-
#
|
|
313
|
+
# @param search_tags [Array<String>] Tags to search for
|
|
314
|
+
# @param query_embedding [Object] What the embedding service returned for the query
|
|
315
|
+
# @return [Hash] query_literal:, embedding_literal: (nil without a usable
|
|
316
|
+
# embedding), tag_literals: (nil without tags), all SQL-escaped
|
|
173
317
|
#
|
|
174
|
-
def
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
additional_conditions << metadata_condition if metadata_condition
|
|
181
|
-
additional_sql = additional_conditions.any? ? "AND #{additional_conditions.join(' AND ')}" : ""
|
|
182
|
-
|
|
183
|
-
# Combined tsvector + trigram search (same as fulltext_search.rb)
|
|
184
|
-
# Escape the query for safe interpolation in trigram comparisons
|
|
185
|
-
query_literal = HTM.db.literal(query)
|
|
186
|
-
sql = <<~SQL
|
|
187
|
-
WITH tsvector_matches AS (
|
|
188
|
-
SELECT id, content, access_count, created_at, token_count,
|
|
189
|
-
(1.0 + ts_rank(to_tsvector('english', content), plainto_tsquery('english', #{query_literal}))) as text_rank
|
|
190
|
-
FROM nodes
|
|
191
|
-
WHERE deleted_at IS NULL
|
|
192
|
-
AND to_tsvector('english', content) @@ plainto_tsquery('english', #{query_literal})
|
|
193
|
-
#{additional_sql}
|
|
194
|
-
),
|
|
195
|
-
trigram_matches AS (
|
|
196
|
-
SELECT id, content, access_count, created_at, token_count,
|
|
197
|
-
similarity(content, #{query_literal}) as text_rank
|
|
198
|
-
FROM nodes
|
|
199
|
-
WHERE deleted_at IS NULL
|
|
200
|
-
AND similarity(content, #{query_literal}) >= 0.1
|
|
201
|
-
AND id NOT IN (SELECT id FROM tsvector_matches)
|
|
202
|
-
#{additional_sql}
|
|
203
|
-
),
|
|
204
|
-
combined AS (
|
|
205
|
-
SELECT * FROM tsvector_matches
|
|
206
|
-
UNION ALL
|
|
207
|
-
SELECT * FROM trigram_matches
|
|
208
|
-
)
|
|
209
|
-
SELECT id, content, access_count, created_at, token_count, text_rank
|
|
210
|
-
FROM combined
|
|
211
|
-
ORDER BY text_rank DESC
|
|
212
|
-
LIMIT ?
|
|
213
|
-
SQL
|
|
214
|
-
|
|
215
|
-
HTM.db.fetch(sql, limit).all.map { |r| r.transform_keys(&:to_s) }
|
|
318
|
+
def build_rrf_literals(query, search_tags, query_embedding)
|
|
319
|
+
{
|
|
320
|
+
query_literal: sql_literal(query),
|
|
321
|
+
embedding_literal: (sql_literal(HTM::SqlBuilder.sanitize_embedding(query_embedding)) if usable_embedding?(query_embedding)),
|
|
322
|
+
tag_literals: (search_tags.map { sql_literal(it) }.join(', ') if search_tags.any?)
|
|
323
|
+
}
|
|
216
324
|
end
|
|
217
325
|
|
|
218
|
-
#
|
|
326
|
+
# @param value [Object] Value to put in SQL
|
|
327
|
+
# @return [String] the value as a quoted SQL literal
|
|
219
328
|
#
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
#
|
|
223
|
-
#
|
|
224
|
-
#
|
|
225
|
-
# - Node with "database:postgresql" = 2/3 = 0.67
|
|
226
|
-
# - Node with "database" = 1/3 = 0.33
|
|
329
|
+
def sql_literal(value) = HTM.db.literal(value)
|
|
330
|
+
|
|
331
|
+
# @param filters [HTM::SearchFilters] Search filters
|
|
332
|
+
# @return [Hash] additional_sql: and additional_sql_n: ("AND ..." suffixes
|
|
333
|
+
# without and with the 'n.' alias)
|
|
227
334
|
#
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
335
|
+
def build_rrf_filter_sql(filters)
|
|
336
|
+
{
|
|
337
|
+
additional_sql: filters.and_sql,
|
|
338
|
+
additional_sql_n: filters.and_sql(table_alias: 'n')
|
|
339
|
+
}
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
# @param results [Array<Hash>] rrf_scores rows
|
|
343
|
+
# @param tag_depth_map [Hash] see #build_tag_depth_map
|
|
344
|
+
# @return [Array<Hash>] the rows, see RrfRows.normalize
|
|
233
345
|
#
|
|
234
|
-
def
|
|
235
|
-
|
|
236
|
-
tag_extraction = find_query_matching_tags(query, include_extracted: true)
|
|
237
|
-
extracted_tags = tag_extraction[:extracted] || []
|
|
238
|
-
matched_db_tags = tag_extraction[:matched] || []
|
|
239
|
-
|
|
240
|
-
return [] if extracted_tags.empty? && matched_db_tags.empty?
|
|
241
|
-
|
|
242
|
-
# Build a map of tag prefixes to their max depth
|
|
243
|
-
# This allows us to score partial matches
|
|
244
|
-
tag_depth_map = build_tag_depth_map(extracted_tags)
|
|
245
|
-
|
|
246
|
-
# Use matched_db_tags if available, otherwise use extracted_tags
|
|
247
|
-
search_tags = matched_db_tags.any? ? matched_db_tags : extracted_tags
|
|
248
|
-
|
|
249
|
-
return [] if search_tags.empty?
|
|
250
|
-
|
|
251
|
-
# Build filter conditions
|
|
252
|
-
timeframe_condition = HTM::SqlBuilder.timeframe_condition(timeframe, table_alias: 'n')
|
|
253
|
-
metadata_condition = HTM::SqlBuilder.metadata_condition(metadata, table_alias: 'n')
|
|
254
|
-
|
|
255
|
-
additional_conditions = []
|
|
256
|
-
additional_conditions << timeframe_condition if timeframe_condition
|
|
257
|
-
additional_conditions << metadata_condition if metadata_condition
|
|
258
|
-
additional_sql = additional_conditions.any? ? "AND #{additional_conditions.join(' AND ')}" : ""
|
|
259
|
-
|
|
260
|
-
# Find nodes with matching tags
|
|
261
|
-
# Use Sequel's literal to safely quote tag names
|
|
262
|
-
tag_literals = search_tags.map { |tag| HTM.db.literal(tag) }.join(', ')
|
|
263
|
-
|
|
264
|
-
sql = <<~SQL
|
|
265
|
-
SELECT DISTINCT n.id, n.content, n.access_count, n.created_at, n.token_count,
|
|
266
|
-
array_agg(t.name) as matched_tags
|
|
267
|
-
FROM nodes n
|
|
268
|
-
JOIN node_tags nt ON nt.node_id = n.id
|
|
269
|
-
JOIN tags t ON t.id = nt.tag_id
|
|
270
|
-
WHERE n.deleted_at IS NULL
|
|
271
|
-
AND t.name IN (#{tag_literals})
|
|
272
|
-
#{additional_sql}
|
|
273
|
-
GROUP BY n.id, n.content, n.access_count, n.created_at, n.token_count
|
|
274
|
-
LIMIT ?
|
|
275
|
-
SQL
|
|
276
|
-
|
|
277
|
-
results = HTM.db.fetch(sql, limit).all
|
|
278
|
-
|
|
279
|
-
# Calculate depth scores for each result
|
|
280
|
-
results.map do |result|
|
|
281
|
-
matched_tags = parse_pg_array(result[:matched_tags])
|
|
282
|
-
depth_score = calculate_tag_depth_score(matched_tags, tag_depth_map)
|
|
283
|
-
|
|
284
|
-
result.transform_keys(&:to_s).merge('tag_depth_score' => depth_score, 'matched_tags' => matched_tags)
|
|
285
|
-
end.sort_by { |r| -r['tag_depth_score'] }
|
|
346
|
+
def post_process_rrf_results(results, tag_depth_map)
|
|
347
|
+
results.map { RrfRows.normalize(it, tag_depth_map) }
|
|
286
348
|
end
|
|
287
349
|
|
|
288
|
-
# Build
|
|
350
|
+
# Build the single-CTE SQL for hybrid search
|
|
289
351
|
#
|
|
290
|
-
#
|
|
291
|
-
#
|
|
292
|
-
# - "database:postgresql" => { depth: 2, max_depth: 3 }
|
|
293
|
-
# - "database:postgresql:extensions" => { depth: 3, max_depth: 3 }
|
|
352
|
+
# @param parts [Hash] The members of RrfSql::Query
|
|
353
|
+
# @return [String] Complete SQL query
|
|
294
354
|
#
|
|
355
|
+
def build_hybrid_cte_sql(**) = RrfSql::Query.new(**).to_sql
|
|
356
|
+
|
|
295
357
|
# @param extracted_tags [Array<String>] Tags extracted from query
|
|
296
|
-
# @return [Hash] Map of tag/prefix to depth info
|
|
358
|
+
# @return [Hash] Map of tag/prefix to depth info (see TagDepth.map)
|
|
297
359
|
#
|
|
298
|
-
def build_tag_depth_map(extracted_tags)
|
|
299
|
-
depth_map = {}
|
|
300
|
-
|
|
301
|
-
extracted_tags.each do |tag|
|
|
302
|
-
levels = tag.split(':')
|
|
303
|
-
max_depth = levels.size
|
|
304
|
-
|
|
305
|
-
# Add entry for each prefix level
|
|
306
|
-
(1..max_depth).each do |depth|
|
|
307
|
-
prefix = levels[0, depth].join(':')
|
|
308
|
-
# Keep the highest max_depth if prefix appears in multiple tags
|
|
309
|
-
if !depth_map.key?(prefix) || depth_map[prefix][:max_depth] < max_depth
|
|
310
|
-
depth_map[prefix] = { depth: depth, max_depth: max_depth }
|
|
311
|
-
end
|
|
312
|
-
end
|
|
313
|
-
end
|
|
360
|
+
def build_tag_depth_map(extracted_tags) = TagDepth.map(extracted_tags)
|
|
314
361
|
|
|
315
|
-
depth_map
|
|
316
|
-
end
|
|
317
|
-
|
|
318
|
-
# Calculate depth score for a node's matched tags
|
|
319
|
-
#
|
|
320
|
-
# The score is based on how deeply the matched tags align with
|
|
321
|
-
# the extracted query tags. More levels matched = higher score.
|
|
322
|
-
#
|
|
323
362
|
# @param matched_tags [Array<String>] Tags the node has that matched
|
|
324
363
|
# @param tag_depth_map [Hash] Map of tag/prefix to depth info
|
|
325
|
-
# @return [Float] Normalized score (0.0 to 1.0)
|
|
364
|
+
# @return [Float] Normalized score (0.0 to 1.0), see TagDepth.score
|
|
326
365
|
#
|
|
327
|
-
def calculate_tag_depth_score(matched_tags, tag_depth_map)
|
|
328
|
-
return 0.0 if matched_tags.empty? || tag_depth_map.empty?
|
|
329
|
-
|
|
330
|
-
# Find the best depth match for each matched tag
|
|
331
|
-
best_score = 0.0
|
|
332
|
-
|
|
333
|
-
matched_tags.each do |tag|
|
|
334
|
-
if tag_depth_map.key?(tag)
|
|
335
|
-
info = tag_depth_map[tag]
|
|
336
|
-
# Score is depth / max_depth
|
|
337
|
-
# e.g., "database:postgresql" matching query "database:postgresql:extensions"
|
|
338
|
-
# gives 2/3 = 0.67
|
|
339
|
-
score = info[:depth].to_f / info[:max_depth].to_f
|
|
340
|
-
best_score = [best_score, score].max
|
|
341
|
-
else
|
|
342
|
-
# Check if this tag is a parent of any extracted tag
|
|
343
|
-
tag_depth_map.each do |prefix, info|
|
|
344
|
-
if prefix.start_with?(tag + ':') || prefix == tag
|
|
345
|
-
score = tag.split(':').size.to_f / info[:max_depth].to_f
|
|
346
|
-
best_score = [best_score, score].max
|
|
347
|
-
end
|
|
348
|
-
end
|
|
349
|
-
end
|
|
350
|
-
end
|
|
351
|
-
|
|
352
|
-
# Bonus for multiple tag matches (capped at 0.2 extra)
|
|
353
|
-
multi_match_bonus = [(matched_tags.size - 1) * 0.05, 0.2].min
|
|
354
|
-
|
|
355
|
-
[best_score + multi_match_bonus, 1.0].min
|
|
356
|
-
end
|
|
366
|
+
def calculate_tag_depth_score(matched_tags, tag_depth_map) = TagDepth.score(matched_tags, tag_depth_map)
|
|
357
367
|
|
|
358
|
-
#
|
|
368
|
+
# @param pg_array [String, Array, Sequel::Postgres::PGArray, nil] PostgreSQL array or Ruby array
|
|
369
|
+
# @return [Array<String>] Parsed array, see RrfRows.parse_pg_array
|
|
359
370
|
#
|
|
360
|
-
|
|
361
|
-
# @return [Array<String>] Parsed array
|
|
362
|
-
#
|
|
363
|
-
def parse_pg_array(pg_array)
|
|
364
|
-
# Handle Sequel::Postgres::PGArray (wraps Ruby Array)
|
|
365
|
-
return pg_array.to_a if pg_array.respond_to?(:to_a) && !pg_array.is_a?(String)
|
|
366
|
-
return pg_array if pg_array.is_a?(Array)
|
|
367
|
-
return [] if pg_array.nil? || (pg_array.respond_to?(:empty?) && pg_array.empty?)
|
|
368
|
-
|
|
369
|
-
# Handle raw PostgreSQL array format: {val1,val2,val3}
|
|
370
|
-
pg_str = pg_array.to_s
|
|
371
|
-
if pg_str.start_with?('{') && pg_str.end_with?('}')
|
|
372
|
-
pg_str[1..-2].split(',').map { |s| s.gsub(/^"|"$/, '') }
|
|
373
|
-
else
|
|
374
|
-
[pg_str]
|
|
375
|
-
end
|
|
376
|
-
end
|
|
371
|
+
def parse_pg_array(pg_array) = RrfRows.parse_pg_array(pg_array)
|
|
377
372
|
|
|
378
373
|
# Merge three result sets using Reciprocal Rank Fusion
|
|
379
374
|
#
|
|
@@ -388,103 +383,207 @@ class HTM
|
|
|
388
383
|
# @return [Array<Hash>] Merged results sorted by RRF score
|
|
389
384
|
#
|
|
390
385
|
def merge_with_rrf(vector_results, fulltext_results, tag_results = [])
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
'
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
386
|
+
RrfMerger.new
|
|
387
|
+
.add('vector', vector_results)
|
|
388
|
+
.add('fulltext', fulltext_results)
|
|
389
|
+
.add('tags', tag_results)
|
|
390
|
+
.results
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
# The rows hybrid search returns
|
|
394
|
+
module RrfRows
|
|
395
|
+
class << self
|
|
396
|
+
# Give an rrf_scores row string keys, parsed matched_tags, a
|
|
397
|
+
# tag_depth_score, the sources that found it, Float scores, and every
|
|
398
|
+
# rank key (nil for a source that did not find it)
|
|
399
|
+
#
|
|
400
|
+
# @param row [Hash] rrf_scores row
|
|
401
|
+
# @param tag_depth_map [Hash] see TagDepth.map
|
|
402
|
+
# @return [Hash]
|
|
403
|
+
#
|
|
404
|
+
def normalize(row, tag_depth_map)
|
|
405
|
+
result = row.transform_keys(&:to_s)
|
|
406
|
+
matched_tags = parse_pg_array(result['matched_tags'])
|
|
407
|
+
result.merge!(
|
|
408
|
+
'matched_tags' => matched_tags,
|
|
409
|
+
'tag_depth_score' => TagDepth.score(matched_tags, tag_depth_map),
|
|
410
|
+
'sources' => sources(result),
|
|
411
|
+
'similarity' => result['similarity'].to_f,
|
|
412
|
+
'text_rank' => result['text_rank'].to_f,
|
|
413
|
+
'rrf_score' => result['rrf_score'].to_f
|
|
414
|
+
)
|
|
415
|
+
result.merge!(%w[vector_rank fulltext_rank tag_rank].to_h { [it, result[it]] })
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
# @param row [Hash] rrf_scores row with string keys
|
|
419
|
+
# @return [Array<String>] 'vector', 'fulltext' and 'tags', for each
|
|
420
|
+
# search that ranked the row
|
|
421
|
+
#
|
|
422
|
+
def sources(row)
|
|
423
|
+
{ 'vector' => 'vector_rank', 'fulltext' => 'fulltext_rank', 'tags' => 'tag_rank' }
|
|
424
|
+
.filter_map { |source, rank_key| source if row[rank_key] }
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
# Parse PostgreSQL array string to Ruby array
|
|
428
|
+
#
|
|
429
|
+
# @param pg_array [String, Array, Sequel::Postgres::PGArray, nil] PostgreSQL array or Ruby array
|
|
430
|
+
# @return [Array<String>] Parsed array
|
|
431
|
+
#
|
|
432
|
+
def parse_pg_array(pg_array)
|
|
433
|
+
pg_array.is_a?(String) ? parse_pg_array_literal(pg_array) : Array(pg_array)
|
|
434
|
+
end
|
|
435
|
+
|
|
436
|
+
# @param text [String] PostgreSQL array literal ({val1,val2,val3})
|
|
437
|
+
# @return [Array<String>] the values, unquoted; [text] for other text
|
|
438
|
+
#
|
|
439
|
+
def parse_pg_array_literal(text)
|
|
440
|
+
return [] if text.empty?
|
|
441
|
+
return [text] unless text.start_with?('{') && text.end_with?('}')
|
|
442
|
+
|
|
443
|
+
text[1..-2].split(',').map { it.gsub(/^"|"$/, '') }
|
|
444
|
+
end
|
|
417
445
|
end
|
|
446
|
+
end
|
|
447
|
+
|
|
448
|
+
# Hierarchical depth scoring of the tags a node matched
|
|
449
|
+
#
|
|
450
|
+
# Scoring: For a query tag "database:postgresql:extensions" (3 levels):
|
|
451
|
+
# - Node with "database:postgresql:extensions" = 3/3 = 1.0
|
|
452
|
+
# - Node with "database:postgresql" = 2/3 = 0.67
|
|
453
|
+
# - Node with "database" = 1/3 = 0.33
|
|
454
|
+
module TagDepth
|
|
455
|
+
class << self
|
|
456
|
+
# Build a map of tag prefixes to their depth information
|
|
457
|
+
#
|
|
458
|
+
# For tag "database:postgresql:extensions":
|
|
459
|
+
# - "database" => { depth: 1, max_depth: 3 }
|
|
460
|
+
# - "database:postgresql" => { depth: 2, max_depth: 3 }
|
|
461
|
+
# - "database:postgresql:extensions" => { depth: 3, max_depth: 3 }
|
|
462
|
+
#
|
|
463
|
+
# @param extracted_tags [Array<String>] Tags extracted from query
|
|
464
|
+
# @return [Hash] Map of tag/prefix to depth info
|
|
465
|
+
#
|
|
466
|
+
def map(extracted_tags)
|
|
467
|
+
extracted_tags.each_with_object({}) { |tag, depth_map| add_prefixes(depth_map, tag.split(':')) }
|
|
468
|
+
end
|
|
469
|
+
|
|
470
|
+
# Add an entry for each prefix of a tag, keeping the highest
|
|
471
|
+
# max_depth when a prefix appears in several tags
|
|
472
|
+
#
|
|
473
|
+
# @param depth_map [Hash] Map of tag/prefix to depth info (modified in-place)
|
|
474
|
+
# @param levels [Array<String>] The tag split into its levels
|
|
475
|
+
# @return [void]
|
|
476
|
+
#
|
|
477
|
+
def add_prefixes(depth_map, levels)
|
|
478
|
+
max_depth = levels.size
|
|
479
|
+
(1..max_depth).each do |depth|
|
|
480
|
+
prefix = levels[0, depth].join(':')
|
|
481
|
+
known = depth_map[prefix]
|
|
482
|
+
depth_map[prefix] = { depth:, max_depth: } if known.nil? || known[:max_depth] < max_depth
|
|
483
|
+
end
|
|
484
|
+
end
|
|
485
|
+
|
|
486
|
+
# Calculate depth score for a node's matched tags
|
|
487
|
+
#
|
|
488
|
+
# The score is based on how deeply the matched tags align with
|
|
489
|
+
# the extracted query tags. More levels matched = higher score.
|
|
490
|
+
#
|
|
491
|
+
# @param matched_tags [Array<String>] Tags the node has that matched
|
|
492
|
+
# @param depth_map [Hash] Map of tag/prefix to depth info
|
|
493
|
+
# @return [Float] Normalized score (0.0 to 1.0)
|
|
494
|
+
#
|
|
495
|
+
def score(matched_tags, depth_map)
|
|
496
|
+
return 0.0 if matched_tags.empty? || depth_map.empty?
|
|
497
|
+
|
|
498
|
+
best_score = [0.0, *matched_tags.map { tag_score(it, depth_map) }].max
|
|
499
|
+
|
|
500
|
+
# Bonus for multiple tag matches (capped at 0.2 extra)
|
|
501
|
+
multi_match_bonus = [(matched_tags.size - 1) * 0.05, 0.2].min
|
|
418
502
|
|
|
419
|
-
|
|
420
|
-
fulltext_results.each_with_index do |result, index|
|
|
421
|
-
id = result['id']
|
|
422
|
-
rank = index + 1 # 1-based rank
|
|
423
|
-
rrf_contribution = 1.0 / (RRF_K + rank)
|
|
424
|
-
|
|
425
|
-
if merged.key?(id)
|
|
426
|
-
# Node appears in both - add RRF contribution (this is the boost!)
|
|
427
|
-
merged[id]['rrf_score'] += rrf_contribution
|
|
428
|
-
merged[id]['text_rank'] = result['text_rank']
|
|
429
|
-
merged[id]['fulltext_rank'] = rank
|
|
430
|
-
merged[id]['sources'] << 'fulltext'
|
|
431
|
-
else
|
|
432
|
-
# Node only in fulltext
|
|
433
|
-
merged[id] = {
|
|
434
|
-
'id' => result['id'],
|
|
435
|
-
'content' => result['content'],
|
|
436
|
-
'access_count' => result['access_count'],
|
|
437
|
-
'created_at' => result['created_at'],
|
|
438
|
-
'token_count' => result['token_count'],
|
|
439
|
-
'similarity' => 0.0,
|
|
440
|
-
'text_rank' => result['text_rank'],
|
|
441
|
-
'tag_depth_score' => 0.0,
|
|
442
|
-
'matched_tags' => [],
|
|
443
|
-
'rrf_score' => rrf_contribution,
|
|
444
|
-
'vector_rank' => nil,
|
|
445
|
-
'fulltext_rank' => rank,
|
|
446
|
-
'tag_rank' => nil,
|
|
447
|
-
'sources' => ['fulltext']
|
|
448
|
-
}
|
|
503
|
+
[best_score + multi_match_bonus, 1.0].min
|
|
449
504
|
end
|
|
505
|
+
|
|
506
|
+
# @param tag [String] A tag the node matched
|
|
507
|
+
# @param depth_map [Hash] Map of tag/prefix to depth info
|
|
508
|
+
# @return [Float] depth / max_depth for a tag in the map (e.g.
|
|
509
|
+
# "database:postgresql" for query tag "database:postgresql:extensions"
|
|
510
|
+
# gives 2/3), else its score as a parent of an extracted tag
|
|
511
|
+
#
|
|
512
|
+
def tag_score(tag, depth_map)
|
|
513
|
+
info = depth_map[tag]
|
|
514
|
+
return info[:depth].to_f / info[:max_depth] if info
|
|
515
|
+
|
|
516
|
+
parent_score(tag, depth_map)
|
|
517
|
+
end
|
|
518
|
+
|
|
519
|
+
# @param tag [String] A tag not in the depth map
|
|
520
|
+
# @param depth_map [Hash] Map of tag/prefix to depth info
|
|
521
|
+
# @return [Float] the best levels / max_depth over the prefixes the tag
|
|
522
|
+
# is a parent of; 0.0 when it is a parent of none
|
|
523
|
+
#
|
|
524
|
+
def parent_score(tag, depth_map)
|
|
525
|
+
child_prefix = "#{tag}:"
|
|
526
|
+
levels = tag.split(':').size.to_f
|
|
527
|
+
depth_map.filter_map { |prefix, info| levels / info[:max_depth] if prefix.start_with?(child_prefix) }.max || 0.0
|
|
528
|
+
end
|
|
529
|
+
end
|
|
530
|
+
end
|
|
531
|
+
|
|
532
|
+
# Merges ranked result lists with Reciprocal Rank Fusion
|
|
533
|
+
class RrfMerger
|
|
534
|
+
# The rank key and the result fields each source sets on an entry
|
|
535
|
+
SOURCE_FIELDS = {
|
|
536
|
+
'vector' => ['vector_rank', %w[similarity]],
|
|
537
|
+
'fulltext' => ['fulltext_rank', %w[text_rank]],
|
|
538
|
+
'tags' => ['tag_rank', %w[tag_depth_score matched_tags]]
|
|
539
|
+
}.freeze
|
|
540
|
+
|
|
541
|
+
def initialize
|
|
542
|
+
@entries = {}
|
|
450
543
|
end
|
|
451
544
|
|
|
452
|
-
#
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
merged[id]['tag_rank'] = rank
|
|
464
|
-
merged[id]['sources'] << 'tags'
|
|
465
|
-
else
|
|
466
|
-
# Node only found via tags
|
|
467
|
-
merged[id] = {
|
|
468
|
-
'id' => result['id'],
|
|
469
|
-
'content' => result['content'],
|
|
470
|
-
'access_count' => result['access_count'],
|
|
471
|
-
'created_at' => result['created_at'],
|
|
472
|
-
'token_count' => result['token_count'],
|
|
473
|
-
'similarity' => 0.0,
|
|
474
|
-
'text_rank' => 0.0,
|
|
475
|
-
'tag_depth_score' => result['tag_depth_score'],
|
|
476
|
-
'matched_tags' => result['matched_tags'],
|
|
477
|
-
'rrf_score' => rrf_contribution,
|
|
478
|
-
'vector_rank' => nil,
|
|
479
|
-
'fulltext_rank' => nil,
|
|
480
|
-
'tag_rank' => rank,
|
|
481
|
-
'sources' => ['tags']
|
|
482
|
-
}
|
|
545
|
+
# Add one source's results, best first
|
|
546
|
+
#
|
|
547
|
+
# @param source [String] 'vector', 'fulltext' or 'tags'
|
|
548
|
+
# @param results [Array<Hash>] Results with string keys
|
|
549
|
+
# @return [RrfMerger] self
|
|
550
|
+
#
|
|
551
|
+
def add(source, results)
|
|
552
|
+
rank_key, fields = SOURCE_FIELDS.fetch(source)
|
|
553
|
+
results.each.with_index(1) do |result, rank|
|
|
554
|
+
entry = (@entries[result['id']] ||= blank_entry(result))
|
|
555
|
+
credit(entry, rank, fields.to_h { [it, result[it]] }.merge(rank_key => rank, 'sources' => [*entry['sources'], source]))
|
|
483
556
|
end
|
|
557
|
+
self
|
|
484
558
|
end
|
|
485
559
|
|
|
486
|
-
#
|
|
487
|
-
|
|
560
|
+
# @return [Array<Hash>] the merged entries, highest RRF score first
|
|
561
|
+
#
|
|
562
|
+
def results = @entries.values.sort_by { -it['rrf_score'] }
|
|
563
|
+
|
|
564
|
+
private
|
|
565
|
+
|
|
566
|
+
# @param result [Hash] The first result seen for a node
|
|
567
|
+
# @return [Hash] an entry with the node's fields and no score yet
|
|
568
|
+
#
|
|
569
|
+
def blank_entry(result)
|
|
570
|
+
%w[id content access_count created_at occurred_at token_count].to_h { [it, result[it]] }.merge(
|
|
571
|
+
'similarity' => 0.0, 'text_rank' => 0.0, 'tag_depth_score' => 0.0, 'matched_tags' => [],
|
|
572
|
+
'rrf_score' => 0.0, 'vector_rank' => nil, 'fulltext_rank' => nil, 'tag_rank' => nil, 'sources' => []
|
|
573
|
+
)
|
|
574
|
+
end
|
|
575
|
+
|
|
576
|
+
# Add 1/(k + rank) to the entry's RRF score and set the source's fields
|
|
577
|
+
#
|
|
578
|
+
# @param entry [Hash] Merged entry (modified in-place)
|
|
579
|
+
# @param rank [Integer] 1-based rank in the source
|
|
580
|
+
# @param fields [Hash] Fields the source sets
|
|
581
|
+
# @return [Hash] the entry
|
|
582
|
+
#
|
|
583
|
+
def credit(entry, rank, fields)
|
|
584
|
+
entry['rrf_score'] += 1.0 / (RRF_K + rank)
|
|
585
|
+
entry.merge!(fields)
|
|
586
|
+
end
|
|
488
587
|
end
|
|
489
588
|
end
|
|
490
589
|
end
|