Searching "WHP founding partner pricing" excerpted the "business
partners ... (1) WHP commercial launch" sentence instead of the Founding
Partner passage. Every query term counted the same, so a common term
("WHP", four times) plus a coincidental hit ("partners") tied the real
passage on two terms and won by coming first. "pricing" matched nothing:
the memory says "price".
- Weight each term by rarity within the memory (1 / occurrences), so a
word that appears once outweighs one sprinkled throughout.
- Strip one common suffix (-ing/-ed/-es/-s/-e, keeping 4+ chars) and
match as a prefix, so "pricing" and "price" both become "pric".
Postgres ts_headline, suggested as the alternative, was tested on the
same text and picked the same wrong passage with an OR query (it also
weighs words equally); with plainto_tsquery's AND it found no cover and
fell back to a different, also wrong, passage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
144 lines
5.2 KiB
TypeScript
144 lines
5.2 KiB
TypeScript
/**
|
|
* Short excerpts for memory.list / memory.search results.
|
|
*
|
|
* Those tools used to return every memory's full body, so one search over
|
|
* a few dozen long memories could pour thousands of words into the
|
|
* caller's context. They now return an excerpt plus `contentLength` /
|
|
* `truncated`, and the caller fetches the whole body with memory.get when
|
|
* the excerpt says it's worth it.
|
|
*
|
|
* With a query, the excerpt is the window with the highest weighted score
|
|
* over the query terms it contains. Each term is weighted by how RARE it
|
|
* is in this memory (1 / occurrences): a word that appears once points at
|
|
* one passage, while a word sprinkled throughout (often the project's own
|
|
* name) says little about where to look. Without the weighting, a common
|
|
* term plus one coincidental hit tied the real passage and won by coming
|
|
* first. Terms are matched case-insensitively as prefixes after light
|
|
* suffix stripping, so "pricing" finds "price" and "launch" finds
|
|
* "launched". Without a query — or when no term appears, e.g. a
|
|
* vector-only hit — the excerpt is the start of the memory, which is
|
|
* usually its summary line.
|
|
*
|
|
* Postgres ts_headline was tried for this and picked the same wrong
|
|
* passage: it also weighs every query word equally.
|
|
*/
|
|
|
|
export const EXCERPT_CHARS = 200;
|
|
|
|
/** Context kept before the first matched term so the passage reads naturally. */
|
|
const LEAD_CHARS = 40;
|
|
/** Cap on occurrences examined per term, to keep huge memories cheap. */
|
|
const MAX_OCCURRENCES_PER_TERM = 25;
|
|
|
|
const STOPWORDS = new Set([
|
|
"the", "and", "for", "are", "but", "not", "you", "all", "any", "can",
|
|
"had", "her", "was", "one", "our", "out", "has", "his", "how", "its",
|
|
"who", "did", "get", "may", "use", "she", "him", "too", "via",
|
|
"that", "this", "with", "from", "they", "have", "what", "when", "where",
|
|
"which", "there", "their", "about", "into", "than", "then", "them",
|
|
"does", "should", "would", "could",
|
|
]);
|
|
|
|
export interface Excerpt {
|
|
excerpt: string;
|
|
/** True when the excerpt is not the whole (whitespace-collapsed) memory. */
|
|
truncated: boolean;
|
|
}
|
|
|
|
/** Suffixes stripped so a query word matches its simple inflections. */
|
|
const SUFFIXES = ["ing", "ed", "es", "s", "e"];
|
|
|
|
/**
|
|
* Crude stem: strip one common suffix as long as 4+ chars remain, so the
|
|
* result works as a prefix ("pricing"/"price" → "pric", "partners" →
|
|
* "partner"). Not a real stemmer — a missed inflection only costs a
|
|
* slightly worse window, never a wrong result.
|
|
*/
|
|
function stem(term: string): string {
|
|
for (const suf of SUFFIXES) {
|
|
if (term.endsWith(suf) && term.length - suf.length >= 4) {
|
|
return term.slice(0, -suf.length);
|
|
}
|
|
}
|
|
return term;
|
|
}
|
|
|
|
function queryTerms(query: string): string[] {
|
|
const terms = query
|
|
.toLowerCase()
|
|
.split(/[^\p{L}\p{N}]+/u)
|
|
.filter((t) => t.length >= 3 && !STOPWORDS.has(t))
|
|
.map(stem);
|
|
return [...new Set(terms)];
|
|
}
|
|
|
|
/** Occurrences of `term` in `lower`, capped. */
|
|
function countOccurrences(lower: string, term: string): number {
|
|
let n = 0;
|
|
for (let i = lower.indexOf(term); i !== -1 && n < MAX_OCCURRENCES_PER_TERM; i = lower.indexOf(term, i + 1)) n++;
|
|
return n;
|
|
}
|
|
|
|
/** Start offset of the best-matching window, or 0 when nothing matches. */
|
|
function bestWindowStart(lower: string, allTerms: string[], max: number): number {
|
|
// Rarity weight per term; terms absent from the memory drop out.
|
|
const weights = new Map<string, number>();
|
|
for (const t of allTerms) {
|
|
const n = countOccurrences(lower, t);
|
|
if (n > 0) weights.set(t, 1 / n);
|
|
}
|
|
const terms = [...weights.keys()];
|
|
|
|
let best = 0;
|
|
let bestScore = 0;
|
|
for (const term of terms) {
|
|
let i = -1;
|
|
for (let n = 0; n < MAX_OCCURRENCES_PER_TERM; n++) {
|
|
i = lower.indexOf(term, i + 1);
|
|
if (i === -1) break;
|
|
const start = Math.max(0, i - LEAD_CHARS);
|
|
const window = lower.slice(start, start + max);
|
|
const score = terms.reduce((s, t) => s + (window.includes(t) ? weights.get(t)! : 0), 0);
|
|
if (score > bestScore || (score === bestScore && start < best)) {
|
|
best = start;
|
|
bestScore = score;
|
|
}
|
|
}
|
|
}
|
|
return best;
|
|
}
|
|
|
|
export function makeExcerpt(
|
|
content: string,
|
|
query?: string,
|
|
max: number = EXCERPT_CHARS,
|
|
): Excerpt {
|
|
const text = content.replace(/\s+/g, " ").trim();
|
|
if (text.length <= max) return { excerpt: text, truncated: false };
|
|
|
|
const terms = query ? queryTerms(query) : [];
|
|
let start = terms.length > 0 ? bestWindowStart(text.toLowerCase(), terms, max) : 0;
|
|
|
|
// A match near the end would leave a stub; slide back to fill the window.
|
|
start = Math.min(start, text.length - max);
|
|
|
|
// Snap the start forward to a word boundary (never mid-word).
|
|
if (start > 0 && text[start - 1] !== " ") {
|
|
const space = text.indexOf(" ", start);
|
|
if (space !== -1 && space - start < 20) start = space + 1;
|
|
}
|
|
|
|
let end = Math.min(text.length, start + max);
|
|
// Snap the end back to a word boundary.
|
|
if (end < text.length && text[end] !== " ") {
|
|
const space = text.lastIndexOf(" ", end);
|
|
if (space > start + max / 2) end = space;
|
|
}
|
|
|
|
const body = text.slice(start, end).trim();
|
|
return {
|
|
excerpt: `${start > 0 ? "…" : ""}${body}${end < text.length ? "…" : ""}`,
|
|
truncated: true,
|
|
};
|
|
}
|