Repository navigation
fix(search): ground lexical identifier evidence #207
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,11 @@ import { type IndexMeta, readIndexMeta, validateIndexArtifacts } from './index-m | |
| import { hashFileContent, readReferenceManifest, type FileManifest } from './manifest.js'; | ||
| import { isPathWithin } from '../utils/project-discovery.js'; | ||
| import { isSourceBodyWithinInterval } from '../utils/source-interval.js'; | ||
| import { | ||
| findLexicalIdentifierOccurrences, | ||
| hasIdentifierCandidate, | ||
| maskComments | ||
| } from '../utils/tree-sitter.js'; | ||
| import { | ||
| InternalSourceResolver, | ||
| loadTsconfigCompilerOptions | ||
|
|
@@ -237,6 +242,7 @@ export class CodebaseSearcher { | |
|
|
||
| private importCentrality: Map<string, number> | null = null; | ||
| private indexedImports = new Map<string, Map<string, string[]>>(); | ||
| private rescueDeclaredNames: Set<string> | undefined; | ||
|
|
||
| constructor(rootPath: string) { | ||
| this.rootPath = rootPath; | ||
|
|
@@ -265,6 +271,7 @@ export class CodebaseSearcher { | |
| this.patternIntelligence = null; | ||
| this.importCentrality = null; | ||
| this.indexedImports.clear(); | ||
| this.rescueDeclaredNames = undefined; | ||
| } | ||
| if ( | ||
| this.initialized && | ||
|
|
@@ -783,6 +790,23 @@ export class CodebaseSearcher { | |
| .flatMap((name) => name.split('+')); | ||
| } | ||
|
|
||
| private indexedSymbolNames(chunk: CodeChunk): string[] { | ||
| return [...this.indexedDeclarationNames(chunk), ...(chunk.exports ?? [])]; | ||
| } | ||
|
|
||
| private lexicalRescueDeclaredNames(): Set<string> { | ||
| if (this.rescueDeclaredNames) return this.rescueDeclaredNames; | ||
|
|
||
| const names = new Set<string>(); | ||
| for (const chunk of this.chunks) { | ||
| for (const name of this.indexedSymbolNames(chunk)) { | ||
| if (typeof name === 'string') names.add(name.toLowerCase()); | ||
| } | ||
| } | ||
| this.rescueDeclaredNames = names; | ||
| return names; | ||
| } | ||
|
|
||
| private hasExactQueryDeclaration(chunk: Pick<CodeChunk, 'metadata'>, query: string): boolean { | ||
| const identifiers = new Set( | ||
| (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(query.trim()) | ||
|
|
@@ -828,11 +852,35 @@ export class CodebaseSearcher { | |
|
|
||
| const queryTerms = this.lexicalQueryTerms(query); | ||
| const terms = [...queryTerms.keys()]; | ||
| if (terms.length < 2) return []; | ||
| const symbolAnchors = new Set( | ||
| (query.match(/[a-zA-Z_][a-zA-Z0-9_]*/g) ?? []) | ||
| .filter( | ||
| (term) => | ||
| term.length >= 8 && | ||
| (/[a-z][A-Z]/.test(term) || (term.includes('_') && term.replace(/_/g, '').length >= 4)) | ||
| ) | ||
| .map((term) => term.toLowerCase()) | ||
| ); | ||
| if (terms.length + symbolAnchors.size < 2) return []; | ||
|
|
||
| const symbolAnchors = (query.match(/[a-zA-Z_][a-zA-Z0-9_]*/g) ?? []) | ||
| .filter((term) => /[a-z][A-Z]/.test(term) && term.length >= 8) | ||
| .map((term) => term.toLowerCase()); | ||
| // Declarations still require an indexed edge for corroboration. A name with | ||
| // no declaration can instead count as a literal clue in the file that uses it. | ||
| const literalAnchors = [...symbolAnchors].filter( | ||
| (anchor) => !this.lexicalRescueDeclaredNames().has(anchor) | ||
| ); | ||
| const possibleClues = terms.length + literalAnchors.length; | ||
| if (possibleClues < 2) return []; | ||
|
|
||
| const literalMatches = (item: CodeChunk, nominationText: string): string[] => { | ||
| if (!literalAnchors.some((anchor) => nominationText.includes(anchor))) return []; | ||
| const code = maskComments(item.content).toLowerCase(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| const filename = path.basename(item.relativePath).toLowerCase(); | ||
| return literalAnchors.filter( | ||
| (anchor) => | ||
| findLexicalIdentifierOccurrences(code, anchor).length > 0 || | ||
| findLexicalIdentifierOccurrences(filename, anchor).length > 0 | ||
| ); | ||
| }; | ||
|
|
||
| const candidateLimit = Math.min(MAX_CANDIDATE_WORK, Math.max(256, limit * 80)); | ||
| const budget = sourceBudget ?? { limit: candidateLimit, inspected: new Set<string>() }; | ||
|
|
@@ -841,9 +889,12 @@ export class CodebaseSearcher { | |
| // "polic", and archive/archiving share "archiv". These fragments only nominate; | ||
| // the unchanged exact lexical evidence below still decides admission. | ||
| const fragments = [...new Set(aliases.map((alias) => alias.replace(/[ey]$/, '')))]; | ||
| const lookupTerms = fragments.filter( | ||
| (fragment) => !fragments.some((other) => other !== fragment && fragment.includes(other)) | ||
| ); | ||
| const lookupTerms = [ | ||
| ...fragments.filter( | ||
| (fragment) => !fragments.some((other) => other !== fragment && fragment.includes(other)) | ||
| ), | ||
| ...symbolAnchors | ||
| ]; | ||
| // Keep original chunk ordinals, including ties, and nominate across every | ||
| // exact evidence zone. Filters apply before the bounded evidence window. | ||
| const rawCandidates = | ||
|
|
@@ -853,15 +904,11 @@ export class CodebaseSearcher { | |
| const fields = [ | ||
| item.content, | ||
| path.basename(item.relativePath), | ||
| ...this.indexedDeclarationNames(item), | ||
| ...(item.exports ?? []) | ||
| ...this.indexedSymbolNames(item) | ||
| ]; | ||
| const matches = fields.some((field) => { | ||
| const text = field.toLowerCase(); | ||
| return ( | ||
| lookupTerms.some((term) => text.includes(term)) || | ||
| symbolAnchors.some((anchor) => text.includes(anchor)) | ||
| ); | ||
| return lookupTerms.some((term) => text.includes(term)); | ||
| }); | ||
| return matches ? [{ item, refIndex, score: 0 }] : []; | ||
| }); | ||
|
|
@@ -879,27 +926,27 @@ export class CodebaseSearcher { | |
| const text = [ | ||
| result.item.content, | ||
| path.basename(result.item.relativePath), | ||
| ...this.indexedDeclarationNames(result.item), | ||
| ...(result.item.exports ?? []) | ||
| ...this.indexedSymbolNames(result.item) | ||
| ] | ||
| .join(' ') | ||
| .toLowerCase(); | ||
| const clues = [...queryTerms.values()].filter((aliases) => | ||
| aliases.some((alias) => text.includes(alias)) | ||
| ).length; | ||
| return { result, clues }; | ||
| const identifiers = literalMatches(result.item, text); | ||
| const clues = | ||
| [...queryTerms.values()].filter((aliases) => | ||
| aliases.some((alias) => text.includes(alias)) | ||
| ).length + identifiers.length; | ||
| return { result, identifiers, clues }; | ||
| }) | ||
| .sort((a, b) => b.clues - a.clues || a.result.refIndex - b.result.refIndex) | ||
| .slice(0, candidateLimit) | ||
| .map(({ result }) => result); | ||
| .slice(0, candidateLimit); | ||
| const unavailableBefore = [...checkedSources.values()].filter( | ||
| (source) => source === null | ||
| ).length; | ||
|
|
||
| const queryAliases = new Map( | ||
| terms.map((term) => [term, new Set(queryTerms.get(term)!)] as const) | ||
| ); | ||
| const evidence = candidates.map((result) => { | ||
| const evidence = candidates.map(({ result, identifiers }) => { | ||
| const { item } = result; | ||
| const bodyWords = this.lexicalWords(item.content); | ||
| const bodyLexemes = new Set<string>(); | ||
|
|
@@ -929,18 +976,15 @@ export class CodebaseSearcher { | |
| Math.sqrt(Math.max(1, bodyWords.length)); | ||
| // Export names remain useful lexical/graph clues, but can be re-exports; | ||
| // exact definition priority below requires own declaration metadata. | ||
| const indexedSymbols = [...this.indexedDeclarationNames(item), ...(item.exports ?? [])]; | ||
| const exactAnchor = symbolAnchors.some((symbol) => | ||
| indexedSymbols.some( | ||
| (indexedSymbol) => | ||
| typeof indexedSymbol === 'string' && indexedSymbol.toLowerCase() === symbol | ||
| ) | ||
| const indexedSymbols = this.indexedSymbolNames(item); | ||
| const exactAnchor = indexedSymbols.some( | ||
| (name) => typeof name === 'string' && symbolAnchors.has(name.toLowerCase()) | ||
| ); | ||
| const declarationLexemes = this.lexicalEvidence(indexedSymbols.filter(Boolean).join(' ')); | ||
| const declarationMatching = new Set( | ||
| terms.filter((term) => queryTerms.get(term)!.some((alias) => declarationLexemes.has(alias))) | ||
| ); | ||
| return { result, matching, declarationMatching, exactAnchor, density }; | ||
| return { result, matching, identifiers, declarationMatching, exactAnchor, density }; | ||
| }); | ||
|
|
||
| const supportedCompanions = new Map( | ||
|
|
@@ -1015,10 +1059,11 @@ export class CodebaseSearcher { | |
| } | ||
|
|
||
| const fileEvidence = new Map<string, Set<string>>(); | ||
| for (const { result, matching } of evidence) { | ||
| for (const { result, matching, identifiers } of evidence) { | ||
| const key = this.indexedFileKey(result.item.filePath); | ||
| const termsForFile = fileEvidence.get(key) ?? new Set<string>(); | ||
| for (const term of matching) termsForFile.add(term); | ||
| for (const identifier of identifiers) termsForFile.add(identifier); | ||
| fileEvidence.set(key, termsForFile); | ||
| } | ||
|
|
||
|
|
@@ -1036,6 +1081,7 @@ export class CodebaseSearcher { | |
| const score = (entry: typeof a, key: string) => | ||
| ((fileEvidence.get(key)?.size ?? 0) + entry.declarationMatching.size) * 8 + | ||
| entry.matching.size * 3 + | ||
| entry.identifiers.length * 8 + | ||
| (entry.exactAnchor ? 8 : 0) - | ||
| (this.isTestFile(entry.result.item.filePath) ? 2 : 0) - | ||
| (entry.result.score ?? 0); | ||
|
|
@@ -1049,16 +1095,17 @@ export class CodebaseSearcher { | |
| seenFiles.add(key); | ||
| return true; | ||
| }) | ||
| .map(({ result, declarationMatching }) => ({ | ||
| .map(({ result, declarationMatching, identifiers }) => ({ | ||
| ...result, | ||
| // Equal document zones: distinct source clues nominate the file; | ||
| // indexed declaration clues distinguish its own work from mentions in | ||
| // imports or configuration. This remains bounded to [0, 1]. | ||
| // declaration and literal clues in the selected chunk distinguish where | ||
| // the named evidence appears. This remains bounded to [0, 1]. | ||
| score: | ||
| 1 - | ||
| ((fileEvidence.get(this.indexedFileKey(result.item.filePath))?.size ?? 0) + | ||
| declarationMatching.size) / | ||
| (terms.length * 2) | ||
| declarationMatching.size + | ||
| identifiers.length) / | ||
| (possibleClues * 2) | ||
| })); | ||
| const current = await this.selectCurrentCandidates( | ||
| nominated, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -526,6 +526,72 @@ export interface IdentifierOccurrence { | |
| nodeType: string; | ||
| } | ||
|
|
||
| /** Mask common source comments while preserving quoted text and source offsets. */ | ||
| export function maskComments(source: string): string { | ||
| const chars = source.split(''); | ||
| let quote: string | undefined; | ||
| let escaped = false; | ||
|
|
||
| for (let index = 0; index < chars.length; index += 1) { | ||
| const char = chars[index]; | ||
| const next = chars[index + 1]; | ||
|
|
||
| if (quote) { | ||
| if (escaped) escaped = false; | ||
| else if (char === '\\') escaped = true; | ||
| else if (char === quote) quote = undefined; | ||
| continue; | ||
| } | ||
|
|
||
| if (char === '"' || char === "'" || char === '`') { | ||
| quote = char; | ||
| continue; | ||
|
Comment on lines
+539
to
+548
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
|
|
||
| if (source.startsWith('<!--', index)) { | ||
| while (index < chars.length && !source.startsWith('-->', index)) { | ||
| if (chars[index] !== '\n' && chars[index] !== '\r') chars[index] = ' '; | ||
| index += 1; | ||
| } | ||
| if (index < chars.length) { | ||
| chars[index] = ' '; | ||
| chars[index + 1] = ' '; | ||
| chars[index + 2] = ' '; | ||
| index += 2; | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| const lineComment = | ||
| (char === '/' && next === '/') || char === '#' || (char === '-' && next === '-'); | ||
|
Comment on lines
+565
to
+566
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For JavaScript/TypeScript, AGENTS.md reference: AGENTS.md:L108-L108 Useful? React with 👍 / 👎.
Comment on lines
+565
to
+566
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| if (lineComment) { | ||
| while (index < chars.length && chars[index] !== '\n' && chars[index] !== '\r') { | ||
| chars[index] = ' '; | ||
| index += 1; | ||
| } | ||
| index -= 1; | ||
| continue; | ||
| } | ||
|
|
||
| if (char === '/' && next === '*') { | ||
| chars[index] = ' '; | ||
| chars[index + 1] = ' '; | ||
| index += 2; | ||
| while (index < chars.length && !(chars[index] === '*' && chars[index + 1] === '/')) { | ||
| if (chars[index] !== '\n' && chars[index] !== '\r') chars[index] = ' '; | ||
| index += 1; | ||
| } | ||
| if (index < chars.length) { | ||
| chars[index] = ' '; | ||
| chars[index + 1] = ' '; | ||
| index += 1; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return chars.join(''); | ||
| } | ||
|
|
||
| const LEXICAL_IDENTIFIER_CONTINUE = /(?:\p{ID_Continue}|[$]|\u200c|\u200d)/u; | ||
| const ASCII_IDENTIFIER_CONTINUE = /[A-Za-z0-9_$]/; | ||
| const ASCII_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/; | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a multiline comment crosses a chunk boundary, masking
item.contentstarts with no knowledge of the opening delimiter. The line-based chunker insrc/utils/chunking.tsslices files every 50 lines without preserving comment boundaries, so an identifier appearing only inside a comment after that boundary remains unmasked. Combined with one natural clue elsewhere in the file, it becomes sufficient rescue evidence and returns a comment-only identifier match, contrary to the new admission contract. Mask the complete source before selecting chunk intervals, or retain the lexical state at each chunk's start.Useful? React with 👍 / 👎.