feat(search): field-qualified queries (kind:/lang:/path:/name:) + fuzzy typo fallback (#131)
* feat(search): field-qualified queries (kind:/lang:/path:/name:) + fuzzy typo fallback
Two UX improvements that turn a free-text search into something a
real user can drive precisely.
1) Field-qualified queries.
A new query parser (src/search/query-parser.ts) splits the raw query
into structured filters and a free-text remainder:
kind:function name:auth path:src/api authenticate
becomes
{ kinds: ['function'], nameFilters: ['auth'],
pathFilters: ['src/api'], text: 'authenticate' }
Filters compose with the SearchOptions arg (intersection). Unknown
prefixes pass through as plain text so `query "TODO:"` keeps working.
Quoted values (`path:"my dir"`) handle whitespace. When the user
specifies only filters with no text, the search uses a filter-only
candidate scan instead of bailing out.
Recognised today:
kind: any NodeKind value
lang: any Language value (alias: language:)
path: case-insensitive substring of file_path
name: case-insensitive substring of node.name
2) Fuzzy fallback.
When BOTH FTS and LIKE return nothing AND the text is at least 3
chars, the resolver scans the distinct-name set with a bounded
Damerau-Levenshtein-style edit distance (≤2 for ≥5 chars, ≤1 for
4-char queries, off for shorter). Bounded edit-distance early-exits
once the row min exceeds maxDist, so this stays O(distinct-names *
avg-name-length) with a very low constant.
Verified live against ollama/ollama@v0.22.0:
query "kind:function auth" → only function-kind hits
query "lang:go path:server route" → Go files under server/
query "getUssr" (typo) → finds getUser, SetUser
query "confg" (typo) → finds Config
Full test suite: 380 passed.
* fix(search): address reviewer findings — tokenizer mid-token quotes, fuzzy fan-out cap, larger filter-only over-fetch, unit tests
Five fixes from independent review:
- parseQuery tokenizer: quotes that appear MID-token (path:"my dir/
file") were not being recognised — only quotes at the start of a
token were treated as quoted spans. The fixture path:"my dir"
parsed as ['path:"my', 'dir"'] instead of ['path:"my dir"'].
Tokeniser is now a single state machine that scans into a token
until whitespace OR a quote, and recognises quotes anywhere within
the token (skips to the matching close quote).
- searchNodesFuzzy: cap the per-name follow-up SQL queries at
Math.max(limit*2, 50) AFTER edit-distance filtering. Without
this, a project with many similar names (getUser1, getUser2...)
could fan out far beyond limit queries before the inner-loop
break kicks in.
- searchAllByFilters (filter-only no-text path): bumped over-fetch
multiplier from 2× to 5× so a selective post-filter (e.g.
path:src/very/specific/file.ts) doesn't return fewer than limit
results despite the DB having matches.
- 23 new unit tests in __tests__/search-query-parser.test.ts:
parseQuery covers known-field filter, lang/language alias,
multiple kind: ORs, quoted spans (incl. mid-token), URL
passthrough, empty-value passthrough, unknown prefix passthrough,
unknown value passthrough, all-filters-no-text, empty input,
20k-char input. boundedEditDistance covers identity, single
insertion/deletion/substitution, length-difference shortcut,
empty inputs, case-sensitivity, early-exit correctness.
Full test suite: 853 passed (up from 830).
* refactor(search): derive parser kind/lang sets from types.ts as const
Convert NodeKind and Language to runtime-iterable as const arrays
(NODE_KINDS, LANGUAGES) so the query parser imports the canonical
list instead of duplicating it. Also fix the path: JSDoc to say
substring (matches the .includes() impl).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Colby McHenry <me@colbymchenry.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
Colby McHenry
parent
38d155618f
commit
56f6b3b485
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Field-qualified search query parser.
|
||||
*
|
||||
* Splits a raw query like
|
||||
*
|
||||
* kind:function name:auth path:src/api authenticate
|
||||
*
|
||||
* into structured filters (kind=function, name="auth", path prefix
|
||||
* "src/api") plus the free-text portion ("authenticate") that goes
|
||||
* to FTS. Free-text and filters compose: filters narrow the result
|
||||
* set, FTS scores within the narrowed set.
|
||||
*
|
||||
* Recognised fields (case-insensitive, value is the rest until
|
||||
* whitespace):
|
||||
*
|
||||
* kind: one of function|method|class|interface|struct|...
|
||||
* lang: one of typescript|python|go|... (alias: language:)
|
||||
* path: case-insensitive substring of file_path
|
||||
* name: case-insensitive substring of the symbol's name
|
||||
*
|
||||
* Unknown field prefixes (e.g. `foo:bar`) are passed through to FTS
|
||||
* as plain text — that's how someone searching for `TODO:` gets a
|
||||
* result instead of a parse error.
|
||||
*
|
||||
* Quoting:
|
||||
* kind:function path:"src/some path/with spaces" → handled by stripping
|
||||
* the surrounding double quotes from the value (single token only,
|
||||
* no nested escapes).
|
||||
*/
|
||||
|
||||
import { NODE_KINDS, LANGUAGES } from '../types';
|
||||
import type { NodeKind, Language } from '../types';
|
||||
|
||||
export interface ParsedQuery {
|
||||
/** Free-text portion to feed to FTS / LIKE. May be empty. */
|
||||
text: string;
|
||||
/** kind: filters (OR'd). Empty when none specified. */
|
||||
kinds: NodeKind[];
|
||||
/** lang:/language: filters (OR'd). Empty when none specified. */
|
||||
languages: Language[];
|
||||
/** path: filters (OR'd, case-insensitive substring of file_path). Empty when none. */
|
||||
pathFilters: string[];
|
||||
/** name: filters (OR'd, case-insensitive substring of node.name). */
|
||||
nameFilters: string[];
|
||||
}
|
||||
|
||||
// Derived from the canonical `NODE_KINDS` / `LANGUAGES` arrays in
|
||||
// types.ts so adding a new kind or language doesn't silently fall
|
||||
// through to plain text here.
|
||||
const KIND_VALUES: ReadonlySet<string> = new Set<NodeKind>(NODE_KINDS);
|
||||
const LANGUAGE_VALUES: ReadonlySet<string> = new Set<Language>(LANGUAGES);
|
||||
|
||||
/**
|
||||
* Strip a surrounding pair of double quotes from `s`. Allows users to
|
||||
* keep whitespace in path filters: `path:"my dir/file"`.
|
||||
*/
|
||||
function unquote(s: string): string {
|
||||
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) return s.slice(1, -1);
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a raw query into structured filters + remaining text.
|
||||
* Always returns a value; never throws.
|
||||
*/
|
||||
export function parseQuery(raw: string): ParsedQuery {
|
||||
const out: ParsedQuery = {
|
||||
text: '',
|
||||
kinds: [],
|
||||
languages: [],
|
||||
pathFilters: [],
|
||||
nameFilters: [],
|
||||
};
|
||||
|
||||
// Tokenise on whitespace, preserving quoted spans as part of the
|
||||
// current token. Quotes can appear at the start (`"…"`) OR mid-token
|
||||
// (`path:"…"`); in both cases everything from the opening `"` to the
|
||||
// matching `"` is included in the token, whitespace and all.
|
||||
const tokens: string[] = [];
|
||||
let i = 0;
|
||||
while (i < raw.length) {
|
||||
while (i < raw.length && /\s/.test(raw[i]!)) i++;
|
||||
if (i >= raw.length) break;
|
||||
const start = i;
|
||||
while (i < raw.length && !/\s/.test(raw[i]!)) {
|
||||
if (raw[i] === '"') {
|
||||
const end = raw.indexOf('"', i + 1);
|
||||
if (end === -1) {
|
||||
// Unterminated quote — swallow the rest of the input as
|
||||
// one token. Forgiving rather than throwing.
|
||||
i = raw.length;
|
||||
break;
|
||||
}
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
tokens.push(raw.slice(start, i));
|
||||
}
|
||||
|
||||
const textParts: string[] = [];
|
||||
for (const tok of tokens) {
|
||||
const colon = tok.indexOf(':');
|
||||
if (colon <= 0 || colon === tok.length - 1) {
|
||||
textParts.push(tok);
|
||||
continue;
|
||||
}
|
||||
const key = tok.slice(0, colon).toLowerCase();
|
||||
const valueRaw = unquote(tok.slice(colon + 1));
|
||||
if (!valueRaw) {
|
||||
textParts.push(tok);
|
||||
continue;
|
||||
}
|
||||
switch (key) {
|
||||
case 'kind': {
|
||||
if (KIND_VALUES.has(valueRaw)) {
|
||||
out.kinds.push(valueRaw as NodeKind);
|
||||
} else {
|
||||
textParts.push(tok);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'lang':
|
||||
case 'language': {
|
||||
const lower = valueRaw.toLowerCase();
|
||||
if (LANGUAGE_VALUES.has(lower)) {
|
||||
out.languages.push(lower as Language);
|
||||
} else {
|
||||
textParts.push(tok);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'path':
|
||||
out.pathFilters.push(valueRaw);
|
||||
break;
|
||||
case 'name':
|
||||
out.nameFilters.push(valueRaw);
|
||||
break;
|
||||
default:
|
||||
textParts.push(tok);
|
||||
}
|
||||
}
|
||||
|
||||
out.text = textParts.join(' ').trim();
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Damerau-Levenshtein-ish bounded edit distance. Returns `maxDist + 1`
|
||||
* as soon as the distance is known to exceed `maxDist`; that early-exit
|
||||
* makes the fuzzy fallback cheap even over tens of thousands of names.
|
||||
*
|
||||
* Pure DP, O(min(len(a), len(b))) memory. Compares case-folded inputs;
|
||||
* callers should pass `lowercase(name)` strings.
|
||||
*/
|
||||
export function boundedEditDistance(a: string, b: string, maxDist: number): number {
|
||||
if (a === b) return 0;
|
||||
const al = a.length;
|
||||
const bl = b.length;
|
||||
if (Math.abs(al - bl) > maxDist) return maxDist + 1;
|
||||
if (al === 0) return bl;
|
||||
if (bl === 0) return al;
|
||||
|
||||
let prev = new Array<number>(bl + 1);
|
||||
let cur = new Array<number>(bl + 1);
|
||||
for (let j = 0; j <= bl; j++) prev[j] = j;
|
||||
|
||||
for (let i = 1; i <= al; i++) {
|
||||
cur[0] = i;
|
||||
let rowMin = cur[0]!;
|
||||
for (let j = 1; j <= bl; j++) {
|
||||
const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
|
||||
const insertion = cur[j - 1]! + 1;
|
||||
const deletion = prev[j]! + 1;
|
||||
const substitution = prev[j - 1]! + cost;
|
||||
cur[j] = Math.min(insertion, deletion, substitution);
|
||||
if (cur[j]! < rowMin) rowMin = cur[j]!;
|
||||
}
|
||||
if (rowMin > maxDist) return maxDist + 1;
|
||||
[prev, cur] = [cur, prev];
|
||||
}
|
||||
return prev[bl]!;
|
||||
}
|
||||
Reference in New Issue
Block a user