Files
shared-memory/apps/web/lib/memory-excerpt.test.ts
T

56 lines
2.7 KiB
TypeScript
Raw Normal View History

import { describe, expect, test } from "vitest";
import { EXCERPT_CHARS, makeExcerpt } from "./memory-excerpt";
const words = (n: number, w = "filler") => Array.from({ length: n }, () => w).join(" ");
describe("makeExcerpt", () => {
test("short content comes back whole, not truncated", () => {
expect(makeExcerpt("a short fact")).toEqual({ excerpt: "a short fact", truncated: false });
});
test("collapses whitespace and newlines so the excerpt reads as one line", () => {
expect(makeExcerpt("# Title\n\n- one\n- two\n").excerpt).toBe("# Title - one - two");
});
test("without a query, long content is cut from the start at a word boundary", () => {
const { excerpt, truncated } = makeExcerpt(`opening line ${words(200)}`);
expect(truncated).toBe(true);
expect(excerpt.startsWith("opening line filler")).toBe(true);
expect(excerpt.endsWith("…")).toBe(true);
expect(excerpt.length).toBeLessThanOrEqual(EXCERPT_CHARS + 2);
// Never splits a word: everything before the ellipsis is whole words.
expect(excerpt.slice(0, -1).trim().split(" ").every((w) => ["opening", "line", "filler"].includes(w))).toBe(true);
});
test("with a query, centres on the passage that matches it", () => {
const content = `${words(150)} the kumquat marmalade recipe lives here ${words(150)}`;
const { excerpt, truncated } = makeExcerpt(content, "kumquat marmalade");
expect(truncated).toBe(true);
expect(excerpt).toContain("kumquat marmalade recipe");
expect(excerpt.startsWith("…")).toBe(true);
expect(excerpt.endsWith("…")).toBe(true);
});
test("prefers the window matching the most distinct query terms", () => {
const content = `alpha ${words(100)} beta ${words(100)} alpha beta gamma together ${words(100)}`;
expect(makeExcerpt(content, "alpha beta gamma").excerpt).toContain("alpha beta gamma together");
});
test("matching is case-insensitive and ignores stopwords", () => {
// "the" would otherwise match at position 0 and win.
const content = `the ${words(100)} WHP Launch plan ${words(100)}`;
expect(makeExcerpt(content, "the whp launch").excerpt).toContain("WHP Launch plan");
});
test("falls back to the start when no query term appears (vector-only hit)", () => {
const content = `opening line ${words(200)}`;
expect(makeExcerpt(content, "zebra").excerpt.startsWith("opening line")).toBe(true);
});
test("a match near the end still fills the window instead of returning a stub", () => {
const content = `${words(200)} needle`;
const { excerpt } = makeExcerpt(content, "needle");
expect(excerpt.endsWith("needle")).toBe(true);
expect(excerpt.length).toBeGreaterThan(EXCERPT_CHARS - 20);
});
});