Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(memory): bound knowledge search fallback and reads

muterC9762e8ae48aa
diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.md
index 3433bdb6..47c39661 100644
--- a/apps/node-services/src/memory/README.md
+++ b/apps/node-services/src/memory/README.md
@@ -191,7 +191,7 @@ Core configuration:
vote, fused by RRF, and the response returns at most 30 `facts` at the top level. Without keyword matches it
returns none. Each fact carries its Raw's `evidenceId` and `sectionId` for a follow-up read. Facts take no part in
the Chunk ranking and take at most a quarter of the response's output budget (below); with or without the fact
- channel, both lists are ranked the same. A failed fact recall only omits `facts`.
+ channel, both lists are ranked the same. A summaries-only search omits facts; a failed fact recall only omits `facts`.
Memory's endpoints mount on the shared Node Services listener (`127.0.0.1:4319` by default), all under the
`/internal/v1/` prefix and protected by the workload token. The process answers `GET /healthz`, `GET /startupz` and
@@ -383,8 +383,8 @@ top 50, merged by RRF with `k=60`; adjacent results from the same source are ded
source before backfilling. The Chunk ranking may keep several matches from one source, but Personal Knowledge output
deduplicates by immutable Raw source and returns one evidence ID per source: the top Chunk is the preview, and the
full Chunk directory is offered for the second step.
-Without a valid chunk match, Memory runs a BM25 fallback over the text of the current PostgreSQL Raw versions within
-the same Tenant, Human owner, Agent and date range (the 30 most recently updated sources, at most 3 MB of text). It
+When neither requested list has a valid chunk match, Memory runs a BM25 fallback over the text of the current PostgreSQL Raw versions within
+the same Tenant, Human owner, Agent and date range (per list, at most 30 recent sources and 3 MB of text). It
reads no local files, never scans all Raw, and never revives a retired My Pages source from a local Document
projection. Fallback candidates can be verified by the same boundary's second-step Evidence read; a database query
error returns `partial` with `raw_chunk_search_unavailable` rather than posing as an empty result.
diff --git a/apps/node-services/src/memory/knowledge-query.ts b/apps/node-services/src/memory/knowledge-query.ts
index 4dd14c82..17ecd735 100644
--- a/apps/node-services/src/memory/knowledge-query.ts
+++ b/apps/node-services/src/memory/knowledge-query.ts
@@ -112,8 +112,8 @@ interface ListEntry {
* One search over every source of the Agent's index, as two separately ranked
* lists: items are Sessions, recordings, My pages, mail, Pocket Notes and the
* Profile; summaries are the published Wiki and Daily and Weekly reports.
- * Session facts rank in their own channel. `scope` searches one list with the
- * whole budget, and `page` continues the same search.
+ * Session facts rank in their own channel except in summaries-only searches.
+ * `scope` searches one list with the whole budget; `page` continues it.
*/
export async function queryPersonalKnowledge(
dataRoot: string,
@@ -131,7 +131,7 @@ export async function queryPersonalKnowledge(
: input.scope === "originals"
? ["items"]
: ["items", "summaries"];
- const search = (name: ListName) =>
+ const search = (name: ListName, fallback: "skip" | "only") =>
lists.includes(name)
? searchRawSources(
workspaceRoot,
@@ -141,13 +141,31 @@ export async function queryPersonalKnowledge(
limit: LIST_CANDIDATE_CHUNKS,
},
options.chunkSearch,
+ [],
+ { fallback, maxSources: MAX_ENTRIES[name] },
)
- : Promise.resolve({ matches: [], limited: false });
- const [itemResult, summaryResult, facts] = await Promise.all([
- search("items"),
- search("summaries"),
- options.chunkSearch?.searchFacts?.(input) ?? [],
+ : Promise.resolve({ matches: [], limited: false, unavailable: false });
+ const [indexedItems, indexedSummaries, facts] = await Promise.all([
+ search("items", "skip"),
+ search("summaries", "skip"),
+ input.scope === "summaries"
+ ? []
+ : (options.chunkSearch?.searchFacts?.(input) ?? []),
]);
+ let itemResult = indexedItems;
+ let summaryResult = indexedSummaries;
+ // A miss in one list must not scan Raw while the other list has index hits.
+ if (
+ !itemResult.unavailable &&
+ !summaryResult.unavailable &&
+ !itemResult.matches.length &&
+ !summaryResult.matches.length
+ ) {
+ [itemResult, summaryResult] = await Promise.all([
+ search("items", "only"),
+ search("summaries", "only"),
+ ]);
+ }
const terms = new Set(
tokenizeSearchText([input.query, ...(input.alternates ?? [])].join(" ")),
);
diff --git a/apps/node-services/src/memory/search/raw-query.ts b/apps/node-services/src/memory/search/raw-query.ts
index 1e4cc501..0392cf84 100644
--- a/apps/node-services/src/memory/search/raw-query.ts
+++ b/apps/node-services/src/memory/search/raw-query.ts
@@ -79,6 +79,7 @@ async function searchAvailableRawSources(
input: RawSearchInput,
chunkSearch?: ChunkSearchProvider,
references: readonly RawSourceReference[] = [],
+ options: { fallback?: "skip" | "only"; maxSources?: number } = {},
): Promise<{ matches: RawMatch[]; limited: boolean }> {
const { originKinds, limit } = input;
const inList = (source: RawSource) =>
@@ -89,7 +90,7 @@ async function searchAvailableRawSources(
sourcePriority.set(reference.sourceId, index);
}
}
- if (chunkSearch) {
+ if (chunkSearch && options.fallback !== "only") {
const ranked: IndexedChunkMatch[] = await chunkSearch.search({
agent_id: input.agent_id,
tenant_id: input.tenant_id,
@@ -115,6 +116,7 @@ async function searchAvailableRawSources(
);
const sourceById = new Map(sources.map((source) => [source.id, source]));
const loaded = new Map<string, SourceChunk[]>();
+ const attempted = new Set<string>();
const matches: RawMatch[] = [];
for (const match of ranked) {
const source = sourceById.get(match.sourceId);
@@ -127,6 +129,13 @@ async function searchAvailableRawSources(
continue;
let chunks = loaded.get(source.id);
if (!chunks) {
+ if (
+ attempted.has(source.id) ||
+ (options.maxSources !== undefined &&
+ attempted.size >= options.maxSources)
+ )
+ continue;
+ attempted.add(source.id);
const text = await chunkSearch.readRawSource?.(input, source);
if (text === undefined) continue;
chunks = chunkSource(text);
@@ -144,6 +153,7 @@ async function searchAvailableRawSources(
if (matches.length > 0) return { matches, limited: false };
}
}
+ if (options.fallback === "skip") return { matches: [], limited: false };
const resolved = await resolveSearchRawSources(
workspaceRoot,
input,
diff --git a/apps/node-services/tests/memory/raw-knowledge-query.test.ts b/apps/node-services/tests/memory/raw-knowledge-query.test.ts
index bb861a51..bf7a6e22 100644
--- a/apps/node-services/tests/memory/raw-knowledge-query.test.ts
+++ b/apps/node-services/tests/memory/raw-knowledge-query.test.ts
@@ -457,9 +457,124 @@ describe("Raw Chunk search with PG Raw BM25 fallback", () => {
expect(result.summaries[0]!.content).toContain("Cobalt budget history");
});
+ it("does not scan an empty list when the other has an indexed match", async () => {
+ const f = await fixture();
+ const [room] = await listRawSources(f.workspace, identity);
+ const text = (await readRawSource(f.workspace, room!))!;
+ const chunk = chunkSource(text)[0]!;
+ const database = databases.get(f.root)!;
+ for (let index = 0; index < 40; index += 1) {
+ const markdown = `# Cobalt ${index}\n\nA summary.`;
+ const wiki = wikiPageRawSource({
+ identity,
+ pageKey: `projects/cobalt-${index}`,
+ title: `Cobalt ${index}`,
+ documentId: `wiki-${index}`,
+ documentVersionId: `version-${index}`,
+ publishedAt: "2026-09-16T00:00:00Z",
+ revision: "revision_1",
+ markdown,
+ });
+ database.put(wiki, markdown);
+ }
+ const resolve = vi.fn(database.resolveRawSources.bind(database));
+ const read = vi.fn(database.readRawSource.bind(database));
+ const result = await queryPersonalKnowledge(f.root, request("Cobalt"), {
+ chunkSearch: {
+ search: async (input) =>
+ input.originKinds?.includes("room")
+ ? [
+ {
+ sourceId: room!.id,
+ chunkId: chunk.id,
+ mergedChunkIds: [chunk.id],
+ score: 1,
+ },
+ ]
+ : [],
+ resolveRawSources: resolve,
+ readRawSource: read,
+ },
+ });
+ expect(result.status).toBe("grounded");
+ expect(result.summaries).toEqual([]);
+ expect(resolve).toHaveBeenCalledTimes(1);
+ expect(resolve.mock.calls[0]![1]).toHaveLength(1);
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(read.mock.calls[0]![1].id).toBe(room!.id);
+ });
+
+ it("does not scan when one list's index search fails", async () => {
+ const f = await fixture();
+ const database = databases.get(f.root)!;
+ const resolve = vi.fn(database.resolveRawSources.bind(database));
+ const read = vi.fn(database.readRawSource.bind(database));
+ const result = await queryPersonalKnowledge(f.root, request("Cobalt"), {
+ chunkSearch: {
+ search: async (input) => {
+ if (input.originKinds?.includes("room"))
+ throw new Error("index failed");
+ return [];
+ },
+ resolveRawSources: resolve,
+ readRawSource: read,
+ },
+ });
+ expect(result.status).toBe("partial");
+ expect(result.gaps).toContainEqual({
+ code: "raw_chunk_search_unavailable",
+ });
+ expect(resolve).not.toHaveBeenCalled();
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ it("loads at most the number of sources shown while retaining later matched sections", async () => {
+ const f = await fixture();
+ const database = databases.get(f.root)!;
+ const indexed = Array.from({ length: 25 }, (_, index) => {
+ const markdown = `# Cobalt ${index}\n\n## First\n\nCobalt first.\n\n## Second\n\nCobalt second.`;
+ const source = storeDocumentSource(f.root, {
+ ...meetingDocument,
+ documentId: `document_limit_${index}`,
+ textSourceId: `version_limit_${index}`,
+ title: `Cobalt ${index}`,
+ markdown,
+ });
+ const chunks = chunkSource(markdown);
+ return { source, chunks };
+ });
+ const match = (index: number, chunkIndex: number) => {
+ const { source, chunks } = indexed[index]!;
+ const chunk = chunks[chunkIndex]!;
+ return {
+ sourceId: source.id,
+ chunkId: chunk.id,
+ mergedChunkIds: [chunk.id],
+ score: 1,
+ };
+ };
+ const read = vi.fn(database.readRawSource.bind(database));
+ const result = await queryPersonalKnowledge(f.root, request("Cobalt"), {
+ outputBudgetChars: 100_000,
+ chunkSearch: {
+ search: async (input) =>
+ input.originKinds?.includes("my_pages")
+ ? [...indexed.map((_, index) => match(index, 0)), match(0, 2)]
+ : [],
+ readRawSource: read,
+ },
+ });
+ expect(read).toHaveBeenCalledTimes(20);
+ expect(result.items).toHaveLength(20);
+ expect(
+ result.items[0]!.sections.map((section) => section.sectionId),
+ ).toContain(indexed[0]!.chunks[2]!.id);
+ });
+
it("searches one list with the whole budget when scoped", async () => {
const fixtureData = await fixture();
const kinds: (readonly string[] | undefined)[] = [];
+ const searchFacts = vi.fn(async () => []);
const result = await queryPersonalKnowledge(
fixtureData.root,
{ ...request("Cobalt"), scope: "summaries" },
@@ -470,10 +585,13 @@ describe("Raw Chunk search with PG Raw BM25 fallback", () => {
return [];
},
resolveRawSources: async () => [],
+ searchFacts,
},
},
);
expect(kinds).toEqual([["wiki", "period_summary"]]);
+ expect(searchFacts).not.toHaveBeenCalled();
+ expect(result).not.toHaveProperty("facts");
expect(result).toMatchObject({ scope: "summaries", items: [], page: 1 });
});