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.
- 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 +14 -14
- data/.reek.yml +104 -0
- data/.rubocop.yml +0 -11
- data/.ruby-version +1 -0
- data/CHANGELOG.md +160 -98
- data/README.md +22 -17
- data/SETUP.md +49 -46
- data/_typos.toml +17 -0
- data/bin/htm +18 -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 +238 -7
- data/db/seed_data/README.md +11 -11
- data/db/seeds.rb +11 -11
- data/docs/api/database.md +8 -8
- data/docs/api/embedding-service.md +138 -262
- data/docs/api/htm.md +128 -12
- data/docs/api/index.md +8 -8
- data/docs/api/long-term-memory.md +8 -19
- data/docs/api/working-memory.md +34 -46
- 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 +2 -2
- data/docs/architecture/overview.md +3 -3
- data/docs/assets/images/project-structure.svg +2 -2
- data/docs/database/INDEX.md +113 -0
- data/docs/database/README.md +60 -176
- 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 +6 -6
- data/docs/development/index.md +15 -17
- data/docs/development/schema.md +43 -14
- data/docs/development/setup.md +60 -70
- data/docs/development/testing.md +57 -65
- data/docs/examples/basic-usage.md +9 -9
- data/docs/examples/config-files.md +8 -8
- data/docs/examples/file-loading.md +12 -12
- 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 +24 -22
- data/docs/guides/adding-memories.md +14 -3
- data/docs/guides/cli.md +458 -0
- data/docs/guides/configuration.md +72 -37
- data/docs/guides/epistemic-status.md +138 -0
- data/docs/guides/event-time.md +106 -0
- data/docs/guides/file-loading.md +26 -22
- data/docs/guides/getting-started.md +21 -17
- data/docs/guides/long-term-memory.md +1 -1
- data/docs/guides/mcp-server.md +416 -173
- data/docs/guides/propositions.md +18 -29
- data/docs/guides/recalling-memories.md +22 -7
- data/docs/guides/robot-teams.md +96 -0
- data/docs/guides/search-strategies.md +10 -7
- data/docs/guides/tags.md +19 -19
- 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 +13 -13
- data/docs/robots/robot-groups.md +9 -9
- data/docs/robots/two-tier-memory.md +13 -26
- data/docs/setup_local_database.md +33 -31
- data/examples/00_create_examples_db.rb +20 -7
- data/examples/01_basic_usage.rb +20 -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 +12 -12
- data/examples/04_file_loader_usage.rb +15 -21
- data/examples/05_timeframe_demo.rb +282 -234
- data/examples/06_example_app/.loki +36 -0
- data/examples/06_example_app/app.rb +21 -33
- data/examples/07_cli_app/README.md +18 -18
- data/examples/07_cli_app/htm_cli.rb +25 -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 +92 -119
- data/examples/10_telemetry/README.md +3 -3
- data/examples/10_telemetry/SETUP_README.md +2 -2
- data/examples/10_telemetry/demo.rb +5 -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 +5 -4
- data/examples/11_robot_groups/same_process.rb +18 -17
- data/examples/12_rails_app/Gemfile +1 -1
- data/examples/12_rails_app/Gemfile.lock +146 -97
- data/examples/12_rails_app/README.md +21 -17
- data/examples/12_rails_app/app/controllers/chats_controller.rb +33 -63
- data/examples/12_rails_app/app/controllers/memories_controller.rb +7 -1
- data/examples/12_rails_app/app/controllers/messages_controller.rb +21 -58
- data/examples/12_rails_app/app/controllers/search_controller.rb +7 -2
- data/examples/12_rails_app/app/models/chat.rb +0 -33
- data/examples/12_rails_app/app/models/message.rb +0 -2
- data/examples/12_rails_app/app/views/chats/show.html.erb +2 -2
- data/examples/12_rails_app/app/views/files/new.html.erb +1 -1
- data/examples/12_rails_app/app/views/memories/_memory_card.html.erb +1 -1
- data/examples/12_rails_app/app/views/memories/new.html.erb +12 -0
- data/examples/12_rails_app/app/views/memories/show.html.erb +13 -0
- data/examples/12_rails_app/app/views/search/index.html.erb +18 -2
- data/examples/12_rails_app/config/initializers/ruby_llm.rb +11 -15
- 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 +163 -20
- data/examples/README.md +53 -44
- data/examples/examples_helper.rb +29 -5
- 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 -68
- 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 +99 -68
- data/lib/htm/config/coercion.rb +91 -0
- data/lib/htm/config/database.rb +81 -52
- 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 +45 -26
- data/lib/htm/config.rb +112 -297
- data/lib/htm/database.rb +305 -396
- data/lib/htm/database_docs.rb +149 -0
- data/lib/htm/embedding_service.rb +26 -66
- 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 +43 -31
- data/lib/htm/job_adapter.rb +78 -83
- data/lib/htm/jobs/failure_logging.rb +49 -0
- data/lib/htm/jobs/generate_embedding_job.rb +21 -28
- data/lib/htm/jobs/generate_propositions_job.rb +56 -28
- data/lib/htm/jobs/generate_relationships_job.rb +28 -24
- data/lib/htm/jobs/generate_tags_job.rb +32 -37
- 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 +76 -120
- data/lib/htm/long_term_memory/fulltext_search.rb +15 -36
- data/lib/htm/long_term_memory/hybrid_search.rb +471 -544
- data/lib/htm/long_term_memory/node_operations.rb +110 -81
- data/lib/htm/long_term_memory/relevance_scorer.rb +232 -237
- data/lib/htm/long_term_memory/tag_operations.rb +201 -130
- data/lib/htm/long_term_memory/vector_search.rb +33 -61
- data/lib/htm/long_term_memory.rb +5 -17
- 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 -14
- 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 +232 -283
- data/lib/htm/models/file_source.rb +35 -20
- data/lib/htm/models/node.rb +287 -193
- data/lib/htm/models/node_link.rb +97 -0
- data/lib/htm/models/node_relationship.rb +3 -2
- data/lib/htm/models/node_tag.rb +22 -2
- data/lib/htm/models/robot.rb +4 -8
- data/lib/htm/models/robot_node.rb +5 -2
- data/lib/htm/models/tag.rb +53 -207
- data/lib/htm/node_enrichment.rb +75 -0
- data/lib/htm/node_view.rb +295 -0
- data/lib/htm/observability.rb +114 -98
- data/lib/htm/proposition_service.rb +38 -74
- data/lib/htm/query_cache.rb +145 -91
- data/lib/htm/railtie.rb +3 -7
- 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 +128 -521
- 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 +95 -59
- data/lib/htm/sql_builder.rb +162 -53
- data/lib/htm/startup_prompt.rb +73 -0
- data/lib/htm/tag_service.rb +104 -109
- data/lib/htm/tag_tree.rb +206 -0
- data/lib/htm/telemetry.rb +15 -16
- data/lib/htm/timeframe.rb +27 -9
- data/lib/htm/timeframe_extractor.rb +77 -55
- data/lib/htm/timeline.rb +230 -0
- data/lib/htm/version.rb +1 -1
- data/lib/htm/workflows/remember_workflow.rb +145 -136
- data/lib/htm/working_memory/entry.rb +53 -0
- data/lib/htm/working_memory/store.rb +97 -0
- data/lib/htm/working_memory.rb +137 -139
- data/lib/htm/working_memory_channel.rb +90 -40
- data/lib/htm.rb +177 -501
- data/mkdocs.yml +100 -23
- data/scripts/install_local_database.sh +7 -6
- metadata +1032 -594
- data/.tbls.yml +0 -31
- data/Rakefile +0 -240
- 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 -345
- 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/examples/12_rails_app/app/models/model.rb +0 -5
- data/examples/12_rails_app/app/models/tool_call.rb +0 -5
- data/examples/12_rails_app/db/migrate/20250124000001_create_ruby_llm_tables.rb +0 -34
- data/examples/12_rails_app/db/migrate/20250124000002_create_models_table.rb +0 -28
- data/lib/htm/mcp/cli.rb +0 -583
- data/lib/htm/tasks.rb +0 -79
- data/lib/tasks/db.rake +0 -15
- data/lib/tasks/doc.rake +0 -301
- data/lib/tasks/files.rake +0 -285
- data/lib/tasks/htm.rake +0 -703
- data/lib/tasks/jobs.rake +0 -429
- data/lib/tasks/tags.rake +0 -184
- 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,99 +38,269 @@ 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
259
|
safe_limit = limit.to_i.clamp(1, MAX_HYBRID_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
|
-
)
|
|
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
|
-
|
|
70
|
-
{
|
|
71
|
-
'id' => result['id'],
|
|
72
|
-
'content' => result['content'],
|
|
73
|
-
'access_count' => result['access_count'],
|
|
74
|
-
'created_at' => result['created_at'],
|
|
75
|
-
'token_count' => result['token_count'],
|
|
76
|
-
'similarity' => 0.0,
|
|
77
|
-
'text_rank' => 0.0,
|
|
78
|
-
'tag_depth_score' => 0.0,
|
|
79
|
-
'matched_tags' => [],
|
|
80
|
-
'rrf_score' => 1.0 / (RRF_K + rank),
|
|
81
|
-
'vector_rank' => nil,
|
|
82
|
-
'fulltext_rank' => nil,
|
|
83
|
-
'tag_rank' => nil,
|
|
84
|
-
'sources' => []
|
|
85
|
-
}
|
|
86
|
-
end
|
|
87
|
-
|
|
88
|
-
# Hybrid search using Reciprocal Rank Fusion with retrieve-then-rerank
|
|
273
|
+
# Hybrid search using Reciprocal Rank Fusion
|
|
89
274
|
#
|
|
90
275
|
# Uses a single SQL CTE query instead of three round-trips:
|
|
91
|
-
# 1. Fulltext
|
|
92
|
-
#
|
|
93
|
-
#
|
|
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
|
|
94
281
|
#
|
|
95
|
-
# Trade-off: Queries with high semantic relevance but zero keyword/tag
|
|
96
|
-
# overlap will be missed. Use :vector strategy for pure semantic search.
|
|
97
|
-
#
|
|
98
|
-
# @param timeframe [nil, Range, Array<Range>] Time range(s) to search
|
|
99
282
|
# @param query [String] Search query
|
|
100
|
-
# @param limit [Integer] Maximum results
|
|
101
283
|
# @param embedding_service [Object] Service to generate query embedding
|
|
102
|
-
# @param
|
|
103
|
-
# @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)
|
|
104
286
|
# @return [Array<Hash>] Merged results with RRF scores
|
|
105
287
|
#
|
|
106
|
-
def search_hybrid_rrf(
|
|
107
|
-
tag_info
|
|
108
|
-
literals
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
embedding_literal: literals[:embedding_literal],
|
|
114
|
-
tag_literals: literals[:tag_literals],
|
|
115
|
-
additional_sql: filter_sql[:additional_sql],
|
|
116
|
-
additional_sql_n: filter_sql[:additional_sql_n],
|
|
117
|
-
candidate_limit: candidate_limit.to_i,
|
|
118
|
-
limit: limit.to_i
|
|
119
|
-
)
|
|
120
|
-
|
|
121
|
-
results = HTM.db.fetch(sql).all
|
|
122
|
-
top_results = post_process_rrf_results(results, tag_info[:tag_depth_map])
|
|
123
|
-
track_access(top_results.map { |r| r['id'] })
|
|
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))
|
|
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'] })
|
|
124
295
|
top_results
|
|
125
296
|
end
|
|
126
297
|
|
|
298
|
+
# @param query [String] Search query
|
|
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)
|
|
301
|
+
#
|
|
127
302
|
def extract_rrf_tag_info(query)
|
|
128
|
-
extraction =
|
|
303
|
+
extraction = query_tag_matches(query)
|
|
129
304
|
extracted_tags = extraction[:extracted] || []
|
|
130
305
|
matched_db_tags = extraction[:matched] || []
|
|
131
306
|
{
|
|
@@ -134,528 +309,280 @@ class HTM
|
|
|
134
309
|
}
|
|
135
310
|
end
|
|
136
311
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
312
|
+
# @param query [String] Search query
|
|
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
|
|
317
|
+
#
|
|
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
|
+
}
|
|
147
324
|
end
|
|
148
325
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
326
|
+
# @param value [Object] Value to put in SQL
|
|
327
|
+
# @return [String] the value as a quoted SQL literal
|
|
328
|
+
#
|
|
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)
|
|
334
|
+
#
|
|
335
|
+
def build_rrf_filter_sql(filters)
|
|
154
336
|
{
|
|
155
|
-
additional_sql:
|
|
156
|
-
additional_sql_n:
|
|
337
|
+
additional_sql: filters.and_sql,
|
|
338
|
+
additional_sql_n: filters.and_sql(table_alias: 'n')
|
|
157
339
|
}
|
|
158
340
|
end
|
|
159
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
|
|
345
|
+
#
|
|
160
346
|
def post_process_rrf_results(results, tag_depth_map)
|
|
161
|
-
results.map
|
|
162
|
-
r = row.transform_keys(&:to_s)
|
|
163
|
-
r['matched_tags'] = r.key?('matched_tags') ? parse_pg_array(r['matched_tags']) : []
|
|
164
|
-
r['tag_depth_score'] = r['matched_tags'].any? && tag_depth_map.any? ?
|
|
165
|
-
calculate_tag_depth_score(r['matched_tags'], tag_depth_map) : 0.0
|
|
166
|
-
sources = []
|
|
167
|
-
sources << 'vector' if r['vector_rank']
|
|
168
|
-
sources << 'fulltext' if r['fulltext_rank']
|
|
169
|
-
sources << 'tags' if r['tag_rank']
|
|
170
|
-
r['sources'] = sources
|
|
171
|
-
r['similarity'] = (r['similarity'] || 0.0).to_f
|
|
172
|
-
r['text_rank'] = (r['text_rank'] || 0.0).to_f
|
|
173
|
-
r['rrf_score'] = r['rrf_score'].to_f
|
|
174
|
-
r['vector_rank'] ||= nil
|
|
175
|
-
r['fulltext_rank'] ||= nil
|
|
176
|
-
r['tag_rank'] ||= nil
|
|
177
|
-
|
|
178
|
-
r
|
|
179
|
-
end
|
|
347
|
+
results.map { RrfRows.normalize(it, tag_depth_map) }
|
|
180
348
|
end
|
|
181
349
|
|
|
182
350
|
# Build the single-CTE SQL for hybrid search
|
|
183
351
|
#
|
|
184
|
-
#
|
|
185
|
-
# - Always: fulltext (tsvector + trigram) candidates
|
|
186
|
-
# - If tag_literals: tag candidates CTE
|
|
187
|
-
# - If embedding_literal: vector rerank CTE (only on candidate IDs)
|
|
188
|
-
#
|
|
189
|
-
# @param query_literal [String] SQL-escaped query string
|
|
190
|
-
# @param embedding_literal [String, nil] SQL-escaped embedding vector (nil to skip vector)
|
|
191
|
-
# @param tag_literals [String, nil] Comma-separated SQL-escaped tag names (nil to skip tags)
|
|
192
|
-
# @param additional_sql [String] Extra WHERE conditions (no table alias)
|
|
193
|
-
# @param additional_sql_n [String] Extra WHERE conditions (with 'n.' alias)
|
|
194
|
-
# @param candidate_limit [Integer] Max candidates per source
|
|
195
|
-
# @param limit [Integer] Final result limit
|
|
352
|
+
# @param parts [Hash] The members of RrfSql::Query
|
|
196
353
|
# @return [String] Complete SQL query
|
|
197
354
|
#
|
|
198
|
-
def build_hybrid_cte_sql(
|
|
199
|
-
limit:)
|
|
200
|
-
has_embedding = !embedding_literal.nil?
|
|
201
|
-
has_tags = !tag_literals.nil?
|
|
202
|
-
|
|
203
|
-
ctes = fulltext_ctes_sql(query_literal, additional_sql, candidate_limit)
|
|
204
|
-
ctes << tag_candidates_cte_sql(tag_literals, additional_sql_n, candidate_limit) if has_tags
|
|
205
|
-
ctes << candidate_ids_cte_sql(has_tags)
|
|
206
|
-
ctes << vector_rerank_cte_sql(embedding_literal) if has_embedding
|
|
207
|
-
ctes.concat ranked_ctes_sql(has_tags, has_embedding)
|
|
208
|
-
ctes << rrf_scores_cte_sql(has_tags, has_embedding)
|
|
209
|
-
|
|
210
|
-
final_fields = build_final_select_fields(has_tags, has_embedding)
|
|
211
|
-
|
|
212
|
-
<<~SQL
|
|
213
|
-
WITH #{ctes.join(",\n")}
|
|
214
|
-
SELECT #{final_fields.join(",\n ")}
|
|
215
|
-
FROM rrf_scores rrf
|
|
216
|
-
JOIN nodes n ON n.id = rrf.id
|
|
217
|
-
ORDER BY rrf.rrf_score DESC
|
|
218
|
-
LIMIT #{limit}
|
|
219
|
-
SQL
|
|
220
|
-
end
|
|
221
|
-
|
|
222
|
-
def fulltext_ctes_sql(query_literal, additional_sql, candidate_limit)
|
|
223
|
-
[<<~SQL.chomp, <<~SQL.chomp, <<~SQL.chomp]
|
|
224
|
-
tsvector_matches AS (
|
|
225
|
-
SELECT id,
|
|
226
|
-
(1.0 + ts_rank(to_tsvector('english', content), plainto_tsquery('english', #{query_literal}))) as text_rank
|
|
227
|
-
FROM nodes
|
|
228
|
-
WHERE deleted_at IS NULL
|
|
229
|
-
AND to_tsvector('english', content) @@ plainto_tsquery('english', #{query_literal})
|
|
230
|
-
#{additional_sql}
|
|
231
|
-
)
|
|
232
|
-
SQL
|
|
233
|
-
trigram_matches AS (
|
|
234
|
-
SELECT id,
|
|
235
|
-
similarity(content, #{query_literal}) as text_rank
|
|
236
|
-
FROM nodes
|
|
237
|
-
WHERE deleted_at IS NULL
|
|
238
|
-
AND similarity(content, #{query_literal}) >= 0.1
|
|
239
|
-
AND id NOT IN (SELECT id FROM tsvector_matches)
|
|
240
|
-
#{additional_sql}
|
|
241
|
-
)
|
|
242
|
-
SQL
|
|
243
|
-
fulltext_candidates AS (
|
|
244
|
-
SELECT * FROM tsvector_matches
|
|
245
|
-
UNION ALL
|
|
246
|
-
SELECT * FROM trigram_matches
|
|
247
|
-
ORDER BY text_rank DESC
|
|
248
|
-
LIMIT #{candidate_limit}
|
|
249
|
-
)
|
|
250
|
-
SQL
|
|
251
|
-
end
|
|
355
|
+
def build_hybrid_cte_sql(**) = RrfSql::Query.new(**).to_sql
|
|
252
356
|
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
FROM nodes n
|
|
258
|
-
JOIN node_tags nt ON nt.node_id = n.id
|
|
259
|
-
JOIN tags t ON t.id = nt.tag_id
|
|
260
|
-
WHERE n.deleted_at IS NULL
|
|
261
|
-
AND t.name IN (#{tag_literals})
|
|
262
|
-
#{additional_sql_n}
|
|
263
|
-
GROUP BY n.id
|
|
264
|
-
LIMIT #{candidate_limit}
|
|
265
|
-
)
|
|
266
|
-
SQL
|
|
267
|
-
end
|
|
268
|
-
|
|
269
|
-
def candidate_ids_cte_sql(has_tags)
|
|
270
|
-
id_sources = ["SELECT id FROM fulltext_candidates"]
|
|
271
|
-
id_sources << "SELECT id FROM tag_candidates" if has_tags
|
|
272
|
-
<<~SQL.chomp
|
|
273
|
-
all_candidate_ids AS (
|
|
274
|
-
#{id_sources.join("\n UNION\n ")}
|
|
275
|
-
)
|
|
276
|
-
SQL
|
|
277
|
-
end
|
|
278
|
-
|
|
279
|
-
def vector_rerank_cte_sql(embedding_literal)
|
|
280
|
-
<<~SQL.chomp
|
|
281
|
-
vector_rerank AS (
|
|
282
|
-
SELECT id,
|
|
283
|
-
1 - (embedding <=> #{embedding_literal}::vector) as similarity
|
|
284
|
-
FROM nodes
|
|
285
|
-
WHERE id IN (SELECT id FROM all_candidate_ids)
|
|
286
|
-
AND embedding IS NOT NULL
|
|
287
|
-
)
|
|
288
|
-
SQL
|
|
289
|
-
end
|
|
290
|
-
|
|
291
|
-
def ranked_ctes_sql(has_tags, has_embedding)
|
|
292
|
-
ctes = [<<~SQL.chomp]
|
|
293
|
-
fulltext_ranked AS (
|
|
294
|
-
SELECT id, text_rank, ROW_NUMBER() OVER (ORDER BY text_rank DESC) as rank
|
|
295
|
-
FROM fulltext_candidates
|
|
296
|
-
)
|
|
297
|
-
SQL
|
|
298
|
-
ctes << <<~SQL.chomp if has_tags
|
|
299
|
-
tag_ranked AS (
|
|
300
|
-
SELECT id, matched_tags, ROW_NUMBER() OVER (ORDER BY tag_match_count DESC) as rank
|
|
301
|
-
FROM tag_candidates
|
|
302
|
-
)
|
|
303
|
-
SQL
|
|
304
|
-
ctes << <<~SQL.chomp if has_embedding
|
|
305
|
-
vector_ranked AS (
|
|
306
|
-
SELECT id, similarity, ROW_NUMBER() OVER (ORDER BY similarity DESC) as rank
|
|
307
|
-
FROM vector_rerank
|
|
308
|
-
)
|
|
309
|
-
SQL
|
|
310
|
-
ctes
|
|
311
|
-
end
|
|
357
|
+
# @param extracted_tags [Array<String>] Tags extracted from query
|
|
358
|
+
# @return [Hash] Map of tag/prefix to depth info (see TagDepth.map)
|
|
359
|
+
#
|
|
360
|
+
def build_tag_depth_map(extracted_tags) = TagDepth.map(extracted_tags)
|
|
312
361
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
score_terms << "COALESCE(1.0/(#{RRF_K} + tr.rank), 0)" if has_tags
|
|
319
|
-
score_terms << "COALESCE(1.0/(#{RRF_K} + vr.rank), 0)" if has_embedding
|
|
320
|
-
fields = ["COALESCE(#{rrf_id.join(', ')}) as id", "#{score_terms.join(' + ')} as rrf_score",
|
|
321
|
-
"fr.rank as fulltext_rank", "fr.text_rank"]
|
|
322
|
-
fields << "tr.rank as tag_rank" << "tr.matched_tags" if has_tags
|
|
323
|
-
fields << "vr.rank as vector_rank" << "vr.similarity" if has_embedding
|
|
324
|
-
from = "fulltext_ranked fr"
|
|
325
|
-
from += "\n FULL OUTER JOIN tag_ranked tr ON fr.id = tr.id" if has_tags
|
|
326
|
-
coalesce_id = has_tags ? "COALESCE(fr.id, tr.id)" : "fr.id"
|
|
327
|
-
from += "\n FULL OUTER JOIN vector_ranked vr ON #{coalesce_id} = vr.id" if has_embedding
|
|
328
|
-
<<~SQL.chomp
|
|
329
|
-
rrf_scores AS (
|
|
330
|
-
SELECT #{fields.join(",\n ")}
|
|
331
|
-
FROM #{from}
|
|
332
|
-
)
|
|
333
|
-
SQL
|
|
334
|
-
end
|
|
362
|
+
# @param matched_tags [Array<String>] Tags the node has that matched
|
|
363
|
+
# @param tag_depth_map [Hash] Map of tag/prefix to depth info
|
|
364
|
+
# @return [Float] Normalized score (0.0 to 1.0), see TagDepth.score
|
|
365
|
+
#
|
|
366
|
+
def calculate_tag_depth_score(matched_tags, tag_depth_map) = TagDepth.score(matched_tags, tag_depth_map)
|
|
335
367
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
fields << "rrf.vector_rank" << "COALESCE(rrf.similarity, 0.0) as similarity" if has_embedding
|
|
341
|
-
fields
|
|
342
|
-
end
|
|
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
|
|
370
|
+
#
|
|
371
|
+
def parse_pg_array(pg_array) = RrfRows.parse_pg_array(pg_array)
|
|
343
372
|
|
|
344
|
-
#
|
|
373
|
+
# Merge three result sets using Reciprocal Rank Fusion
|
|
345
374
|
#
|
|
346
|
-
#
|
|
347
|
-
# @param embedding_service [Object] Service to generate embeddings
|
|
348
|
-
# @param timeframe [nil, Range, Array<Range>] Time filter
|
|
349
|
-
# @param metadata [Hash] Metadata filter
|
|
350
|
-
# @param limit [Integer] Maximum candidates
|
|
351
|
-
# @return [Array<Hash>] Results with similarity scores
|
|
375
|
+
# RRF score = Σ 1/(k + rank) for each list where the item appears
|
|
352
376
|
#
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
conditions = ["embedding IS NOT NULL", "deleted_at IS NULL"]
|
|
370
|
-
conditions << timeframe_condition if timeframe_condition
|
|
371
|
-
conditions << metadata_condition if metadata_condition
|
|
377
|
+
# Items appearing in multiple lists naturally get higher scores
|
|
378
|
+
# because they receive contributions from multiple ranks.
|
|
379
|
+
#
|
|
380
|
+
# @param vector_results [Array<Hash>] Vector search results (ordered by similarity)
|
|
381
|
+
# @param fulltext_results [Array<Hash>] Fulltext search results (ordered by text_rank)
|
|
382
|
+
# @param tag_results [Array<Hash>] Tag search results (ordered by tag_depth_score)
|
|
383
|
+
# @return [Array<Hash>] Merged results sorted by RRF score
|
|
384
|
+
#
|
|
385
|
+
def merge_with_rrf(vector_results, fulltext_results, tag_results = [])
|
|
386
|
+
RrfMerger.new
|
|
387
|
+
.add('vector', vector_results)
|
|
388
|
+
.add('fulltext', fulltext_results)
|
|
389
|
+
.add('tags', tag_results)
|
|
390
|
+
.results
|
|
391
|
+
end
|
|
372
392
|
|
|
373
|
-
|
|
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
|
|
374
417
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
LIMIT ?
|
|
384
|
-
SQL
|
|
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
|
|
385
426
|
|
|
386
|
-
|
|
387
|
-
|
|
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
|
|
388
435
|
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
# @return [Array<Hash>] Results with text rank scores
|
|
396
|
-
#
|
|
397
|
-
def fetch_fulltext_candidates(query:, timeframe:, metadata:, limit:)
|
|
398
|
-
timeframe_condition = HTM::SqlBuilder.timeframe_condition(timeframe)
|
|
399
|
-
metadata_condition = HTM::SqlBuilder.metadata_condition(metadata)
|
|
400
|
-
|
|
401
|
-
additional_conditions = []
|
|
402
|
-
additional_conditions << timeframe_condition if timeframe_condition
|
|
403
|
-
additional_conditions << metadata_condition if metadata_condition
|
|
404
|
-
additional_sql = additional_conditions.any? ? "AND #{additional_conditions.join(' AND ')}" : ""
|
|
405
|
-
|
|
406
|
-
# Combined tsvector + trigram search (same as fulltext_search.rb)
|
|
407
|
-
# Escape the query for safe interpolation in trigram comparisons
|
|
408
|
-
query_literal = HTM.db.literal(query)
|
|
409
|
-
sql = <<~SQL
|
|
410
|
-
WITH tsvector_matches AS (
|
|
411
|
-
SELECT id, content, access_count, created_at, token_count,
|
|
412
|
-
(1.0 + ts_rank(to_tsvector('english', content), plainto_tsquery('english', #{query_literal}))) as text_rank
|
|
413
|
-
FROM nodes
|
|
414
|
-
WHERE deleted_at IS NULL
|
|
415
|
-
AND to_tsvector('english', content) @@ plainto_tsquery('english', #{query_literal})
|
|
416
|
-
#{additional_sql}
|
|
417
|
-
),
|
|
418
|
-
trigram_matches AS (
|
|
419
|
-
SELECT id, content, access_count, created_at, token_count,
|
|
420
|
-
similarity(content, #{query_literal}) as text_rank
|
|
421
|
-
FROM nodes
|
|
422
|
-
WHERE deleted_at IS NULL
|
|
423
|
-
AND similarity(content, #{query_literal}) >= 0.1
|
|
424
|
-
AND id NOT IN (SELECT id FROM tsvector_matches)
|
|
425
|
-
#{additional_sql}
|
|
426
|
-
),
|
|
427
|
-
combined AS (
|
|
428
|
-
SELECT * FROM tsvector_matches
|
|
429
|
-
UNION ALL
|
|
430
|
-
SELECT * FROM trigram_matches
|
|
431
|
-
)
|
|
432
|
-
SELECT id, content, access_count, created_at, token_count, text_rank
|
|
433
|
-
FROM combined
|
|
434
|
-
ORDER BY text_rank DESC
|
|
435
|
-
LIMIT ?
|
|
436
|
-
SQL
|
|
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?('}')
|
|
437
442
|
|
|
438
|
-
|
|
443
|
+
text[1..-2].split(',').map { it.gsub(/^"|"$/, '') }
|
|
444
|
+
end
|
|
445
|
+
end
|
|
439
446
|
end
|
|
440
447
|
|
|
441
|
-
#
|
|
442
|
-
#
|
|
443
|
-
# Extracts tags from the query, finds nodes with matching tags,
|
|
444
|
-
# and scores based on hierarchical depth match.
|
|
448
|
+
# Hierarchical depth scoring of the tags a node matched
|
|
445
449
|
#
|
|
446
450
|
# Scoring: For a query tag "database:postgresql:extensions" (3 levels):
|
|
447
451
|
# - Node with "database:postgresql:extensions" = 3/3 = 1.0
|
|
448
452
|
# - Node with "database:postgresql" = 2/3 = 0.67
|
|
449
453
|
# - Node with "database" = 1/3 = 0.33
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
# Build a map of tag prefixes to their max depth
|
|
466
|
-
# This allows us to score partial matches
|
|
467
|
-
tag_depth_map = build_tag_depth_map(extracted_tags)
|
|
468
|
-
|
|
469
|
-
# Use matched_db_tags if available, otherwise use extracted_tags
|
|
470
|
-
search_tags = matched_db_tags.any? ? matched_db_tags : extracted_tags
|
|
471
|
-
|
|
472
|
-
return [] if search_tags.empty?
|
|
473
|
-
|
|
474
|
-
# Build filter conditions
|
|
475
|
-
timeframe_condition = HTM::SqlBuilder.timeframe_condition(timeframe, table_alias: 'n')
|
|
476
|
-
metadata_condition = HTM::SqlBuilder.metadata_condition(metadata, table_alias: 'n')
|
|
477
|
-
|
|
478
|
-
additional_conditions = []
|
|
479
|
-
additional_conditions << timeframe_condition if timeframe_condition
|
|
480
|
-
additional_conditions << metadata_condition if metadata_condition
|
|
481
|
-
additional_sql = additional_conditions.any? ? "AND #{additional_conditions.join(' AND ')}" : ""
|
|
482
|
-
|
|
483
|
-
# Find nodes with matching tags
|
|
484
|
-
# Use Sequel's literal to safely quote tag names
|
|
485
|
-
tag_literals = search_tags.map { |tag| HTM.db.literal(tag) }.join(', ')
|
|
486
|
-
|
|
487
|
-
sql = <<~SQL
|
|
488
|
-
SELECT DISTINCT n.id, n.content, n.access_count, n.created_at, n.token_count,
|
|
489
|
-
array_agg(t.name) as matched_tags
|
|
490
|
-
FROM nodes n
|
|
491
|
-
JOIN node_tags nt ON nt.node_id = n.id
|
|
492
|
-
JOIN tags t ON t.id = nt.tag_id
|
|
493
|
-
WHERE n.deleted_at IS NULL
|
|
494
|
-
AND t.name IN (#{tag_literals})
|
|
495
|
-
#{additional_sql}
|
|
496
|
-
GROUP BY n.id, n.content, n.access_count, n.created_at, n.token_count
|
|
497
|
-
LIMIT ?
|
|
498
|
-
SQL
|
|
499
|
-
|
|
500
|
-
results = HTM.db.fetch(sql, limit).all
|
|
501
|
-
|
|
502
|
-
# Calculate depth scores for each result
|
|
503
|
-
results.map do |result|
|
|
504
|
-
matched_tags = parse_pg_array(result[:matched_tags])
|
|
505
|
-
depth_score = calculate_tag_depth_score(matched_tags, tag_depth_map)
|
|
506
|
-
|
|
507
|
-
result.transform_keys(&:to_s).merge('tag_depth_score' => depth_score, 'matched_tags' => matched_tags)
|
|
508
|
-
end
|
|
509
|
-
results.sort_by { |r| -r['tag_depth_score'] }
|
|
510
|
-
end
|
|
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
|
|
511
469
|
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
extracted_tags.each do |tag|
|
|
526
|
-
levels = tag.split(':')
|
|
527
|
-
max_depth = levels.size
|
|
528
|
-
|
|
529
|
-
# Add entry for each prefix level
|
|
530
|
-
(1..max_depth).each do |depth|
|
|
531
|
-
prefix = levels[0, depth].join(':')
|
|
532
|
-
# Keep the highest max_depth if prefix appears in multiple tags
|
|
533
|
-
if !depth_map.key?(prefix) || depth_map[prefix][:max_depth] < max_depth
|
|
534
|
-
depth_map[prefix] = { depth: depth, max_depth: max_depth }
|
|
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
|
|
535
483
|
end
|
|
536
484
|
end
|
|
537
|
-
end
|
|
538
485
|
|
|
539
|
-
|
|
540
|
-
|
|
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?
|
|
541
497
|
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
# @param tag_depth_map [Hash] Map of tag/prefix to depth info
|
|
549
|
-
# @return [Float] Normalized score (0.0 to 1.0)
|
|
550
|
-
#
|
|
551
|
-
def calculate_tag_depth_score(matched_tags, tag_depth_map)
|
|
552
|
-
return 0.0 if matched_tags.empty? || tag_depth_map.empty?
|
|
553
|
-
|
|
554
|
-
# Find the best depth match for each matched tag
|
|
555
|
-
best_score = 0.0
|
|
556
|
-
|
|
557
|
-
matched_tags.each do |tag|
|
|
558
|
-
if tag_depth_map.key?(tag)
|
|
559
|
-
info = tag_depth_map[tag]
|
|
560
|
-
# Score is depth / max_depth
|
|
561
|
-
# e.g., "database:postgresql" matching query "database:postgresql:extensions"
|
|
562
|
-
# gives 2/3 = 0.67
|
|
563
|
-
score = info[:depth].to_f / info[:max_depth]
|
|
564
|
-
best_score = [best_score, score].max
|
|
565
|
-
else
|
|
566
|
-
# Check if this tag is a parent of any extracted tag
|
|
567
|
-
tag_depth_map.each do |prefix, info|
|
|
568
|
-
if prefix.start_with?(tag + ':') || prefix == tag
|
|
569
|
-
score = tag.split(':').size.to_f / info[:max_depth]
|
|
570
|
-
best_score = [best_score, score].max
|
|
571
|
-
end
|
|
572
|
-
end
|
|
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
|
|
502
|
+
|
|
503
|
+
[best_score + multi_match_bonus, 1.0].min
|
|
573
504
|
end
|
|
574
|
-
end
|
|
575
505
|
|
|
576
|
-
|
|
577
|
-
|
|
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
|
|
578
518
|
|
|
579
|
-
|
|
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
|
|
580
530
|
end
|
|
581
531
|
|
|
582
|
-
#
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
# Handle raw PostgreSQL array format: {val1,val2,val3}
|
|
594
|
-
pg_str = pg_array.to_s
|
|
595
|
-
if pg_str.start_with?('{') && pg_str.end_with?('}')
|
|
596
|
-
pg_str[1..-2].split(',').map { |s| s.gsub(/^"|"$/, '') }
|
|
597
|
-
else
|
|
598
|
-
[pg_str]
|
|
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 = {}
|
|
599
543
|
end
|
|
600
|
-
end
|
|
601
544
|
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
vector_results.each_with_index { |r, i| merge_vector_rrf_entry(merged, r, i + 1) }
|
|
617
|
-
fulltext_results.each_with_index { |r, i| merge_fulltext_rrf_entry(merged, r, i + 1) }
|
|
618
|
-
tag_results.each_with_index { |r, i| merge_tag_rrf_entry(merged, r, i + 1) }
|
|
619
|
-
merged.values.sort_by { |r| -r['rrf_score'] }
|
|
620
|
-
end
|
|
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]))
|
|
556
|
+
end
|
|
557
|
+
self
|
|
558
|
+
end
|
|
621
559
|
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
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
|
|
627
565
|
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
merged[id]['sources'] << 'fulltext'
|
|
636
|
-
else
|
|
637
|
-
merged[id] = init_rrf_entry(result, rank).merge(
|
|
638
|
-
'text_rank' => result['text_rank'], 'fulltext_rank' => rank, 'sources' => ['fulltext']
|
|
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' => []
|
|
639
573
|
)
|
|
640
574
|
end
|
|
641
|
-
end
|
|
642
575
|
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
merged[id] = init_rrf_entry(result, rank).merge(
|
|
654
|
-
'tag_depth_score' => result['tag_depth_score'],
|
|
655
|
-
'matched_tags' => result['matched_tags'],
|
|
656
|
-
'tag_rank' => rank,
|
|
657
|
-
'sources' => ['tags']
|
|
658
|
-
)
|
|
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)
|
|
659
586
|
end
|
|
660
587
|
end
|
|
661
588
|
end
|