Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(memory): memory_search 中文子串检索失效 — FTS MATCH + LIKE 兜底 (#1537) (#1912)

KingSystemHaiGo8e409222da2c
diff --git a/packages/maker-core/src/memory/__tests__/fts.test.ts b/packages/maker-core/src/memory/__tests__/fts.test.ts
new file mode 100644
index 0000000000..f1843abcc4
--- /dev/null
+++ b/packages/maker-core/src/memory/__tests__/fts.test.ts
@@ -0,0 +1,177 @@
+/**
+ * MemoryFts 单测 — 用真 better-sqlite3 内存库。
+ *
+ * 重点覆盖 #1537: unicode61 tokenizer 把连续 CJK 文本当一个 token,
+ * phrase MATCH 无法命中中文子串, 必须由 LIKE 兜底捞回 (模式对齐 contacts/fts.ts)。
+ * 另覆盖 buildFilename 对带 type 前缀 slug 的拒绝 (#1652 附带小 bug)。
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import DatabaseCtor from 'better-sqlite3';
+import type Database from 'better-sqlite3';
+
+import { MemoryFts } from '../fts.js';
+import { buildFilename } from '../storage.js';
+import type { MemoryRecord } from '../types.js';
+
+function record(filename: string, body: string, overrides?: Partial<MemoryRecord>): MemoryRecord {
+ // 按 MemoryRecord 契约: slug 是去掉 <type>_ 前缀与 .md 后缀的部分 (types.ts)
+ const slug = filename.replace(/\.md$/, '').replace(/^(user|feedback|project|reference|digest)_/, '');
+ const type = (filename.match(/^(user|feedback|project|reference|digest)_/) ?? ['digest'])[0].replace(/_$/, '') as MemoryRecord['frontmatter']['type'];
+ return {
+ filename,
+ slug,
+ frontmatter: {
+ type,
+ title: `标题 ${filename}`,
+ description: `描述 ${filename}`,
+ updatedAt: '2026-08-06T00:00:00.000Z',
+ },
+ body,
+ sizeBytes: body.length,
+ ...overrides,
+ };
+}
+
+describe('MemoryFts', () => {
+ let db: Database.Database;
+ let fts: MemoryFts;
+
+ beforeEach(() => {
+ db = new DatabaseCtor(':memory:');
+ fts = new MemoryFts(db);
+ fts.init();
+ });
+
+ afterEach(() => {
+ db.close();
+ });
+
+ it('中文子串查询命中 (LIKE 兜底, #1537 主场景)', () => {
+ fts.upsert(record('project_a.md', 'MaxCompute 数据分析链路性能优化'));
+ fts.upsert(record('project_b.md', '边界索引配置说明'));
+
+ // 复现 issue: 无通配符的精确中文查询
+ const hits = fts.search('边界');
+ expect(hits.length).toBe(1);
+ expect(hits[0].filename).toBe('project_b.md');
+ });
+
+ it('英文精确查询仍走 MATCH 优先 (score = bm25 非 0)', () => {
+ fts.upsert(record('project_a.md', 'MaxCompute link 优化'));
+
+ const hits = fts.search('MaxCompute');
+ expect(hits.length).toBe(1);
+ expect(hits[0].filename).toBe('project_a.md');
+ expect(hits[0].score).not.toBe(Number.MAX_SAFE_INTEGER); // 走 MATCH 路径才带 bm25
+ });
+
+ it('MATCH 命中不足时合并 LIKE 兜底并按 filename 去重', () => {
+ // A: MATCH('link') 与 LIKE('%link%') 双命中
+ fts.upsert(record('project_a.md', '数据链路分析与 link 优化'));
+ // B: token 是 LinkedIn, MATCH('link') 不命中, 但 LIKE 大小写不敏感可命中
+ fts.upsert(record('project_b.md', 'LinkedIn 社交平台分析'));
+ // C: 双不命中
+ fts.upsert(record('project_c.md', 'MaxCompute 边界索引'));
+
+ const hits = fts.search('link');
+ const filenames = hits.map((h) => h.filename).sort();
+ expect(filenames).toEqual(['project_a.md', 'project_b.md']);
+ // 去重: A 只出现一次
+ expect(new Set(filenames).size).toBe(filenames.length);
+ });
+
+ it('type filter 对 MATCH 与 LIKE 兜底都生效', () => {
+ fts.upsert(record('project_a.md', '边界索引配置说明'));
+ fts.upsert(record('feedback_b.md', '边界相关反馈'));
+
+ const all = fts.search('边界');
+ expect(all.length).toBe(2);
+
+ const filtered = fts.search('边界', { type: 'feedback' });
+ expect(filtered.length).toBe(1);
+ expect(filtered[0].filename).toBe('feedback_b.md');
+ });
+
+ it('空查询返回空', () => {
+ fts.upsert(record('project_a.md', '内容'));
+ expect(fts.search('')).toEqual([]);
+ expect(fts.search(' ')).toEqual([]);
+ });
+
+ it('特殊字符查询不抛 (语法错被吞, 由 LIKE 兜底接管)', () => {
+ fts.upsert(record('project_a.md', '括号 (nested) 与引号 "quote" 内容'));
+ const hits = fts.search('"quote" 括号');
+ // 不抛异常即可; 能命中引号词更好
+ expect(Array.isArray(hits)).toBe(true);
+ });
+
+ it('limit 生效', () => {
+ for (let i = 0; i < 20; i++) {
+ fts.upsert(record(`project_${String(i).padStart(2, '0')}.md`, `共同词 内容 ${i}`));
+ }
+ expect(fts.search('共同词', { limit: 3 }).length).toBe(3);
+ expect(fts.search('共同词', { limit: 100 }).length).toBe(20); // 上限 50 不越界即可
+ });
+
+ it('MATCH 命中满 limit 时为 LIKE-only 子串命中预留 1 个名额', () => {
+ const spy = vi.spyOn(fts as unknown as { searchLike: (q: string, o: unknown, n: number) => unknown }, 'searchLike');
+ try {
+ // 7 条整 token 命中 (>= limit 3, 满额; 且 7 > limit*2=6, LIKE 全扫也排在前面) +
+ // 1 条 LIKE-only (LinkedIn, MATCH 不中) 在物理顺序最后 — 若 SQL 先 LIMIT 会被截掉
+ for (let i = 0; i < 7; i++) {
+ fts.upsert(record(`project_${String(i).padStart(2, '0')}.md`, `link 内容 ${i}`));
+ }
+ fts.upsert(record('project_linkedin.md', 'LinkedIn 社交平台'));
+ const hits = fts.search('link', { limit: 3 });
+ expect(spy).toHaveBeenCalled(); // 子串检索仍执行
+ expect(hits.length).toBe(3);
+ // 预留名额生效: 唯一的 LIKE-only 命中必须可见
+ expect(hits.some((h) => h.filename === 'project_linkedin.md')).toBe(true);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('limit=1 且 MATCH 满额时不预留 (保住唯一最佳 MATCH)', () => {
+ fts.upsert(record('project_a.md', 'link 内容'));
+ fts.upsert(record('project_linkedin.md', 'LinkedIn 社交平台'));
+ const hits = fts.search('link', { limit: 1 });
+ expect(hits.length).toBe(1);
+ expect(hits[0].filename).toBe('project_a.md'); // MATCH 优先, 不被 LIKE 挤掉
+ });
+
+ it('upsert 按 filename 去重, delete/count/rebuild 基本行为', () => {
+ fts.upsert(record('project_a.md', 'v1 边界'));
+ fts.upsert(record('project_a.md', 'v2 索引'));
+ expect(fts.count()).toBe(1);
+
+ fts.delete('project_a.md');
+ expect(fts.count()).toBe(0);
+
+ fts.upsert(record('project_b.md', '边界内容'));
+ fts.rebuild([record('project_b.md', '边界内容'), record('project_c.md', 'MaxCompute 链路')]);
+ expect(fts.count()).toBe(2);
+ expect(fts.search('MaxCompute').length).toBe(1);
+ });
+});
+
+describe('buildFilename · 拒绝 type 前缀 slug (#1652 附带小 bug)', () => {
+ it('slug 已带同 type 前缀时拒绝 (而非剥离), 避免存量分片定位错位', () => {
+ // 存量 feedback_feedback_foo.md 被 parseFilename 解析为 slug 'feedback_foo',
+ // 若剥离成 'foo' 会定位到不存在的 feedback_foo.md (not-found 或静默改错分片)
+ expect(() => buildFilename('feedback', 'feedback_foo')).toThrow(/invalid-slug/);
+ expect(() => buildFilename('project', 'project_pricing')).toThrow(/invalid-slug/);
+ });
+
+ it('不带前缀的纯 slug 原样拼装', () => {
+ expect(buildFilename('feedback', 'foo')).toBe('feedback_foo.md');
+ });
+
+ it('slug 恰好等于 type 名时报 invalid-slug', () => {
+ expect(() => buildFilename('feedback', 'feedback')).toThrow(/invalid-slug/);
+ });
+
+ it('只带前缀没有实体的 slug 报 invalid-slug', () => {
+ expect(() => buildFilename('feedback', 'feedback_')).toThrow(/invalid-slug/);
+ });
+});
diff --git a/packages/maker-core/src/memory/fts.ts b/packages/maker-core/src/memory/fts.ts
index 8fc3be7ab0..31749be3dd 100644
--- a/packages/maker-core/src/memory/fts.ts
+++ b/packages/maker-core/src/memory/fts.ts
@@ -5,8 +5,11 @@
* - 用 standalone FTS5 (所有列存表内, 含 body) 而非 contentless / external content。
* 理由: memory 量级小 (per-workdir 几十到一两百条), 空间开销可忽略;
* standalone 直接支持 snippet() 高亮, 不用维护内容→FTS 同步关系。
- * - tokenize='porter unicode61' — porter stemming + unicode61 分词, 中文按字符拆 (够用,
- * 专业中文 tokenizer 等真实漏检率高了再上 jieba)。
+ * - tokenize='porter unicode61' — porter stemming + unicode61 分词。⚠️ unicode61
+ * 把**连续 CJK 文本当一个 token** ("数据分析链路"是单 token), 中文子串无法被
+ * phrase MATCH 命中; 因此 search 用 **MATCH + LIKE 兜底** 保证 CJK 召回
+ * (模式对齐 contacts/fts.ts)。不换 trigram: 它对 <3 字符查询(如"边界")返回空,
+ * 且要重建存量 fts.db 表。
* - upsert = DELETE + INSERT (FTS5 没有 ON CONFLICT 子句)。
* - 不在 maker-core 加 better-sqlite3 runtime dep — 用 type-only import, 实例由 host
* (desktop) 注入, 跟 zero-electron-deps 边界一致。
@@ -29,6 +32,9 @@ import {
const TABLE = 'memory_fts';
const SNIPPET_TOKEN_RADIUS = 8; // snippet() 命中前后各取 N tokens
const DEFAULT_LIMIT = 10;
+const MAX_LIMIT = 50;
+/** LIKE 兜底没有 snippet() 高亮, 用 body 前 N 字符顶替 (防 UI 展示超长原文) */
+const SNIPPET_FALLBACK_LEN = 160;
export class MemoryFts {
constructor(private readonly db: Database.Database) {}
@@ -72,12 +78,33 @@ export class MemoryFts {
}
/**
- * 全文检索. query 直接走 FTS5 MATCH 语法 (支持 AND/OR/NOT/phrase "...")。
+ * 全文检索. query 经 escapeFtsQuery 转义为 phrase 后走 FTS5 MATCH
+ * (AND/OR/NOT 等高级语法会被转义吞掉, 见 escapeFtsQuery 说明)。
* 返回按 bm25 排序 (越小越相关) 的命中, 含 snippet() 高亮片段。
+ *
+ * CJK 兜底: unicode61 把连续 CJK 文本当一个 token, MATCH 只能覆盖整 token 命中;
+ * 中文子串(如「边界」在「边界索引配置说明」中) 只有 LIKE 扫描捞得到 —
+ * 始终合并 LIKE 兜底结果并按 filename 去重; MATCH 已满 limit 时为 LIKE-only
+ * 子串命中预留 1 个名额, 避免其被整 token 命中完全遮蔽。
*/
search(query: string, opts: SearchOptions = {}): SearchHit[] {
if (!query || query.trim().length === 0) return [];
- const limit = Math.max(1, Math.min(opts.limit ?? DEFAULT_LIMIT, 50));
+ const limit = Math.max(1, Math.min(opts.limit ?? DEFAULT_LIMIT, MAX_LIMIT));
+ // top = bm25 最佳 limit 条 (完整列); seen 用轻量查询取全部 MATCH 命中
+ // filename, 保证 fallback 里只剩 MATCH 永远命不中的 true LIKE-only
+ const top = this.searchMatch(query, opts, limit);
+ const seen = new Set(this.searchMatchFilenames(query, opts));
+ const fallback = this.searchLike(query, opts).filter((h) => !seen.has(h.filename));
+ if (limit > 1 && top.length >= limit && fallback.length > 0) {
+ // MATCH 已满 limit: 预留 1 个名额给 LIKE-only 子串命中, 避免中文子串结果
+ // 被整 token 命中完全遮蔽 (limit=1 时不预留, 保住唯一最佳 MATCH)
+ return [...top.slice(0, limit - 1), fallback[0]];
+ }
+ return [...top, ...fallback].slice(0, limit);
+ }
+
+ /** FTS5 MATCH 路径; query 语法错静默返空(让 LIKE 兜底接管) */
+ private searchMatch(query: string, opts: SearchOptions, limit: number): SearchHit[] {
const escapedQuery = escapeFtsQuery(query);
let sql = `SELECT filename, type, title,
@@ -111,11 +138,74 @@ export class MemoryFts {
} catch (e) {
// FTS5 query 语法错 (用户传了非法 token) 直接返空, 不抛 — 让 LLM 改写 query 重试。
const msg = (e as Error).message;
- if (msg.includes('fts5') || msg.includes('syntax error')) return [];
+ // 只吞明确的 MATCH 语法错误; 其他 FTS5 运行时错误 (snippet/bm25/索引损坏) 抛 io-error
+ // 避免真实故障被静默吞掉、search 退化到 LIKE-only 而难以定位 (Copilot review 反馈)
+ if (msg.includes('syntax error') || msg.includes('malformed MATCH expression')) return [];
throw new MemoryError('io-error', `fts search failed: ${msg}`);
}
}
+ /**
+ * 轻量查询: 只取全部 MATCH 命中的 filename (不计算 snippet/bm25) —
+ * 用于构建 seen 集合, 让 LIKE 兜底只剩 true LIKE-only 候选。
+ */
+ private searchMatchFilenames(query: string, opts: SearchOptions): string[] {
+ const escapedQuery = escapeFtsQuery(query);
+ let sql = `SELECT filename FROM ${TABLE} WHERE ${TABLE} MATCH ?`;
+ const params: unknown[] = [escapedQuery];
+ if (opts.type) {
+ sql += ` AND type = ?`;
+ params.push(opts.type);
+ }
+ try {
+ const rows = this.db.prepare(sql).all(...params) as Array<{ filename: string }>;
+ return rows.map((r) => r.filename);
+ } catch (e) {
+ const msg = (e as Error).message;
+ if (msg.includes('syntax error') || msg.includes('malformed MATCH expression')) return [];
+ throw new MemoryError('io-error', `fts match-filenames failed: ${msg}`);
+ }
+ }
+
+ /**
+ * LIKE 子串兜底: 大小写不敏感(LIKE 默认 ASCII 不敏感, CJK 逐字节精确), 无 bm25/snippet。
+ * 不做 SQL LIMIT — 由调用方去重后再截断: 否则 LIKE-only 命中排在 MATCH 双命中行
+ * 之后时会被先截掉, 预留名额失效 (memory 量级小, 全扫可接受)。
+ */
+ private searchLike(query: string, opts: SearchOptions): SearchHit[] {
+ const pattern = `%${escapeLikePattern(query.trim())}%`;
+ let sql = `SELECT filename, type, title, description, body
+ FROM ${TABLE}
+ WHERE (title LIKE ? ESCAPE '!' OR description LIKE ? ESCAPE '!' OR body LIKE ? ESCAPE '!')`;
+ const params: unknown[] = [pattern, pattern, pattern];
+ if (opts.type) {
+ sql += ` AND type = ?`;
+ params.push(opts.type);
+ }
+ sql += ` ORDER BY filename`;
+
+ try {
+ const rows = this.db.prepare(sql).all(...params) as Array<{
+ filename: string;
+ type: string;
+ title: string;
+ description: string;
+ body: string;
+ }>;
+ return rows.map((r) => ({
+ filename: r.filename,
+ type: r.type as MemoryType,
+ title: r.title,
+ // snippet 优先取实际命中的字段 (title/description/body), 保证与命中原因相关
+ snippet: truncate(hitField(r, query) ?? r.title, SNIPPET_FALLBACK_LEN),
+ // LIKE 兜底无 bm25: 用大值表示"未排名", 排在所有 MATCH 命中之后 (score 越小越相关)
+ score: Number.MAX_SAFE_INTEGER,
+ }));
+ } catch (e) {
+ throw new MemoryError('io-error', `fts like-fallback failed: ${(e as Error).message}`);
+ }
+ }
+
/**
* 全量重建. 在事务内 DELETE + 重新 INSERT 所有 records。
* 调用时机: storage 跟 fts 检测到不一致 (count 对不上) / 启动 sanity check / 手动触发。
@@ -158,3 +248,22 @@ export class MemoryFts {
function escapeFtsQuery(q: string): string {
return `"${q.trim().replace(/"/g, '""')}"`;
}
+
+/**
+ * LIKE 通配符转义. % _ 是 LIKE 语法字符, 用户 query 里出现时按字面匹配;
+ * 转义符用 '!' (避开反斜杠, 省去 SQL/TS 双重转义的坑)。
+ */
+function escapeLikePattern(q: string): string {
+ return q.replace(/[!%_]/g, (c) => `!${c}`);
+}
+
+/** LIKE 命中字段优先: title/description/body 中第一个包含 query 子串的字段 (ASCII 大小写不敏感) */
+function hitField(r: { title: string; description: string; body: string }, query: string): string | undefined {
+ const ql = query.trim().toLowerCase();
+ return [r.title, r.description, r.body].find((f) => f && f.toLowerCase().includes(ql));
+}
+
+function truncate(s: string, maxLen: number): string {
+ if (s.length <= maxLen) return s;
+ return `${s.slice(0, maxLen)}…`;
+}
diff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.ts
index eb2a49b59d..e1622b72ba 100644
--- a/packages/maker-core/src/memory/storage.ts
+++ b/packages/maker-core/src/memory/storage.ts
@@ -94,11 +94,43 @@ export function memoryScopeDirName(scopeKey: string): string {
return `ssh-${sanitizeWorkdir(hostSegment).slice(0, 24)}-${digest}`;
}
-/** filename = `<type>_<slug>.md` */
+/** filename = `<type>_<slug>.md`; slug 误带 `<type>_` 前缀会被拒绝 (见 validateNoTypePrefix) */
export function buildFilename(type: MemoryType, slug: string): string {
+ validateNoTypePrefix(type, slug);
return `${type}_${slug}${SHARD_EXT}`;
}
+/**
+ * 拒绝 slug 上误带的 `<type>_` 前缀 — memory_write 的调用方 (LLM) 常把 type
+ * 写进 name, 造成 `feedback_feedback_foo.md` 双前缀分片 (#1652 附带 bug, #205 审计亦命中)。
+ * **只报错不剥离**: 剥离会让存量双前缀分片在 update/append/consolidate 时定位错位 —
+ * parseFilename 把 `feedback_feedback_foo.md` 的 slug 解析为 `feedback_foo`, 剥离后
+ * 定位到 `feedback_foo.md`, 造成 not-found 或静默修改错误分片。报错让调用方传纯 slug,
+ * 存量双前缀分片由一次性改名/去重迁移清理 (另行处理)。
+ */
+function validateNoTypePrefix(type: MemoryType, slug: string): void {
+ if (slug === type) {
+ throw new MemoryError(
+ 'invalid-slug',
+ `slug 不能等于 type 名 "${type}", 请传纯 slug (如 "${type}-brief")`,
+ );
+ }
+ if (slug.startsWith(`${type}_`)) {
+ throw new MemoryError(
+ 'invalid-slug',
+ `slug "${slug}" 已带 type 前缀 "${type}_", 请传纯 slug (如 "${stripAllTypePrefixes(type, slug) || type + '-brief'}")`,
+ );
+ }
+}
+
+/** 剥掉 slug 上所有重复的 `<type>_` 前缀 — 错误信息示例必须本身可通过校验 */
+function stripAllTypePrefixes(type: MemoryType, slug: string): string {
+ let out = slug;
+ while (out.startsWith(`${type}_`)) {
+ out = out.slice(type.length + 1);
+ }
+ return out;
+}
/** 解析 filename 反推 type + slug, 不匹配返 null */
export function parseFilename(filename: string): { type: MemoryType; slug: string } | null {
if (!filename.endsWith(SHARD_EXT)) return null;