/** * ContextualSearchRLM - Optimized Contextual Search Service * * Implementation inspired by parallel search patterns, * adapted for the RLM ecosystem with: * * Features: * - Automatic project indexing with per-projectId namespace * - Hybrid search (vector + keyword) with RRF (Reciprocal Rank Fusion) * - Parallel search across multiple files * - Returns only relevant excerpts with context * - Multi-level intelligent cache * - Integration with existing embedding service * * Architecture: * - Uses PostgreSQL as single backend (vector + keyword + cache) * - Per-projectId namespace for isolation * - Embedding reuse across projects */ import { SearchResult } from "@massa-th0th/shared"; import { getKeywordSearch } from "../../data/keyword/keyword-search-factory.js"; import { getVectorStore } from "../../data/vector/vector-store-factory.js"; import { getSearchCache } from "./cache-factory.js"; import { getSearchAnalytics } from "./analytics-factory.js"; import { SearchAnalytics } from "./search-analytics.js"; import type { SearchAnalyticsPg } from "./search-analytics-pg.js"; import { getSymbolRepository } from "../../data/symbol/symbol-repository-factory.js"; import type { SynapseManager } from "../synapse/synapse-manager.js"; import type { SessionRegistry } from "../synapse/session/session-registry.js"; /** * ContextualSearchRLM - Main contextual search service */ export declare class ContextualSearchRLM { private keywordSearch; private vectorStore; private indexManager; private searchCache; private analytics; private symbolRepo; private fileFilterCache; /** Phase 2: query understanding (LLM rewrite + HyDE). Default-off, silent-degrade. */ private queryUnderstanding; private readonly RRF_K; private initialized; private static indexingLocks; /** * Optional test/extension seam: pre-resolved dependencies. When provided, * `ensureInitialized` skips the factory calls (which are process-wide * mock.module targets in the full test suite) and uses these instances * directly. Production callers pass nothing and resolve via factories. */ private readonly injectedDeps?; constructor(deps?: { keywordSearch?: Awaited>; vectorStore?: Awaited>; searchCache?: Awaited>; analytics?: Awaited>; symbolRepo?: Awaited>; sessionRegistry?: Pick; synapseManager?: Pick; }); private ensureInitialized; /** * Load and parse .gitignore file (delegates to shared ignore-patterns module) */ private loadGitignore; /** * Index an entire project * * @param projectPath - Path to the project * @param projectId - Unique project ID (namespace) * @returns Indexing statistics */ indexProject(projectPath: string, projectId: string, options?: { onProgress?: (current: number, total: number) => void; }): Promise<{ filesIndexed: number; chunksIndexed: number; errors: number; }>; private _indexProjectInternal; /** * Check if index is stale and optionally trigger reindexing */ ensureFreshIndex(projectId: string, projectPath: string, options?: { allowFullReindex?: boolean; maxSyncFiles?: number; }): Promise<{ wasStale: boolean; reindexed: boolean; reason?: string; deferred?: boolean; filesPending?: number; }>; /** * Index a single file, splitting it into semantic chunks * * Uses the smart chunker which is language-aware: * - Markdown: splits by headings with hierarchy context * - JSON: splits by top-level keys * - YAML: splits by document separators or top-level keys * - Code: splits by functions/classes with preceding comments */ private indexFile; /** * Hybrid search (vector + keyword) with projectId filter */ search(query: string, projectId: string, options?: { maxResults?: number; minScore?: number; explainScores?: boolean; includeFilters?: string[]; excludeFilters?: string[]; /** Phase 2: Synapse session id forwarded for future Synapse-biased fusion. */ sessionId?: string; }): Promise; /** * Apply session state after the session-independent base result is cached. * Invalid and workspace-mismatched sessions return the exact base array. */ private applySynapseState; /** * Fuzzy-correct each non-stopword query term via the keyword store's * vocabulary. Returns the corrected query string (lowercased, space-joined), * or null when no term corrects to a different word or fuzzyCorrect is * unavailable. Only words of length >= 3 are considered (shorter tokens * can't be reliably corrected). */ private correctQuery; /** * Phase 7c: build the graph-neighbor RRF stream. BFS depth-2 over outgoing * memory-graph edges; resolved to SearchResults via the memory repository at * a fixed sub-hit score (0.45). * * Id-bridge fix (A3): graph edges connect MEMORY ids, but vector/code-search * results key on chunk ids (e.g. "projectId:path:0"). Seeding BFS with chunk * ids therefore silently omitted the stream for code queries — the primary * use case. We now bridge the two id spaces: collect graph seeds by (a) * trying the raw hit ids (preserves the original behavior for memory search * where memory ids already flow in), AND (b) mapping each code chunk to * memory ids that reference the same filePath/symbol via fullTextSearch. * This makes the graph stream participate for code queries while remaining * a silent-omit no-op when no bridged seeds resolve. * * Degradation (silent-omit): returns [] when the neighbor set is empty, the * graph store throws, or the memory repo returns nothing. The caller only * appends the stream when non-empty, so `resultSets.length` (and thus the * `search:reranked` streamCount) always reflects the real stream count. */ private buildGraphStream; /** * Reciprocal Rank Fusion (RRF) - Combines multiple result lists * * Now includes intelligent boosting: * - Keywords get higher weight when query contains function/class names * - Exact matches in keyword results get additional boost */ private fuseResults; /** * Generate detailed score explanation */ private generateScoreExplanation; /** * Add expanded context to results */ private addContextToResults; /** * Extract content preview (first lines) */ private extractPreview; /** * Calculate average score */ private calculateAvgScore; /** * Filter results by glob patterns */ private filterByPatterns; /** * Clear project index */ clearProjectIndex(projectId: string): Promise<{ deleted: number; }>; /** * Get project statistics */ getProjectStats(projectId: string): Promise<{ totalDocuments: number; totalSize: number; }>; /** * Warmup cache with common queries * * Pre-caches typical search patterns to improve initial search performance */ warmupCache(projectId: string, _projectPath: string, customQueries?: string[]): Promise<{ queriesWarmed: number; errors: number; }>; /** * Get analytics instance for querying metrics */ getAnalytics(): SearchAnalytics | SearchAnalyticsPg; } //# sourceMappingURL=contextual-search-rlm.d.ts.map