diff --git a/packages/memory/src/brain/memory-extraction.ts b/packages/memory/src/brain/memory-extraction.ts index b2b16f5..a7f303e 100644 --- a/packages/memory/src/brain/memory-extraction.ts +++ b/packages/memory/src/brain/memory-extraction.ts @@ -9,11 +9,30 @@ import { memoryHumanMessageSql } from "@pibot/storage"; import { z } from "zod"; import type { MemoryToolInput } from "./memory-input.ts"; +function tokenUnits(point: string): number { + return (point.codePointAt(0) ?? 0) > 127 ? point.length * 4 : 1; +} + /** Rough token estimate for the input budget; the provider's own count is not available yet. */ function estimateTokens(text: string): number { - let nonAscii = 0; - for (const point of text) if ((point.codePointAt(0) ?? 0) > 127) nonAscii += point.length; - return Math.ceil((text.length - nonAscii) / 4 + nonAscii); + let units = 0; + for (const point of text) units += tokenUnits(point); + return Math.ceil(units / 4); +} + +const OVERSIZED_USER_EXCERPT_RESERVE = 32; + +function userExcerpt(content: string, budget: number): string | undefined { + const speaker = "User: "; + const marker = "\n[message truncated]"; + let remaining = (budget - estimateTokens(speaker + marker) - 4) * 4; + let end = 0; + for (const point of content) { + remaining -= tokenUnits(point); + if (remaining < 0) break; + end += point.length; + } + if (end > 0) return speaker + content.slice(0, end) + marker; } /** The only shape the extraction model's output may take. */ @@ -142,45 +161,82 @@ export function extractionSource( ORDER BY m.rowid DESC LIMIT 256`, ) .all(conversationId, Number(after), groupId ?? null, groupId ?? null); - // Allocate to human messages first, then bounded assistant summaries. Never split a user turn. + const messages = rows.flatMap((row) => { + const clean = String(row.content ?? "") + .replace(/```[\s\S]*?(?:```|$)/g, "[code omitted]") + .trim(); + const content = row.role === "user" || groupId ? clean : assistantSummary(clean); + if (!content) return []; + const speaker = groupId + ? `${row.role === "user" ? "Owner" : "Coordinator"} [${row.id}]` + : row.role === "user" + ? "User" + : "Assistant"; + const line = `${speaker}: ${content}`; + return [{ id: String(row.id), role: row.role, content, line, cost: estimateTokens(line) + 4 }]; + }); + // Group extraction verifies candidates against complete source statements. + const oversized = groupId + ? [] + : messages.filter((message) => message.role === "user" && message.cost > budget); const selected = new Map(); const contents = new Map(); let used = 0; let truncated = rows.length === 256; - let subjectMessageId: string | undefined; - for (const role of ["user", "assistant"]) - for (const row of rows) { - if (row.role !== role) continue; - const clean = String(row.content ?? "") - .replace(/```[\s\S]*?(?:```|$)/g, "[code omitted]") - .trim(); - // A group decision may occur after the first 400 characters; keep the whole authorized - // statement or omit it under the existing budget, never import member work as consensus. - const content = role === "user" || groupId ? clean : assistantSummary(clean); - if (!content) continue; - const speaker = groupId - ? `${role === "user" ? "Owner" : "Coordinator"} [${row.id}]` - : role === "user" - ? "User" - : "Assistant"; - const line = `${speaker}: ${content}`; - const cost = estimateTokens(line) + 4; - if (used + cost > budget) { + for (const role of ["user", "assistant"]) { + if (role === "assistant" && oversized.length) { + // Select whole user turns first, then make room by shortening the largest selected turns. + // This keeps an almost-full turn from crowding out smaller turns during reservation. + const reserve = Math.min( + OVERSIZED_USER_EXCERPT_RESERVE, + Math.floor(budget / (selected.size + oversized.length)), + ); + const wholeUserBudget = budget - reserve * oversized.length; + if (used > wholeUserBudget) { + const largestFirst = messages + .filter((message) => selected.has(message.id)) + .sort((a, b) => b.cost - a.cost); + for (const message of largestFirst) { + if (used <= wholeUserBudget || message.cost <= reserve) break; + const cap = Math.max(reserve, message.cost - (used - wholeUserBudget)); + const excerpt = userExcerpt(message.content, cap); + if (!excerpt) continue; + selected.set(message.id, excerpt); + used += estimateTokens(excerpt) + 4 - message.cost; + } + } + for (const [index, message] of oversized.entries()) { + const share = Math.floor((budget - used) / (oversized.length - index)); + const excerpt = userExcerpt(message.content, share); + if (excerpt) { + selected.set(message.id, excerpt); + used += estimateTokens(excerpt) + 4; + } + } + } + for (const message of messages) { + if (message.role !== role) continue; + if (used + message.cost > budget) { truncated = true; continue; } - selected.set(String(row.id), line); - contents.set(String(row.id), content); - used += cost; - if (role === "user" && !subjectMessageId) subjectMessageId = String(row.id); + selected.set(message.id, message.line); + contents.set(message.id, message.content); + used += message.cost; } + } + const subject = rows.find((row) => row.role === "user" && selected.has(String(row.id))); // A later coordinator confirmation can be the only new statement after the last watermark. - if (groupId && !subjectMessageId) subjectMessageId = selected.keys().next().value; - if (!selected.size || !subjectMessageId) return undefined; + const subjectMessageId = subject + ? String(subject.id) + : groupId + ? selected.keys().next().value + : undefined; + if (!subjectMessageId) return undefined; return { - text: [...rows] + text: messages .reverse() - .flatMap((row) => selected.get(String(row.id)) ?? []) + .flatMap((message) => selected.get(message.id) ?? []) .join("\n\n"), messageCount: selected.size, truncated, @@ -254,7 +310,7 @@ export function extractionPrompt(catalog: string, source: string, truncated: boo "EXISTING MEMORIES:", catalog || "(none)", "", - truncated ? "NEW CONVERSATION (older messages omitted):" : "NEW CONVERSATION:", + truncated ? "NEW CONVERSATION (some content omitted):" : "NEW CONVERSATION:", "<<<", source, ">>>", diff --git a/packages/memory/test/memory-extraction.test.ts b/packages/memory/test/memory-extraction.test.ts new file mode 100644 index 0000000..c1b86ae --- /dev/null +++ b/packages/memory/test/memory-extraction.test.ts @@ -0,0 +1,174 @@ +import { DatabaseSync } from "node:sqlite"; +import { + BotsRepo, + ConversationsRepo, + GroupsRepo, + MessagesRepo, + runMigrations, +} from "@pibot/storage"; +import { expect, it } from "vitest"; +import { extractionSource } from "../src/brain/memory-extraction.ts"; + +function estimatedCost(lines: string[]) { + return lines.reduce((total, line) => { + const units = Array.from(line).reduce( + (sum, point) => sum + ((point.codePointAt(0) ?? 0) > 127 ? 4 * point.length : 1), + 0, + ); + return total + Math.ceil(units / 4) + 4; + }, 0); +} + +it("includes a bounded excerpt of an oversized user message before advancing coverage", () => { + const db = new DatabaseSync(":memory:"); + try { + runMigrations(db); + const bot = new BotsRepo(db).ensureMainBot(); + const conversation = new ConversationsRepo(db).create({ botId: bot.id }); + const messages = new MessagesRepo(db); + const send = (content: string) => + messages.create({ conversationId: conversation.id, role: "user", status: "done", content }); + + send("Before"); + send(`Decision worth remembering ${"测🙂".repeat(12_000)}`); + const after = send("After"); + + const first = extractionSource(db, conversation.id, null); + expect(first?.watermarkId).toBe(after.id); + expect(first?.truncated).toBe(true); + expect(first?.messageCount).toBe(3); + const lines = first?.text.split("\n\n") ?? []; + expect(lines[0]).toBe("User: Before"); + expect(lines[1]).toMatch(/^User: Decision worth remembering [测🙂]+\n\[message truncated\]$/u); + expect(lines[1]?.isWellFormed()).toBe(true); + expect(lines[2]).toBe("User: After"); + expect(estimatedCost(lines)).toBeLessThanOrEqual(12_000); + + const latest = send("New turn"); + const second = extractionSource(db, conversation.id, after.id); + expect(second?.text).toBe("User: New turn"); + expect(second?.truncated).toBe(false); + + const oversized = send("A".repeat(60_000)); + const third = extractionSource(db, conversation.id, latest.id); + expect(third?.messageCount).toBe(1); + expect(third?.subjectMessageId).toBe(oversized.id); + expect(third?.text.endsWith("[message truncated]")).toBe(true); + } finally { + db.close(); + } +}, 30_000); + +it.each([ + { + name: "whole user turns would exhaust the budget", + turns: [`Long decision ${"L".repeat(60_000)}`, `Whole decision ${"W".repeat(47_960)}`], + prefixes: ["Long decision", "Whole decision"], + }, + { + name: "two oversized user turns are pending", + turns: [`First decision ${"A".repeat(60_000)}`, `Second decision ${"B".repeat(60_000)}`], + prefixes: ["First decision", "Second decision"], + }, +])( + "includes excerpts before advancing coverage when $name", + ({ turns, prefixes }) => { + const db = new DatabaseSync(":memory:"); + try { + runMigrations(db); + const bot = new BotsRepo(db).ensureMainBot(); + const conversation = new ConversationsRepo(db).create({ botId: bot.id }); + const messages = new MessagesRepo(db); + const send = (content: string) => + messages.create({ conversationId: conversation.id, role: "user", status: "done", content }); + const tail = turns.map(send).at(-1); + const source = extractionSource(db, conversation.id, null); + const lines = source?.text.split("\n\n") ?? []; + expect(lines.map((line) => line.split(" ").slice(1, 3).join(" "))).toEqual(prefixes); + expect(lines.every((line) => line.endsWith("[message truncated]"))).toBe(true); + expect(estimatedCost(lines)).toBeLessThanOrEqual(12_000); + expect(source?.watermarkId).toBe(tail?.id); + + send("Later"); + expect(extractionSource(db, conversation.id, source?.watermarkId ?? null)?.text).toBe( + "User: Later", + ); + } finally { + db.close(); + } + }, + 30_000, +); + +it("keeps only whole eligible statements as group evidence", () => { + const db = new DatabaseSync(":memory:"); + try { + runMigrations(db); + const bots = new BotsRepo(db); + const coordinator = bots.ensureMainBot(); + const member = bots.create({ + name: "Member", + isMain: false, + avatarShape: "blob", + avatarColor: "orange", + avatarEyes: "marks", + modelProvider: null, + modelId: null, + thinkingLevel: "off", + systemPrompt: "", + }); + const group = new GroupsRepo(db).create({ + name: "Extraction test", + botIds: [coordinator.id, member.id], + coordinatorBotId: coordinator.id, + }); + const topic = new ConversationsRepo(db).forGroup(group.id); + if (!topic) throw new Error("Missing group topic"); + const messages = new MessagesRepo(db); + const send = (content: string) => + messages.create({ conversationId: topic.id, role: "user", status: "done", content }); + + send(`Oversized group statement ${"A".repeat(60_000)}`); + const full = send("Confirmed whole group statement"); + const source = extractionSource(db, topic.id, null, 12_000, group.id); + + expect(source?.text).toBe(`Owner [${full.id}]: ${full.content}`); + expect(source?.groupSourceIds).toEqual([full.id]); + expect(source?.groupSourceTexts).toEqual({ [full.id]: full.content }); + expect(source?.truncated).toBe(true); + } finally { + db.close(); + } +}, 30_000); + +it("keeps a short earlier turn when an almost-full turn precedes the excerpt allocation", () => { + const db = new DatabaseSync(":memory:"); + try { + runMigrations(db); + const bot = new BotsRepo(db).ensureMainBot(); + const conversation = new ConversationsRepo(db).create({ botId: bot.id }); + const messages = new MessagesRepo(db); + const send = (content: string) => + messages.create({ conversationId: conversation.id, role: "user", status: "done", content }); + + send("My timezone is UTC."); + send(`Earlier decision ${"L".repeat(60_000)}`); + const latest = `Latest decision ${"A".repeat((11_968 - 4) * 4 - "User: Latest decision ".length)}`; + expect(estimatedCost([`User: ${latest}`])).toBe(11_968); + const tail = send(latest); + + const source = extractionSource(db, conversation.id, null); + const lines = source?.text.split("\n\n") ?? []; + expect(lines).toHaveLength(3); + expect(lines[0]).toBe("User: My timezone is UTC."); + expect(lines[1]).toMatch(/^User: Earlier decision L+\n\[message truncated\]$/u); + expect(lines[2]).toMatch(/^User: Latest decision A+\n\[message truncated\]$/u); + expect(estimatedCost(lines)).toBeLessThanOrEqual(12_000); + expect(source?.watermarkId).toBe(tail.id); + + send("Later"); + expect(extractionSource(db, conversation.id, tail.id)?.text).toBe("User: Later"); + } finally { + db.close(); + } +}, 30_000);