@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
194 lines • 6.99 kB
JavaScript
const BM25_K1 = 0.9;
const BM25_B = 0.4;
const NAME_FIELD_WEIGHT = 3;
const GROUP_FIELD_WEIGHT = 2;
const DESCRIPTION_FIELD_WEIGHT = 1;
/**
* Half of the query's content terms and a third of the best score: a single
* incidental term ("search" inside a six-word query) no longer surfaces an
* unrelated tool, while a two-word query still tolerates one missing term.
*/
export const DEFAULT_BM25_PRECISION = { minCoverage: 0.5, minScoreRatio: 0.35 };
const DEFAULT_LIMIT = 25;
export function buildBm25Index(docs) {
const indexed = docs.map(indexDoc);
const docFreq = new Map();
for (const entry of indexed) {
for (const term of entry.termFreq.keys()) {
docFreq.set(term, (docFreq.get(term) ?? 0) + 1);
}
}
const totalLength = indexed.reduce((sum, entry) => sum + entry.length, 0);
const avgLength = indexed.length === 0 ? 0 : totalLength / indexed.length;
const docCount = indexed.length;
return {
search(query, limit = DEFAULT_LIMIT, options = {}) {
const pool = indexed.filter((entry) => (options.source === undefined || entry.doc.source === options.source) &&
(options.group === undefined || entry.doc.group === options.group));
const queryTerms = tokenizeToolText(query).map(stemToken);
if (queryTerms.length === 0)
return [];
const contentTerms = contentTermsOf(queryTerms);
const useExact = options.exactMatch !== false;
const normQuery = normalizeToolName(query);
const results = [];
for (const entry of pool) {
const exact = useExact && normQuery.length > 0 && entry.exactNames.has(normQuery);
const score = bm25Score(entry, queryTerms, docFreq, avgLength, docCount);
if (!exact && score <= 0)
continue;
results.push({
coverage: coverageOf(entry, contentTerms),
doc: entry.doc,
exact,
name: entry.doc.name,
score,
});
}
results.sort(compareResults);
const gated = options.precision === undefined ? results : applyPrecision(results, options.precision);
return gated.slice(0, Math.max(0, limit));
},
};
}
function applyPrecision(results, precision) {
const best = results.find((result) => !result.exact)?.score ?? 0;
const floor = best * precision.minScoreRatio;
return results.filter((result) => result.exact || (result.coverage >= precision.minCoverage && result.score >= floor));
}
/** Query words that carry no intent on their own; they never count toward coverage. */
const STOPWORDS = new Set([
"a",
"an",
"and",
"are",
"be",
"by",
"can",
"do",
"for",
"from",
"how",
"i",
"in",
"is",
"it",
"me",
"my",
"need",
"of",
"on",
"or",
"please",
"that",
"the",
"this",
"to",
"tool",
"use",
"using",
"via",
"want",
"we",
"with",
"you",
"your",
]);
function contentTermsOf(queryTerms) {
const content = new Set(queryTerms.filter((term) => !STOPWORDS.has(term)));
return content.size > 0 ? content : new Set(queryTerms);
}
function coverageOf(entry, contentTerms) {
if (contentTerms.size === 0)
return 0;
let matched = 0;
for (const term of contentTerms)
if (entry.termFreq.has(term))
matched++;
return matched / contentTerms.size;
}
function indexDoc(doc) {
const termFreq = new Map();
addField(termFreq, indexTokens(doc.name), NAME_FIELD_WEIGHT);
addField(termFreq, indexTokens(doc.label), NAME_FIELD_WEIGHT);
for (const alias of doc.aliases)
addField(termFreq, indexTokens(alias), NAME_FIELD_WEIGHT);
for (const keyword of doc.keywords)
addField(termFreq, indexTokens(keyword), NAME_FIELD_WEIGHT);
addField(termFreq, indexTokens(doc.group), GROUP_FIELD_WEIGHT);
addField(termFreq, indexTokens(doc.ownerLabel), GROUP_FIELD_WEIGHT);
addField(termFreq, indexTokens(doc.description ?? ""), DESCRIPTION_FIELD_WEIGHT);
addField(termFreq, indexTokens(doc.searchText ?? ""), DESCRIPTION_FIELD_WEIGHT);
let length = 0;
for (const count of termFreq.values())
length += count;
return {
doc,
exactNames: new Set([doc.name, doc.label, ...doc.aliases, ...doc.keywords].map(normalizeToolName)),
length,
termFreq,
};
}
function addField(termFreq, tokens, weight) {
for (const token of tokens) {
termFreq.set(token, (termFreq.get(token) ?? 0) + weight);
}
}
function bm25Score(entry, queryTerms, docFreq, avgLength, docCount) {
let score = 0;
const seen = new Set();
for (const term of queryTerms) {
if (seen.has(term))
continue;
seen.add(term);
const tf = entry.termFreq.get(term);
if (tf === undefined)
continue;
const idf = inverseDocFreq(docFreq.get(term) ?? 0, docCount);
const denom = tf + BM25_K1 * (1 - BM25_B + (BM25_B * entry.length) / (avgLength || 1));
score += idf * ((tf * (BM25_K1 + 1)) / (denom || 1));
}
return score;
}
function inverseDocFreq(termDocFreq, docCount) {
const value = Math.log(1 + (docCount - termDocFreq + 0.5) / (termDocFreq + 0.5));
return value < 0 ? 0 : value;
}
function compareResults(left, right) {
if (left.exact !== right.exact)
return left.exact ? -1 : 1;
if (right.score !== left.score)
return right.score - left.score;
return left.name.localeCompare(right.name);
}
function indexTokens(text) {
return tokenizeToolText(text).map(stemToken);
}
/**
* Fold the plural a tool description tends to use ("forecasts", "messages")
* onto the singular a query tends to use. Deliberately minimal: only a trailing
* "s" on words of four or more letters that do not end in "ss" or "us".
*/
export function stemToken(token) {
if (token.length < 4 || !token.endsWith("s") || token.endsWith("ss") || token.endsWith("us"))
return token;
return token.endsWith("ies") ? `${token.slice(0, -3)}y` : token.slice(0, -1);
}
/** Tokenise searchable text into lowercase word tokens, splitting identifiers. */
export function tokenizeToolText(text) {
if (text.length === 0)
return [];
const withBoundaries = text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2");
const tokens = [];
for (const raw of withBoundaries.split(/[^a-zA-Z0-9]+/)) {
if (raw.length === 0)
continue;
tokens.push(raw.toLowerCase());
}
return tokens;
}
/** Normalize a searchable name for separator- and case-insensitive exact matching. */
export function normalizeToolName(name) {
return name.toLowerCase().replace(/[-_\s]+/g, "");
}
//# sourceMappingURL=bm25.js.map