Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(memory): recall Chinese and Japanese notes by the words inside a sentence

heimixieb949cabedd9c5
diff --git a/server/cjk-search.test.ts b/server/cjk-search.test.ts
new file mode 100644
index 0000000000..89be4671cc
--- /dev/null
+++ b/server/cjk-search.test.ts
@@ -0,0 +1,117 @@
+import { rmSync } from "node:fs";
+import { DatabaseSync } from "node:sqlite";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { cjkSearchText, cjkTokenParts, ensureSearchIndex, ftsPhrase, withoutSearchMarks } from "./cjk-search.ts";
+import { DATA_DIR } from "./config.ts";
+import { closeMessageDb } from "./message-db.ts";
+import { memoryPassages, recallQuery } from "./recall.ts";
+import { WORKSPACES_DIR, writeMemoryTopic } from "./workspace.ts";
+
+const SPEC = { table: "messages", fts: "messages_fts", view: "messages_search", triggerPrefix: "messages_fts" };
+
+describe("CJK search text", () => {
+ it("splits every CJK character from its neighbours and leaves other text alone", () => {
+ expect(cjkSearchText("Buy milk")).toBeNull();
+ expect(cjkSearchText(null)).toBeNull();
+ const indexed = cjkSearchText("iPhone15电池, 图书馆")!;
+ expect(withoutSearchMarks(indexed)).toBe("iPhone15电池, 图书馆");
+ expect(indexed.split("​")).toEqual(["iPhone15", "电", "池, 图", "书", "馆"]);
+ });
+
+ it("queries a CJK term as a phrase of its characters", () => {
+ expect(ftsPhrase("图书馆")).toBe('"图 书 馆"');
+ expect(ftsPhrase("iphone15电池")).toBe('"iphone15 电 池"');
+ expect(ftsPhrase("milk")).toBe('"milk"');
+ });
+
+ it("makes bigrams of CJK runs and keeps the rest", () => {
+ expect(cjkTokenParts("iphone15的电池")).toEqual({ other: ["iphone15"], bigrams: ["电池"] });
+ expect(cjkTokenParts("图书馆")).toEqual({ other: [], bigrams: ["图书", "书馆"] });
+ });
+});
+
+describe("the search index", () => {
+ const legacy = () => {
+ const db = new DatabaseSync(":memory:");
+ db.exec(`
+ CREATE TABLE messages (id TEXT PRIMARY KEY, text TEXT);
+ CREATE VIRTUAL TABLE messages_fts USING fts5(text, content='messages', content_rowid='rowid', tokenize='unicode61');
+ CREATE TRIGGER messages_fts_ai AFTER INSERT ON messages BEGIN
+ INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text);
+ END;
+ `);
+ db.prepare("INSERT INTO messages (id, text) VALUES (?, ?)").run("zh", "周三下午三点要去社区图书馆还书。");
+ db.prepare("INSERT INTO messages (id, text) VALUES (?, ?)").run("en", "Buy milk tomorrow");
+ return db;
+ };
+ const match = (db: DatabaseSync, query: string) =>
+ (db.prepare("SELECT m.id FROM messages_fts JOIN messages m ON m.rowid = messages_fts.rowid WHERE messages_fts MATCH ?").all(query) as Array<{ id: string }>)
+ .map((row) => row.id);
+
+ it("migrates a plain-text index so a word inside a Chinese sentence is found, and English still is", () => {
+ const db = legacy();
+ expect(match(db, '"图书馆"')).toEqual([]);
+ ensureSearchIndex(db, SPEC);
+ expect(match(db, ftsPhrase("图书馆"))).toEqual(["zh"]);
+ expect(match(db, '"milk"')).toEqual(["en"]);
+ db.exec("INSERT INTO messages_fts(messages_fts) VALUES ('integrity-check')");
+ });
+
+ it("is unchanged by a second open, and keeps writes, edits and deletes in step", () => {
+ const db = legacy();
+ ensureSearchIndex(db, SPEC);
+ ensureSearchIndex(db, SPEC);
+ db.prepare("INSERT INTO messages (id, text, search_text) VALUES (?, ?, ?)").run("new", "冰箱冷冻室设在零下十八度", cjkSearchText("冰箱冷冻室设在零下十八度"));
+ expect(match(db, ftsPhrase("冷冻"))).toEqual(["new"]);
+ db.prepare("UPDATE messages SET text = ?, search_text = ? WHERE id = ?").run("阳台绿萝每周浇水", cjkSearchText("阳台绿萝每周浇水"), "new");
+ expect(match(db, ftsPhrase("冷冻"))).toEqual([]);
+ expect(match(db, ftsPhrase("绿萝"))).toEqual(["new"]);
+ db.prepare("DELETE FROM messages WHERE id = ?").run("zh");
+ expect(match(db, ftsPhrase("图书"))).toEqual([]);
+ db.exec("INSERT INTO messages_fts(messages_fts) VALUES ('integrity-check')");
+ });
+});
+
+// Ordinary notes a person's assistant keeps, each asked about later in other words.
+const NOTES: Array<[note: string, question: string]> = [
+ ["净水器的滤芯每六个月更换一次,上次是五月初换的。", "滤芯多久要换一次?"],
+ ["周三下午三点去社区图书馆还书,顺便续借阅卡。", "借的书哪天去图书馆还?"],
+ ["车子的保险在明年三月到期,要提前一个月续保。", "车险什么时候到期"],
+ ["牙医预约在下周五上午十点,地点是人民路口腔诊所。", "牙医预约是几点"],
+ ["每月十五号自动扣视频会员费,二十五元。", "视频会员每个月扣多少钱"],
+ ["妈妈的生日是农历八月十二,记得提前订蛋糕。", "我妈生日是哪天"],
+ ["家里的宽带办在电信,套餐年底到期。", "宽带是哪家运营商办的"],
+ ["护照有效期到2028年,办签证前要确认。", "护照什么时候过期"],
+ ["公司报销需要在每月25日前提交发票。", "发票报销截止是几号"],
+ ["阳台的绿萝每周浇一次水,冬天十天一次。", "绿萝多久浇水"],
+ ["下个月去杭州出差,酒店订在西湖边。", "杭州出差住哪个酒店"],
+ ["孩子的英语辅导班每周六上午九点上课。", "英语辅导班星期几上课"],
+ ["冰箱下层的冷冻室温度设在零下十八度。", "冷冻室温度调到多少"],
+ ["体检报告显示血脂偏高,医生建议少吃油炸食品。", "上次体检报告说了什么"],
+ ["房租每季度交一次,房东微信是老王。", "房租怎么交"],
+ ["电动车每两天充一次电,充电器放在门口柜子里。", "充电器放哪里了"],
+ ["信用卡账单日是每月五号,还款日是二十三号。", "信用卡哪天还款"],
+ ["狗狗的疫苗下次接种时间是十二月十号。", "狗打疫苗是什么时候"],
+ ["楼下快递柜的取件码一般发到短信里。", "快递取件码在哪看"],
+ ["年假还剩六天,打算春节前后一起休。", "我还有几天年假"],
+];
+
+describe("Chinese recall", () => {
+ const BOT = "bot-cjk-recall";
+ beforeEach(() => {
+ closeMessageDb();
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ rmSync(WORKSPACES_DIR, { recursive: true, force: true });
+ });
+
+ it("recalls a Chinese note for a paraphrased Chinese question", () => {
+ NOTES.forEach(([note], i) => writeMemoryTopic(BOT, `note-${i}.md`, `${note}\n`));
+ const found = NOTES.filter(([, question], i) =>
+ recallQuery(question) !== null && memoryPassages(BOT, question).some((passage) => passage.label === `memory/note-${i}.md`));
+ expect(found.length).toBe(NOTES.length);
+ const passage = memoryPassages(BOT, "借的书哪天去图书馆还?")[0];
+ expect(passage?.snippet).toContain("社区图书馆还书");
+ expect(passage?.snippet).not.toContain("​");
+ });
+});
diff --git a/server/cjk-search.ts b/server/cjk-search.ts
new file mode 100644
index 0000000000..8817f994ff
--- /dev/null
+++ b/server/cjk-search.ts
@@ -0,0 +1,93 @@
+import type { DatabaseSync } from "node:sqlite";
+
+// FTS5's unicode61 tokenizer has no CJK dictionary and indexes a whole Han or kana run as one token, so a word in the
+// middle of a sentence can never match. Each CJK character becomes its own token instead (split by U+200B, which
+// unicode61 treats as a separator and a reader never sees), and a query asks for its characters as phrases.
+const CJK = "\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}";
+const CJK_CHAR = new RegExp(`[${CJK}]`, "u");
+const CJK_RUNS = new RegExp(`[${CJK}]+|[^${CJK}]+`, "gu");
+const CJK_BOUNDARY = new RegExp(`(?<=[${CJK}])(?=[\\p{L}\\p{N}])|(?<=[\\p{L}\\p{N}])(?=[${CJK}])`, "gu");
+const SEARCH_MARK = /​/g;
+
+/** Particles and filler words say nothing about what a note is about; they also end a run, so no bigram straddles one. */
+const FILLER = new RegExp(
+ "我们|你们|他们|她们|它们|这个|那个|一下|一个|可以|时候|现在|知道|告诉|记得|还是|就是|不是|没有|已经|因为|所以|但是|如果|然后|还有|请问|帮我|怎样|这样|那样|哪里|哪个|应该|一些|[的了是吗呢吧啊呀哦嗯么]",
+ "gu",
+);
+
+export const hasCjk = (text: string): boolean => CJK_CHAR.test(text);
+
+/** The indexed form of `text`, or null when it holds no CJK and is indexed as written. */
+export function cjkSearchText(text: string | null | undefined): string | null {
+ return text && hasCjk(text) ? text.replace(CJK_BOUNDARY, "​") : null;
+}
+
+export const withoutSearchMarks = (snippet: string): string => snippet.replace(SEARCH_MARK, "");
+
+/** A quoted FTS5 phrase whose tokens line up with the indexed form. */
+export const ftsPhrase = (term: string): string => `"${term.replace(/"/g, "").replace(CJK_BOUNDARY, " ")}"`;
+
+/** `token` split into its CJK runs and the rest; each CJK run becomes its overlapping bigrams, so a paraphrase still
+ * shares most of them with a note. */
+export function cjkTokenParts(token: string): { other: string[]; bigrams: string[] } {
+ const other: string[] = [];
+ const bigrams: string[] = [];
+ for (const run of token.match(CJK_RUNS) ?? []) {
+ if (!hasCjk(run)) {
+ other.push(run);
+ continue;
+ }
+ for (const segment of run.replace(FILLER, " ").split(" ")) {
+ const chars = [...segment];
+ for (let i = 0; i + 1 < chars.length; i++) bigrams.push(chars[i]! + chars[i + 1]!);
+ }
+ }
+ return { other, bigrams };
+}
+
+export interface SearchIndexSpec {
+ table: string;
+ fts: string;
+ view: string;
+ triggerPrefix: string;
+}
+
+/** The table's FTS5 index over `coalesce(search_text, text)`, built or migrated from the plain-text index. */
+export function ensureSearchIndex(db: DatabaseSync, { table, fts, view, triggerPrefix: t }: SearchIndexSpec): void {
+ const columns = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
+ if (!columns.some((column) => column.name === "search_text")) db.exec(`ALTER TABLE ${table} ADD COLUMN search_text TEXT`);
+ const existing = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(fts) as { sql: string } | undefined;
+ const current = Boolean(existing?.sql.includes(`'${view}'`));
+ if (!current) {
+ db.exec(`DROP TRIGGER IF EXISTS ${t}_ai; DROP TRIGGER IF EXISTS ${t}_ad; DROP TRIGGER IF EXISTS ${t}_au; DROP TABLE IF EXISTS ${fts};`);
+ const update = db.prepare(`UPDATE ${table} SET search_text = ? WHERE rowid = ?`);
+ db.exec("BEGIN");
+ try {
+ for (const row of db.prepare(`SELECT rowid, text FROM ${table} WHERE text IS NOT NULL AND search_text IS NULL`).iterate()) {
+ const searchText = cjkSearchText(row.text as string);
+ if (searchText) update.run(searchText, row.rowid as number);
+ }
+ db.exec("COMMIT");
+ } catch (error) {
+ db.exec("ROLLBACK");
+ throw error;
+ }
+ }
+ db.exec(`
+ CREATE VIEW IF NOT EXISTS ${view} AS SELECT rowid AS rid, coalesce(search_text, text) AS text FROM ${table};
+ CREATE VIRTUAL TABLE IF NOT EXISTS ${fts} USING fts5(
+ text, content='${view}', content_rowid='rid', tokenize='unicode61'
+ );
+ CREATE TRIGGER IF NOT EXISTS ${t}_ai AFTER INSERT ON ${table} BEGIN
+ INSERT INTO ${fts}(rowid, text) VALUES (new.rowid, coalesce(new.search_text, new.text));
+ END;
+ CREATE TRIGGER IF NOT EXISTS ${t}_ad AFTER DELETE ON ${table} BEGIN
+ INSERT INTO ${fts}(${fts}, rowid, text) VALUES ('delete', old.rowid, coalesce(old.search_text, old.text));
+ END;
+ CREATE TRIGGER IF NOT EXISTS ${t}_au AFTER UPDATE ON ${table} BEGIN
+ INSERT INTO ${fts}(${fts}, rowid, text) VALUES ('delete', old.rowid, coalesce(old.search_text, old.text));
+ INSERT INTO ${fts}(rowid, text) VALUES (new.rowid, coalesce(new.search_text, new.text));
+ END;
+ `);
+ if (!current) db.exec(`INSERT INTO ${fts}(${fts}) VALUES ('rebuild')`);
+}
diff --git a/server/memory-layer.e2e.test.ts b/server/memory-layer.e2e.test.ts
index 36b0f15d59..33264695eb 100644
--- a/server/memory-layer.e2e.test.ts
+++ b/server/memory-layer.e2e.test.ts
@@ -75,6 +75,15 @@ it("recalls, captures, suggests, forgets and tidies a bot's memory", async () =>
expect(sentSince(before)).toContain("Bluebird");
expect(sentSince(before)).toMatch(/your main chat|chat \\"[^"\\]+\\"/);
+ await api(`/api/bots/${bot.id}/memory/file`, "PUT", { path: "memory/home.md", text: "- 净水器的滤芯每六个月更换一次,上次是五月初换的。\n" });
+ before = sentCount();
+ await turn(bot.id, second, "滤芯多久要换一次?");
+ expect(sentSince(before)).toContain("滤芯每六个月更换一次");
+ await turn(bot.id, bot.threadId, "备忘:周三下午三点去社区图书馆还书。");
+ before = sentCount();
+ await turn(bot.id, second, "借的书哪天去图书馆还?");
+ expect(sentSince(before)).toContain("社区图书馆还书");
+
await api(`/api/bots/${bot.id}`, "PATCH", { memoryEnabled: false });
before = sentCount();
await turn(bot.id, second, "Can you suggest some restaurants for Friday?");
diff --git a/server/memory-topics.ts b/server/memory-topics.ts
index 9c823cbc9f..9dc5d64657 100644
--- a/server/memory-topics.ts
+++ b/server/memory-topics.ts
@@ -1,6 +1,8 @@
// A memory/<topic>.md may begin with YAML frontmatter: `title`, `description`, `aliases`.
import { closeSync, openSync, readSync } from "node:fs";
+import { hasCjk } from "./cjk-search.ts";
+
const HEAD_BYTES = 2_048;
export const TOPIC_INDEX_MAX_TOPICS = 40;
export const TOPIC_INDEX_MAX_CHARS = 2_000;
@@ -54,7 +56,7 @@ export function parseTopicHeader(text: string): TopicHeader {
export function topicWords(name: string, header: TopicHeader): string[] {
const text = [name.replace(/\.md$/i, "").replace(/[-_.]+/g, " "), header.title ?? "", header.description ?? "", ...header.aliases].join(" ");
- return [...new Set(text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((word) => word.length >= 3))];
+ return [...new Set(text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((word) => word.length >= (hasCjk(word) ? 2 : 3)))];
}
export function topicBody(text: string): string {
diff --git a/server/message-db-memory-index.ts b/server/message-db-memory-index.ts
index 430f04531d..ca246540d5 100644
--- a/server/message-db-memory-index.ts
+++ b/server/message-db-memory-index.ts
@@ -1,5 +1,7 @@
import type { DatabaseSync } from "node:sqlite";
+import { ensureSearchIndex } from "./cjk-search.ts";
+
export function ensureMemoryIndex(db: DatabaseSync): void {
db.exec(`
CREATE TABLE IF NOT EXISTS memory_files (
@@ -10,18 +12,6 @@ export function ensureMemoryIndex(db: DatabaseSync): void {
bytes INTEGER NOT NULL,
PRIMARY KEY (bot_id, path)
);
- CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(
- text, content='memory_files', content_rowid='rowid', tokenize='unicode61'
- );
- CREATE TRIGGER IF NOT EXISTS memory_fts_ai AFTER INSERT ON memory_files BEGIN
- INSERT INTO memory_fts(rowid, text) VALUES (new.rowid, new.text);
- END;
- CREATE TRIGGER IF NOT EXISTS memory_fts_ad AFTER DELETE ON memory_files BEGIN
- INSERT INTO memory_fts(memory_fts, rowid, text) VALUES ('delete', old.rowid, old.text);
- END;
- CREATE TRIGGER IF NOT EXISTS memory_fts_au AFTER UPDATE ON memory_files BEGIN
- INSERT INTO memory_fts(memory_fts, rowid, text) VALUES ('delete', old.rowid, old.text);
- INSERT INTO memory_fts(rowid, text) VALUES (new.rowid, new.text);
- END;
`);
+ ensureSearchIndex(db, { table: "memory_files", fts: "memory_fts", view: "memory_search", triggerPrefix: "memory_fts" });
}
diff --git a/server/message-db.ts b/server/message-db.ts
index 14ca989c0c..ee6cf0c7e4 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -9,6 +9,7 @@ import type { ResolvedSender, SteerQueueReason } from "../shared/wire.ts";
import type { Message } from "./store.ts";
import type { UsageTrigger } from "./usage-ledger.ts";
import { ensureMemoryIndex } from "./message-db-memory-index.ts";
+import { cjkSearchText, cjkTokenParts, ensureSearchIndex, ftsPhrase, hasCjk, withoutSearchMarks } from "./cjk-search.ts";
import { attentionSelect } from "./message-db-attention.ts";
import { MessageSearchWorker } from "./message-search-worker.ts";
import { searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts";
@@ -115,38 +116,20 @@ export function describeMissingFts5(error: unknown): Error | null {
}
function ensureRecallIndex(db: DatabaseSync): void {
- const existed = db
- .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'")
- .get();
try {
- db.exec(`
- CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
- text, content='messages', content_rowid='rowid', tokenize='unicode61'
- );
- `);
+ ensureSearchIndex(db, { table: "messages", fts: "messages_fts", view: "messages_search", triggerPrefix: "messages_fts" });
} catch (error) {
throw describeMissingFts5(error) ?? error;
}
- db.exec(`
- CREATE TRIGGER IF NOT EXISTS messages_fts_ai AFTER INSERT ON messages BEGIN
- INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text);
- END;
- CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN
- INSERT INTO messages_fts(messages_fts, rowid, text) VALUES ('delete', old.rowid, old.text);
- END;
- CREATE TRIGGER IF NOT EXISTS messages_fts_au AFTER UPDATE ON messages BEGIN
- INSERT INTO messages_fts(messages_fts, rowid, text) VALUES ('delete', old.rowid, old.text);
- INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text);
- END;
- `);
- if (!existed) db.exec("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')");
}
// INSERT OR REPLACE skips the delete trigger (SQLite fires it only with recursive triggers on), so upsert to keep FTS in step.
const UPSERT_MESSAGE =
- "INSERT INTO messages (thread_id, id, at, role, kind, text, json) VALUES (?, ?, ?, ?, ?, ?, ?) " +
+ "INSERT INTO messages (thread_id, id, at, role, kind, text, json, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT(thread_id, id) DO UPDATE SET at = excluded.at, role = excluded.role, kind = excluded.kind, " +
- "text = excluded.text, json = excluded.json";
+ "text = excluded.text, json = excluded.json, search_text = excluded.search_text";
+const messageRow = (threadId: string, message: Message) =>
+ [threadId, message.id, message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message), cjkSearchText(message.text)] as const;
const ACTIVE_LEAF = "SELECT active_leaf_id FROM thread_state WHERE thread_id = ?";
function db(): DatabaseSync {
@@ -425,9 +408,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {
const insert = db().prepare(UPSERT_MESSAGE);
db().exec("BEGIN");
try {
- for (const message of messages) {
- insert.run(threadId, message.id, message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message));
- }
+ for (const message of messages) insert.run(...messageRow(threadId, message));
setActiveLeaf(threadId, activeLeafId);
db().exec("COMMIT");
} catch (error) {
@@ -444,7 +425,7 @@ function importLegacy(threadId: string, legacyFile: string): ThreadRows {
}
export function insertMessage(threadId: string, message: Message): void {
- prepared(UPSERT_MESSAGE).run(threadId, message.id, message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message));
+ prepared(UPSERT_MESSAGE).run(...messageRow(threadId, message));
}
/** `relinked`: adds `messages` to a conversation that has rows; each row it names changes only its parentId, and an id it already has fails the whole import. */
@@ -454,9 +435,9 @@ export function importThread(threadId: string, messages: Message[], activeLeafId
database.prepare("SELECT 1 FROM thread_state WHERE thread_id = ?").get(threadId))) {
throw new Error("Cannot import over an existing conversation");
}
- const insert = relinked && database.prepare("INSERT INTO messages (thread_id, id, at, role, kind, text, json) VALUES (?, ?, ?, ?, ?, ?, ?)");
+ const insert = relinked && database.prepare("INSERT INTO messages (thread_id, id, at, role, kind, text, json, search_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
for (const message of messages) {
- if (insert) insert.run(threadId, message.id, message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message));
+ if (insert) insert.run(...messageRow(threadId, message));
else insertMessage(threadId, message);
}
const link = database.prepare("UPDATE messages SET json = json_set(json, '$.parentId', ?) WHERE thread_id = ? AND id = ?");
@@ -473,7 +454,7 @@ export function appendMessage(threadId: string, message: Message): void {
}
export function updateMessage(threadId: string, message: Message): void {
- prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message), threadId, message.id);
+ prepared("UPDATE messages SET at = ?, role = ?, kind = ?, text = ?, json = ?, search_text = ? WHERE thread_id = ? AND id = ?").run(message.at, message.role, message.kind, message.text ?? null, JSON.stringify(message), cjkSearchText(message.text), threadId, message.id);
}
export function workingGoalRunMessages(): Array<{ threadId: string; message: Message }> {
@@ -745,12 +726,13 @@ function ftsQuery(query: string, mode: SearchMode = "all"): string | null {
const terms = recallTerms(query).map(recallMatchTerm).filter(Boolean);
return terms.length ? terms.join(" OR ") : null;
}
- return (content.length ? content : tokens).map((token) => `"${token}"`).join(" ");
+ return (content.length ? content : tokens).map(ftsPhrase).join(" ");
}
/** FTS5's unicode61 tokenizer cannot tell "-10" from "10" or "c++" from "c", even quoted, so punctuation terms are skipped. */
export function recallMatchTerm(term: string): string | null {
if (!/^[\p{L}\p{N}]+$/u.test(term)) return null;
+ if (hasCjk(term)) return ftsPhrase(term);
if (!/^\p{L}{4,}$/u.test(term)) return `"${term}"`;
const stem = term.length > 4 && term.endsWith("s") && !term.endsWith("ss") ? term.slice(0, -1) : term;
return `"${stem}"*`;
@@ -762,16 +744,23 @@ const RECALL_FILLER = new Set(
"about again also any anything can could does don't know me my please remember remind should tell there they us would hi hello hey thanks thank ok okay yes yeah no i'm im i've i'll i'd you're quick just".split(" "),
);
+const trimToken = (raw: string) => raw.replace(/"/g, "").replace(/^[\s.,;:!?()[\]{}'`“”‘’]+|[\s.,;:!?()[\]{}'`“”‘’]+$/g, "").toLowerCase();
+
+/** Words first, then the CJK bigrams, each list capped on its own so a long Chinese message cannot crowd out the words. */
export function recallTerms(query: string): string[] {
const out: string[] = [];
+ const bigrams: string[] = [];
for (const raw of query.split(/[\s、。!?;:,()【】《》〈〉「」『』]+|(?<=\p{L})[/,;:.—–-]+(?=\p{L})/u)) {
- const token = raw.replace(/"/g, "").replace(/^[\s.,;:!?()[\]{}'`“”‘’]+|[\s.,;:!?()[\]{}'`“”‘’]+$/g, "").toLowerCase();
- if (token.length < 2 && !/\d/.test(token)) continue;
- if (!/[\p{L}\p{N}]/u.test(token)) continue;
- if (STOP_WORDS.has(token) || RECALL_FILLER.has(token)) continue;
- if (!out.includes(token)) out.push(token);
+ const parts = hasCjk(raw) ? cjkTokenParts(raw.toLowerCase()) : { other: [raw], bigrams: [] };
+ for (const pair of parts.bigrams) if (!bigrams.includes(pair)) bigrams.push(pair);
+ for (const token of parts.other.map(trimToken)) {
+ if (token.length < 2 && !/\d/.test(token)) continue;
+ if (!/[\p{L}\p{N}]/u.test(token)) continue;
+ if (STOP_WORDS.has(token) || RECALL_FILLER.has(token)) continue;
+ if (!out.includes(token)) out.push(token);
+ }
}
- return out.slice(0, 16);
+ return [...out.slice(0, 16), ...bigrams.slice(0, 24)];
}
const SNIPPET_TOKENS = 48;
@@ -854,7 +843,7 @@ export function recallMessages(query: string, threadIds: readonly string[], limi
at: row.at,
role: row.role,
...(row.kind === "digest" ? { kind: "digest" as const } : {}),
- snippet: row.snippet.replace(/\s+/g, " ").trim(),
+ snippet: withoutSearchMarks(row.snippet).replace(/\s+/g, " ").trim(),
...(row.from_name ? { from: row.from_name } : {}),
...(peer ? { peer } : {}),
};
@@ -936,10 +925,11 @@ export interface MemoryFileStat {
export function indexMemoryFile(botId: string, path: string, text: string, stat: { mtimeMs: number; bytes: number }): void {
db()
.prepare(
- "INSERT INTO memory_files (bot_id, path, text, mtime_ms, bytes) VALUES (?, ?, ?, ?, ?) " +
- "ON CONFLICT(bot_id, path) DO UPDATE SET text = excluded.text, mtime_ms = excluded.mtime_ms, bytes = excluded.bytes",
+ "INSERT INTO memory_files (bot_id, path, text, mtime_ms, bytes, search_text) VALUES (?, ?, ?, ?, ?, ?) " +
+ "ON CONFLICT(bot_id, path) DO UPDATE SET text = excluded.text, mtime_ms = excluded.mtime_ms, bytes = excluded.bytes, " +
+ "search_text = excluded.search_text",
)
- .run(botId, path, text, Math.trunc(stat.mtimeMs), stat.bytes);
+ .run(botId, path, text, Math.trunc(stat.mtimeMs), stat.bytes, cjkSearchText(text));
}
export function removeMemoryFile(botId: string, path: string): void {
@@ -978,7 +968,7 @@ export function recallMemory(query: string, botId: string, limit = 12, mode: Sea
)
// SAFETY: the SELECT names exactly these three columns; snippet() is never null
.all(match, botId, limit) as Array<{ path: string; mtime_ms: number; snippet: string }>;
- return rows.map((row) => ({ file: row.path, at: row.mtime_ms, snippet: row.snippet.replace(/\s+/g, " ").trim() }));
+ return rows.map((row) => ({ file: row.path, at: row.mtime_ms, snippet: withoutSearchMarks(row.snippet).replace(/\s+/g, " ").trim() }));
}
/** Await before maintenance replaces the database or shutdown releases its lease. */
diff --git a/server/recall.test.ts b/server/recall.test.ts
index 53dbaccfe0..dcd2ee9fef 100644
--- a/server/recall.test.ts
+++ b/server/recall.test.ts
@@ -28,10 +28,18 @@ describe("recall terms and query", () => {
it("splits selected CJK punctuation without breaking signs, symbols or versions", () => {
expect(recallTerms("「本季度预算审批结果?」、【采购计划】;《项目安排》:(预算,审批。进度!)-10、C++、v2.1")).toEqual([
- "本季度预算审批结果", "采购计划", "项目安排", "预算", "审批", "进度", "-10", "c++", "v2.1",
+ "-10", "c++", "v2.1",
+ "本季", "季度", "度预", "预算", "算审", "审批", "批结", "结果", "采购", "购计", "计划", "项目", "目安", "安排", "进度",
]);
});
+ it("splits Chinese into bigrams that never straddle a particle or filler word, and keeps the words beside them", () => {
+ expect(recallTerms("我们什么时候去图书馆还书?")).toEqual(["去图", "图书", "书馆", "馆还", "还书"]);
+ expect(recallTerms("iPhone15的电池")).toEqual(["iphone15", "电池"]);
+ expect(recallQuery("滤芯多久换")).not.toBeNull();
+ expect(recallQuery("好的")).toBeNull();
+ });
+
it("drops greetings, so a hello never recalls a bot's own greeting", () => {
expect(recallTerms("Hi! Quick intro: I'm Omkar")).toEqual(["intro", "omkar"]);
expect(recallQuery("hello there, thanks!")).toBeNull();
diff --git a/server/recall.ts b/server/recall.ts
index f30f3dfbc4..e529332453 100644
--- a/server/recall.ts
+++ b/server/recall.ts
@@ -3,6 +3,7 @@ import { recallMessages, recallTerms, type MemoryHit, type RecallHit } from "./m
import { parseTopicHeader, readTopicHead, topicBody, topicWords } from "./memory-topics.ts";
import { listMemoryTopics, memoryDate, readMemoryTopic, searchMemoryFiles, workspaceDir } from "./workspace.ts";
import { withoutExpired, withoutSuperseded } from "./memory-entries.ts";
+import { hasCjk } from "./cjk-search.ts";
import { join } from "node:path";
type RecallOwner = { id: string; threadId: string; tasks?: readonly { threadId: string }[] };
@@ -51,18 +52,26 @@ export interface RecallResult {
conversations: number;
}
+/** A CJK character carries about a word, so it counts twice toward the minimum length. */
export function recallQuery(text: string): string | null {
const trimmed = text.trim();
- if (trimmed.length < RECALL_MIN_CHARS) return null;
+ if (trimmed.length + [...trimmed].filter(hasCjk).length < RECALL_MIN_CHARS) return null;
return recallTerms(trimmed.slice(0, RECALL_QUERY_CHARS)).length ? trimmed.slice(0, RECALL_QUERY_CHARS) : null;
}
-/** FTS5 brackets the matched terms in a snippet. */
+/** FTS5 brackets the matched terms in a snippet; overlapping CJK bigrams share one bracket, so those count by term. */
const plain = (snippet: string) => snippet.replace(/\[([^[\]]+)\]/g, "$1");
-const matchedTerms = (snippet: string) => new Set([...snippet.matchAll(/\[([^[\]]+)\]/g)].map((m) => m[1]!.toLowerCase())).size;
+function matchedTerms(terms: readonly string[], snippet: string): number {
+ const bigrams = terms.filter(hasCjk);
+ const regions = [...snippet.matchAll(/\[([^[\]]+)\]/g)].map((m) => m[1]!.toLowerCase());
+ return new Set(regions.flatMap((region) => (hasCjk(region) ? bigrams.filter((term) => region.includes(term)) : [region]))).size;
+}
+/** A Chinese word spans about two overlapping bigrams, so bigrams count half toward the content words of a question. */
export function enoughMatches(query: string, snippet: string): boolean {
- return recallTerms(query).length < MIN_TERMS_FOR_TWO || matchedTerms(snippet) >= 2;
+ const terms = recallTerms(query);
+ const bigrams = terms.filter(hasCjk).length;
+ return terms.length - bigrams + Math.ceil(bigrams / 2) < MIN_TERMS_FOR_TWO || matchedTerms(terms, snippet) >= 2;
}
function day(at?: number): string {
@@ -117,6 +126,7 @@ const TOPIC_PASSAGE_CHARS = 600;
function sameWord(term: string, word: string): boolean {
if (term === word) return true;
+ if (hasCjk(term)) return word.includes(term);
if (!/^\p{L}{4,}$/u.test(term) || word.length < 4) return false;
const stem = term.length > 4 && term.endsWith("s") && !term.endsWith("ss") ? term.slice(0, -1) : term;
return word.startsWith(stem) || (stem.startsWith(word) && stem.length - word.length <= 3);
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index e2a3f6cc56..e4eed993d0 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -14,6 +14,7 @@ import { writeFileAtomic } from "./atomic.ts";
import { userErrorFields, userErrorThrown } from "./user-errors.ts";
import { WORKSPACE_BACKUP_CLIENT_KEYS } from "../shared/workspace-backup-client.ts";
import { INSTRUCTION_FILE, restorePaths, validRelative } from "./workspace-backup-paths.ts";
+import { cjkSearchText } from "./cjk-search.ts";
import { ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, liveDataEnginePath, managedTaskSkillLink, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";
import { omittedAsTeamPrivate, routinesWithoutTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";
import type { WorkspaceBackupClientState, WorkspaceBackupPrivateMetadata, WorkspaceBackupSummary, WorkspaceLeftBehind } from "../shared/workspace-backup.ts";
@@ -804,12 +805,14 @@ function prepareRestore(dataDir: string, id: string, manifest: Manifest): string
try {
db.exec("BEGIN");
if (manifest.sourceDataDir !== resolve(dataDir)) {
- const update = db.prepare("UPDATE messages SET json = ?, text = ? WHERE thread_id = ? AND id = ?");
+ const searchText = (db.prepare("PRAGMA table_info(messages)").all() as Array<{ name: string }>).some((column) => column.name === "search_text");
+ const update = db.prepare(`UPDATE messages SET json = ?, text = ?${searchText ? ", search_text = ?" : ""} WHERE thread_id = ? AND id = ?`);
for (const row of db.prepare("SELECT thread_id, id, json FROM messages").iterate()) {
const message: unknown = JSON.parse(String(row.json));
paths.message(message);
const json = JSON.stringify(message);
- if (json !== row.json) update.run(json, record(message) && typeof message.text === "string" ? message.text : null, row.thread_id, row.id);
+ const text = record(message) && typeof message.text === "string" ? message.text : null;
+ if (json !== row.json) update.run(json, text, ...(searchText ? [cjkSearchText(text)] : []), row.thread_id, row.id);
}
}
// Import is not a restart: the source may still be running, so never execute a copy of its pending work.