/** * Advanced Multi-Factor Search Ranking Module (SMCP-087) * * Implements a sophisticated multi-factor ranking algorithm inspired by claude-context-local. * Combines 7+ ranking signals for significantly better search result quality: * * 1. Base similarity score (from vector/hybrid search) * 2. Query intent detection (via SMCP-085) * 3. Chunk type boosting (dynamic based on intent) * 4. Name matching with CamelCase/snake_case awareness * 5. Path/filename relevance * 6. Docstring/comment presence bonus * 7. Complexity penalty for oversized chunks * * @module advancedRanking */ import { type QueryIntent, type IntentDetectionConfig, type ChunkTypeBoosts } from './queryIntent.js'; /** * Result metadata required for advanced ranking. * Extends basic search result with optional semantic metadata. */ export interface RankableResult { /** Unique identifier for the result */ id: string; /** Base similarity/relevance score from search (0-1) */ score: number; /** Text content of the chunk */ text: string; /** File path (relative or absolute) */ path: string; /** Chunk type: function, class, method, module, etc. */ chunkType?: string; /** Name of the code element (function/class/method name) */ chunkName?: string; /** Parent name (e.g., class name for a method) */ chunkParent?: string; /** Semantic tags associated with the chunk */ chunkTags?: string[]; /** Docstring or documentation for the chunk */ chunkDocstring?: string; /** Start line number in the file */ startLine?: number; /** End line number in the file */ endLine?: number; /** Programming language */ chunkLanguage?: string; } /** * Result of advanced ranking with detailed scoring breakdown. */ export interface RankedResult { /** The original result */ result: RankableResult; /** Original score before ranking adjustments */ originalScore: number; /** Final score after all ranking factors applied */ finalScore: number; /** Breakdown of individual ranking factors */ factors: RankingFactors; /** Detected query intent (if applicable) */ intent?: QueryIntent; } /** * Individual ranking factor values. * Each factor is a multiplier (1.0 = no effect). */ export interface RankingFactors { /** Base similarity score (not a multiplier, absolute value 0-1) */ baseScore: number; /** Chunk type boost based on query intent */ chunkTypeBoost: number; /** Name matching boost */ nameBoost: number; /** Path/filename relevance boost */ pathBoost: number; /** Tag overlap boost */ tagBoost: number; /** Docstring presence bonus */ docstringBonus: number; /** Complexity penalty for oversized chunks */ complexityPenalty: number; } /** * Configuration for advanced ranking behavior. */ export interface AdvancedRankingConfig { /** Enable/disable advanced ranking (default: true) */ enabled: boolean; /** Intent detection configuration */ intentConfig?: Partial; /** Weight adjustments for ranking factors (multipliers on the boost values) */ weights?: Partial; /** Chunk size thresholds for complexity penalty */ complexityThresholds?: { /** Chunk size (chars) above which mild penalty applies (default: 2000) */ mild: number; /** Chunk size (chars) above which strong penalty applies (default: 4000) */ strong: number; }; /** Docstring bonus value (default: 1.05) */ docstringBonusValue?: number; } /** * Weight multipliers for each ranking factor. * Higher weight = more influence on final ranking. */ export interface RankingWeights { /** Weight for chunk type boost (default: 1.0) */ chunkType: number; /** Weight for name matching (default: 1.0) */ name: number; /** Weight for path relevance (default: 1.0) */ path: number; /** Weight for tag overlap (default: 1.0) */ tag: number; /** Weight for docstring bonus (default: 1.0) */ docstring: number; /** Weight for complexity penalty (default: 1.0) */ complexity: number; } /** * Default configuration for advanced ranking. */ export declare const DEFAULT_RANKING_CONFIG: AdvancedRankingConfig; /** * Apply advanced multi-factor ranking to search results. * * This is the main entry point for advanced ranking. It: * 1. Detects query intent * 2. Calculates all ranking factors for each result * 3. Computes final scores * 4. Returns results sorted by final score * * @param query - The search query string * @param results - Search results to rank * @param config - Optional ranking configuration * @returns Ranked results with scoring breakdown * * @example * ```typescript * const results = await searchCode(query); * const ranked = applyAdvancedRanking(query, results); * // ranked[0] is now the most relevant result * ``` */ export declare function applyAdvancedRanking(query: string, results: RankableResult[], config?: Partial): RankedResult[]; /** * Calculate chunk type boost based on detected query intent. * * @param chunkType - The type of chunk (function, class, method, etc.) * @param boosts - Boost factors from intent detection * @returns Boost multiplier (1.0 = no boost) */ export declare function calculateChunkTypeBoost(chunkType: string | undefined, boosts: ChunkTypeBoosts): number; /** * Calculate name matching boost based on query-name token overlap. * * Supports CamelCase and snake_case tokenization for robust matching. * * @param name - Name of the code element * @param originalQuery - Original query string * @param queryTokens - Normalized query tokens * @returns Boost multiplier (1.0 = no match, up to 1.4 for exact match) */ export declare function calculateNameBoost(name: string | undefined, originalQuery: string, queryTokens: string[]): number; /** * Calculate path/filename relevance boost. * * Checks for token overlap between query and file path components. * * @param filePath - File path (relative or absolute) * @param queryTokens - Normalized query tokens * @returns Boost multiplier (1.0 = no match, up to MAX_PATH_BOOST) */ export declare function calculatePathBoost(filePath: string | undefined, queryTokens: string[]): number; /** * Calculate docstring presence bonus. * * @param docstring - Documentation string (if present) * @param chunkType - Type of chunk * @param isEntityQuery - Whether query looks like an entity/class name * @param bonusValue - Bonus multiplier for documented chunks * @returns Bonus multiplier (1.0 = no bonus) */ export declare function calculateDocstringBonus(docstring: string | undefined, chunkType: string | undefined, isEntityQuery: boolean, bonusValue?: number): number; /** * Calculate complexity penalty for oversized chunks. * * Large chunks may be too specific or contain too much context, * making them less useful as search results. * * @param text - Chunk text content * @param thresholds - Size thresholds for penalty levels * @returns Penalty multiplier (1.0 = no penalty, <1.0 = penalized) */ export declare function calculateComplexityPenalty(text: string | undefined, thresholds: { mild: number; strong: number; }): number; /** * Create a ranking function with pre-configured settings. * * @param config - Ranking configuration * @returns Configured ranking function * * @example * ```typescript * const rank = createRanker({ weights: { name: 1.5 } }); * const ranked = rank('auth handler', results); * ``` */ export declare function createRanker(config?: Partial): (query: string, results: RankableResult[]) => RankedResult[]; /** * Extract just the final scores from ranked results. * * @param rankedResults - Results from applyAdvancedRanking * @returns Array of {id, score} pairs */ export declare function extractScores(rankedResults: RankedResult[]): Array<{ id: string; score: number; }>; /** * Get the top N results from ranking. * * @param rankedResults - Results from applyAdvancedRanking * @param n - Number of top results to return * @returns Top N ranked results */ export declare function getTopResults(rankedResults: RankedResult[], n: number): RankedResult[]; /** * Calculate ranking factor summary statistics. * * Useful for debugging and understanding ranking behavior. * * @param rankedResults - Results from applyAdvancedRanking * @returns Summary statistics for each factor */ export declare function getRankingStats(rankedResults: RankedResult[]): { factorAverages: Record; factorRanges: Record; scoreImprovement: { average: number; max: number; rankChanges: number; }; }; //# sourceMappingURL=advancedRanking.d.ts.map