whale-memory-core 0.15.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +14 -0
  2. package/bin/whale-memory-mcp.mjs +276 -0
  3. package/demo.mjs +44 -33
  4. package/index.d.ts +19 -15
  5. package/index.js +21 -17
  6. package/lib/archive.d.ts +22 -22
  7. package/lib/archive.js +171 -135
  8. package/lib/as-of.d.ts +5 -5
  9. package/lib/as-of.js +32 -32
  10. package/lib/book.d.ts +4 -4
  11. package/lib/book.js +75 -75
  12. package/lib/chapter-events.d.ts +39 -39
  13. package/lib/chapter-events.js +89 -89
  14. package/lib/detail-recall.d.ts +15 -0
  15. package/lib/detail-recall.js +174 -0
  16. package/lib/event-log.d.ts +10 -10
  17. package/lib/event-log.js +61 -61
  18. package/lib/evidence-from-experience.d.ts +8 -8
  19. package/lib/evidence-from-experience.js +62 -62
  20. package/lib/evidence-policy.js +2 -2
  21. package/lib/fact-timeline-contract.d.ts +73 -0
  22. package/lib/fact-timeline-contract.js +226 -0
  23. package/lib/fact-timeline-query.d.ts +29 -0
  24. package/lib/fact-timeline-query.js +97 -0
  25. package/lib/file-lock.js +1 -1
  26. package/lib/later-events.d.ts +21 -21
  27. package/lib/later-events.js +80 -80
  28. package/lib/link-events.d.ts +15 -15
  29. package/lib/link-events.js +33 -33
  30. package/lib/person-card.d.ts +4 -0
  31. package/lib/person-card.js +179 -0
  32. package/lib/query-match.js +55 -0
  33. package/lib/recall-events.d.ts +24 -24
  34. package/lib/recall-events.js +97 -97
  35. package/lib/recap.d.ts +23 -23
  36. package/lib/recap.js +79 -79
  37. package/lib/relative-window.d.ts +4 -0
  38. package/lib/relative-window.js +123 -0
  39. package/lib/seal-events.d.ts +25 -25
  40. package/lib/seal-events.js +82 -82
  41. package/lib/self-experience.d.ts +180 -175
  42. package/lib/self-experience.js +624 -560
  43. package/lib/self-memory.js +70 -68
  44. package/lib/self-prompt.js +8 -4
  45. package/lib/self-settings.js +2 -2
  46. package/lib/time-sense.d.ts +6 -0
  47. package/lib/time-sense.js +89 -0
  48. package/lib/unfinished-events.d.ts +26 -26
  49. package/lib/unfinished-events.js +105 -105
  50. package/lib/unsaid.d.ts +28 -28
  51. package/lib/unsaid.js +105 -105
  52. package/lib/waking.d.ts +1 -1
  53. package/lib/waking.js +99 -92
  54. package/package.json +139 -113
@@ -1,81 +1,81 @@
1
- // 改主意是事件:只追加,不改 then,也不重写经历文件
2
- // 一行一个 { id, at, day, thought, reason?, feeling? }
3
- // feeling 是她「后来再想起时」的感觉;当时的感觉在 then.feeling 里,永远不动
4
- import fs from 'node:fs'
5
- import path from 'node:path'
6
- import { withFileLock } from './file-lock.js'
7
- import { before } from './as-of.js'
8
-
9
- const FILE = 'later-events.jsonl'
10
-
11
- export function eventsFile(memDir) {
12
- return path.join(memDir, FILE)
13
- }
14
-
15
- export function append(memDir, { id, thought, reason = '', feeling = [] } = {}, opts = {}) {
16
- if (!String(id || '').trim()) throw new Error('id 不能为空')
17
- if (!String(thought || '').trim()) throw new Error('thought 不能为空')
18
- const now = new Date()
19
- const row = {
20
- id: String(id),
21
- at: now.toISOString(),
22
- day: now.toLocaleDateString('sv-SE'),
23
- thought: String(thought),
24
- reason: String(reason || '')
25
- }
26
- if (Array.isArray(feeling) && feeling.length) row.feeling = feeling.map(String)
27
-
28
- fs.mkdirSync(memDir, { recursive: true })
29
- return withFileLock(eventsFile(memDir) + '.lock', () => {
30
- const file = eventsFile(memDir)
31
- let prefix = ''
32
- try {
33
- const st = fs.statSync(file)
34
- if (st.size) {
35
- const fd = fs.openSync(file, 'r')
36
- const buf = Buffer.alloc(1)
37
- fs.readSync(fd, buf, 0, 1, st.size - 1)
38
- fs.closeSync(fd)
39
- if (buf[0] !== 10) prefix = '\n'
40
- }
41
- } catch { }
42
- fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
43
- return row
44
- }, opts)
45
- }
46
-
47
- export function readAll(memDir) {
48
- let raw = ''
49
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
50
- const rows = []
51
- let bad = 0
52
- for (const line of raw.split('\n')) {
53
- if (!line.trim()) continue
54
- try {
55
- const r = JSON.parse(line)
56
- if (r && r.id && r.thought) rows.push(r)
57
- else bad += 1
58
- } catch { bad += 1 }
59
- }
60
- return { rows, bad }
61
- }
62
-
63
- // until:只要这一刻之前(含)写下的后记,「翻回那天的自己」用
64
- export function groupByExp(memDir, { until = null } = {}) {
65
- const { rows } = readAll(memDir)
66
- const map = new Map()
67
- for (const r of rows) {
68
- if (!before(r, until)) continue
69
- const list = map.get(r.id) || []
70
- list.push(r)
71
- map.set(r.id, list)
72
- }
73
- return map
74
- }
75
-
76
- export function list(memDir, { id = '', limit = 20 } = {}) {
77
- const { rows } = readAll(memDir)
78
- return rows.filter((r) => !id || r.id === id).slice(-limit).reverse()
79
- }
80
-
1
+ // 改主意是事件:只追加,不改 then,也不重写经历文件
2
+ // 一行一个 { id, at, day, thought, reason?, feeling? }
3
+ // feeling 是她「后来再想起时」的感觉;当时的感觉在 then.feeling 里,永远不动
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
7
+ import { before } from './as-of.js'
8
+
9
+ const FILE = 'later-events.jsonl'
10
+
11
+ export function eventsFile(memDir) {
12
+ return path.join(memDir, FILE)
13
+ }
14
+
15
+ export function append(memDir, { id, thought, reason = '', feeling = [] } = {}, opts = {}) {
16
+ if (!String(id || '').trim()) throw new Error('id cannot be empty(id 不能为空)')
17
+ if (!String(thought || '').trim()) throw new Error('thought cannot be empty(thought 不能为空)')
18
+ const now = new Date()
19
+ const row = {
20
+ id: String(id),
21
+ at: now.toISOString(),
22
+ day: now.toLocaleDateString('sv-SE'),
23
+ thought: String(thought),
24
+ reason: String(reason || '')
25
+ }
26
+ if (Array.isArray(feeling) && feeling.length) row.feeling = feeling.map(String)
27
+
28
+ fs.mkdirSync(memDir, { recursive: true })
29
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
30
+ const file = eventsFile(memDir)
31
+ let prefix = ''
32
+ try {
33
+ const st = fs.statSync(file)
34
+ if (st.size) {
35
+ const fd = fs.openSync(file, 'r')
36
+ const buf = Buffer.alloc(1)
37
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
38
+ fs.closeSync(fd)
39
+ if (buf[0] !== 10) prefix = '\n'
40
+ }
41
+ } catch { }
42
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
43
+ return row
44
+ }, opts)
45
+ }
46
+
47
+ export function readAll(memDir) {
48
+ let raw = ''
49
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
50
+ const rows = []
51
+ let bad = 0
52
+ for (const line of raw.split('\n')) {
53
+ if (!line.trim()) continue
54
+ try {
55
+ const r = JSON.parse(line)
56
+ if (r && r.id && r.thought) rows.push(r)
57
+ else bad += 1
58
+ } catch { bad += 1 }
59
+ }
60
+ return { rows, bad }
61
+ }
62
+
63
+ // until:只要这一刻之前(含)写下的后记,「翻回那天的自己」用
64
+ export function groupByExp(memDir, { until = null } = {}) {
65
+ const { rows } = readAll(memDir)
66
+ const map = new Map()
67
+ for (const r of rows) {
68
+ if (!before(r, until)) continue
69
+ const list = map.get(r.id) || []
70
+ list.push(r)
71
+ map.set(r.id, list)
72
+ }
73
+ return map
74
+ }
75
+
76
+ export function list(memDir, { id = '', limit = 20 } = {}) {
77
+ const { rows } = readAll(memDir)
78
+ return rows.filter((r) => !id || r.id === id).slice(-limit).reverse()
79
+ }
80
+
81
81
  export const internals = { FILE }
@@ -1,15 +1,15 @@
1
- export interface LinkEvent {
2
- from: string
3
- to: string
4
- at: string
5
- day: string
6
- reason: string
7
- }
8
-
9
- export function eventsFile(memDir: string): string
10
- export function readAll(memDir: string): { rows: LinkEvent[]; bad: number }
11
- /** 同一对(不分方向)只连一次;重复是 noop。自己连自己会抛错 */
12
- export function link(memDir: string, opts: { from: string; to: string; reason: string }, lockOpts?: Record<string, unknown>): { row: LinkEvent | null; noop: boolean }
13
- /** 每条经历连着哪些(两头都有);until 用于翻回那天 */
14
- export function linksByExp(memDir: string, opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
15
- export const internals: { FILE: string }
1
+ export interface LinkEvent {
2
+ from: string
3
+ to: string
4
+ at: string
5
+ day: string
6
+ reason: string
7
+ }
8
+
9
+ export function eventsFile(memDir: string): string
10
+ export function readAll(memDir: string): { rows: LinkEvent[]; bad: number }
11
+ /** 同一对(不分方向)只连一次;重复是 noop。自己连自己会抛错 */
12
+ export function link(memDir: string, opts: { from: string; to: string; reason: string }, lockOpts?: Record<string, unknown>): { row: LinkEvent | null; noop: boolean }
13
+ /** 每条经历连着哪些(两头都有);until 用于翻回那天 */
14
+ export function linksByExp(memDir: string, opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
15
+ export const internals: { FILE: string }
@@ -1,33 +1,33 @@
1
- // 事后联想:她后来才发现两件事有关,亲手把它们连起来
2
- // 一行一个 { from, to, at, day, reason },只追加。不按相似度自动连;不写理由不连
3
- // 和出处(then.refs)的区别:出处是写下这条时就知道的依据;联想是写下之后才发现的关系
4
- import { createLog, stamp } from './event-log.js'
5
- import { before } from './as-of.js'
6
-
7
- const log = createLog('link-events.jsonl', { valid: (r) => Boolean(r.from && r.to && r.reason) })
8
- export const eventsFile = log.eventsFile
9
- export const readAll = log.readAll
10
- export const internals = { FILE: log.FILE }
11
-
12
- const pair = (a, b) => [String(a), String(b)].sort().join('|')
13
-
14
- // 同一对经历(不分方向)只连一次;重复提交是 noop
15
- export function link(memDir, { from, to, reason }, opts = {}) {
16
- if (!from || !to) throw new Error('需要两条经历的 id')
17
- if (String(from) === String(to)) throw new Error('不能把一件事和它自己连起来。')
18
- return log.decide(memDir, (rows) => rows.some((r) => pair(r.from, r.to) === pair(from, to))
19
- ? null
20
- : { from: String(from), to: String(to), ...stamp(), reason: String(reason) }, opts)
21
- }
22
-
23
- // 每条经历连着哪些:不分方向,两头都能看到;until 用于翻回那天
24
- export function linksByExp(memDir, { until = null } = {}) {
25
- const map = new Map()
26
- const push = (id, other, r) => map.set(id, [...(map.get(id) || []), { other, reason: r.reason, at: r.at, day: r.day }])
27
- for (const r of readAll(memDir).rows) {
28
- if (!before(r, until)) continue
29
- push(r.from, r.to, r)
30
- push(r.to, r.from, r)
31
- }
32
- return map
33
- }
1
+ // 事后联想:她后来才发现两件事有关,亲手把它们连起来
2
+ // 一行一个 { from, to, at, day, reason },只追加。不按相似度自动连;不写理由不连
3
+ // 和出处(then.refs)的区别:出处是写下这条时就知道的依据;联想是写下之后才发现的关系
4
+ import { createLog, stamp } from './event-log.js'
5
+ import { before } from './as-of.js'
6
+
7
+ const log = createLog('link-events.jsonl', { valid: (r) => Boolean(r.from && r.to && r.reason) })
8
+ export const eventsFile = log.eventsFile
9
+ export const readAll = log.readAll
10
+ export const internals = { FILE: log.FILE }
11
+
12
+ const pair = (a, b) => [String(a), String(b)].sort().join('|')
13
+
14
+ // 同一对经历(不分方向)只连一次;重复提交是 noop
15
+ export function link(memDir, { from, to, reason }, opts = {}) {
16
+ if (!from || !to) throw new Error('Need the ids of two experiences(需要两条经历的 id)')
17
+ if (String(from) === String(to)) throw new Error('Cannot link an experience to itself.(不能把一件事和它自己连起来。)')
18
+ return log.decide(memDir, (rows) => rows.some((r) => pair(r.from, r.to) === pair(from, to))
19
+ ? null
20
+ : { from: String(from), to: String(to), ...stamp(), reason: String(reason) }, opts)
21
+ }
22
+
23
+ // 每条经历连着哪些:不分方向,两头都能看到;until 用于翻回那天
24
+ export function linksByExp(memDir, { until = null } = {}) {
25
+ const map = new Map()
26
+ const push = (id, other, r) => map.set(id, [...(map.get(id) || []), { other, reason: r.reason, at: r.at, day: r.day }])
27
+ for (const r of readAll(memDir).rows) {
28
+ if (!before(r, until)) continue
29
+ push(r.from, r.to, r)
30
+ push(r.to, r.from, r)
31
+ }
32
+ return map
33
+ }
@@ -0,0 +1,4 @@
1
+ /** 把一个人的档案压成一行提示词;信息不足返回空串 */
2
+ export function renderPersonCard(card: Record<string, unknown>, options?: { now?: number; minEvidence?: number }): string
3
+ /** 挑当前说话人那张卡;默认不按"话最多"退回别人 */
4
+ export function pickPersonCard(cards: Array<Record<string, unknown>>, speaker?: { personId?: string; chatKey?: string }, options?: { fallback?: boolean }): Record<string, unknown> | null
@@ -0,0 +1,179 @@
1
+ /**
2
+ * 人物卡:把「这个人是谁、你们聊过什么、最近一次」压成一行,供提示词使用。
3
+ *
4
+ * 为什么需要:她的记忆是「事件」和「片段」,没有「人」这一层。
5
+ * 问她"某某是谁",她能翻到提到过这个名字的片段,但拼不出这个人是谁。
6
+ *
7
+ * 纯函数,不读文件、不调模型;数据由调用方传进来。
8
+ *
9
+ * 两轮审查后收紧的地方:
10
+ * 1. 群聊不退回别人;精确匹配要带会话,避免同一个人跨群取错卡
11
+ * 2. 关系阶段要有证据支撑(证据条数 < 3 不写)
12
+ * 3. 名字清洗只针对真乱码,不剥合法英文前缀(Tom小明 保持完整)
13
+ * 4. 名字和例句里的分隔符要净化:否则昵称写成「X:关系:挚友」就能伪造卡片
14
+ * 5. 时间戳兼容秒级;「刚认识」只用于当天
15
+ */
16
+
17
+ /** 全角/半角里能伪造卡片结构的符号,从名字里去掉。 */
18
+ const BIDI = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
19
+ const NAME_BREAKERS = /[::,,。.;;、||「」『』“”"'\n\r\t\u2028\u2029]/g;
20
+
21
+ import { humanTime } from './time-sense.js';
22
+
23
+ /** 名字里的控制字符、零宽字符一律清掉。 */
24
+ function cleanName(value) {
25
+ return String(value || '')
26
+ .replace(/[\u0000-\u001f\u007f\u0080-\u009f\u200b-\u200f\ufeff]/g, '')
27
+ .replace(BIDI, '')
28
+ .replace(/^[^\p{L}\p{N}]+/u, '') // 开头的符号去掉
29
+ .replace(NAME_BREAKERS, '')
30
+ .replace(/\s+/g, ' ')
31
+ .trim();
32
+ }
33
+
34
+ /**
35
+ * 只处理真乱码:名字开头连续 2 个以上 Latin-1 补充字符、且后面跟着汉字时,
36
+ * 把这段剥掉(如「ÿfÌÿ地形雨…」→「地形雨…」)。
37
+ * 合法的「Tom小明」「Ame酱」不含这类字符,不会被剥。
38
+ */
39
+ function stripMojibakePrefix(name) {
40
+ const cjkAt = name.search(/[\u3400-\u9fff]/);
41
+ if (cjkAt <= 0) return name;
42
+ const prefix = name.slice(0, cjkAt);
43
+ if (prefix.length > 8) return name;
44
+ const latin1 = [...prefix].filter((c) => c >= '\u00c0' && c <= '\u00ff').length;
45
+ // 只有"前面夹了两个以上 Latin-1 补充字符"才当乱码;Tom小明、Ame酱 这类合法名不受影响
46
+ return latin1 >= 2 ? name.slice(cjkAt) : name;
47
+ }
48
+
49
+ /** 「傻鱼(¬_¬)」→「傻鱼」:去掉结尾的括号注释。 */
50
+ function baseName(value) {
51
+ const first = String(value || '').split(' / ')[0];
52
+ const cleaned = cleanName(stripMojibakePrefix(cleanName(first)));
53
+ return cleaned.replace(/[((][^()()]{0,8}[))]$/, '').trim();
54
+ }
55
+
56
+ /** 名字是否还能用:有字,且没有控制/替换字符。 */
57
+ function nameIsUsable(name) {
58
+ if (!name) return false;
59
+ if (/[\u0000-\u001f\u007f\ufffd]/.test(name)) return false;
60
+ return /[\p{L}\p{N}]/u.test(name);
61
+ }
62
+
63
+ /** 说过多少条 → 一个词。数字对"她记得这个人"没有帮助,只会挤掉具体的事。 */
64
+ function familiarityWord(count) {
65
+ const n = Number(count) || 0;
66
+ if (n >= 800) return '老熟人了';
67
+ if (n >= 200) return '聊得挺多';
68
+ if (n >= 50) return '聊过一阵';
69
+ if (n >= 10) return '说过几次话';
70
+ return '刚打过照面';
71
+ }
72
+
73
+ /** 秒级时间戳换算成毫秒,避免渲染成 1970。 */
74
+ function toMs(ts) {
75
+ const n = Number(ts);
76
+ if (!Number.isFinite(n) || n <= 0) return 0;
77
+ return n >= 1e11 ? n : n * 1000;
78
+ }
79
+
80
+ function fmtTime(ts) {
81
+ const n = toMs(ts);
82
+ if (!n) return '';
83
+ const d = new Date(n);
84
+ const pad = (x) => String(x).padStart(2, '0');
85
+ return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
86
+ }
87
+
88
+ function daysBetween(from, to) {
89
+ const a = toMs(from);
90
+ const b = toMs(to);
91
+ if (!a || !b) return null;
92
+ return Math.round((b - a) / 86400000);
93
+ }
94
+
95
+ /** 例句里不能出现会截断外层的引号;同时去掉换行。 */
96
+ function cleanSample(value) {
97
+ return String(value || '')
98
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
99
+ .replace(BIDI, '')
100
+ .replace(/\u2028|\u2029/g, ' ')
101
+ .replace(/[「」『』]/g, '') // 只去会截断外层的引号,正文标点保留
102
+ .replace(/\s+/g, ' ')
103
+ .trim();
104
+ }
105
+
106
+ /**
107
+ * 渲染一张人物卡。
108
+ * @param {object} card {名字, 消息条数, 首次出现(ts), 最后说话(ts), 常聊话题[], 关系阶段, 证据条数, 最近一句}
109
+ * @param {object} [options] {now, minEvidence}
110
+ * @returns {string} 一行文本;信息不足时返回空串
111
+ */
112
+ export function renderPersonCard(card, { now = Date.now(), minEvidence = 3 } = {}) {
113
+ if (!card) return '';
114
+ const name = baseName(card.名字);
115
+ if (!nameIsUsable(name)) return '';
116
+ const parts = [];
117
+
118
+ const since = daysBetween(card.首次出现, now);
119
+ if (since != null && since >= 0) parts.push(since <= 0 ? '刚认识' : `认识 ${since} 天`);
120
+ const count = Number(card.消息条数) || 0;
121
+ if (count > 0) parts.push(familiarityWord(count));
122
+ const last = humanTime(card.最后说话, { now });
123
+ if (last) parts.push(`最近 ${last}`);
124
+
125
+ const stage = String(card.关系阶段 || '').trim().replace(BIDI, '').replace(NAME_BREAKERS, '');
126
+ const evidence = Number(card.证据条数) || 0;
127
+ if (stage && stage !== '初识' && evidence >= minEvidence) parts.push(`关系:${stage}`);
128
+
129
+ // 话题只留中文的:英文串要么是用户名、要么是工具名,对"这人是谁"帮助不大。
130
+ const topics = (Array.isArray(card.常聊话题) ? card.常聊话题 : [])
131
+ .map((t) => String(t).replace(/\(\d+\)$/, '').trim().replace(BIDI, '').replace(NAME_BREAKERS, ''))
132
+ .filter((t) => /[\u3400-\u9fff]{2}/.test(t))
133
+ .slice(0, 3);
134
+ if (topics.length) parts.push(`常聊:${topics.join('、')}`);
135
+
136
+ // 引用/转发里的话可能是别人说的,归到她认识的人头上会张冠李戴:这种直接不用。
137
+ const rawSample = cleanSample(card.最近一句);
138
+ let sample = /^\[(?:引用|合并转发|转发|回复)/.test(rawSample) ? '' : rawSample;
139
+ sample = sample.slice(0, 28);
140
+ const tail = sample && sample !== '[图片]' && sample !== '[表情]' ? `。最近说过「${sample}」` : '';
141
+
142
+ if (!parts.length) return '';
143
+ return `你认识 ${name}:${parts.join(',')}${tail}。`;
144
+ }
145
+
146
+ /**
147
+ * 从一堆人里挑「当前说话的人」那张卡。
148
+ * - 同一 personId 可能有多个群的卡:先匹配 personId + 当前会话;私聊允许退回该人的任意一张
149
+ * - 默认**不按"话最多"退回别人**:群聊里那等于把别人的资料塞给在场的人
150
+ * @param {Array} cards 人物卡数组
151
+ * @param {{personId?: string, chatKey?: string}} speaker
152
+ * @param {{fallback?: boolean}} options fallback=true 才允许按话最多退回
153
+ */
154
+ export function pickPersonCard(cards, speaker = {}, { fallback = false } = {}) {
155
+ const list = Array.isArray(cards) ? cards : [];
156
+ const id = String(speaker.personId || '').trim();
157
+ const chat = String(speaker.chatKey || '').trim();
158
+ if (id) {
159
+ const samePerson = list.filter((c) => String(c.personId || '') === id);
160
+ if (!chat) {
161
+ // 没有会话键就无法确认是哪张卡;只有唯一一张时才用
162
+ return samePerson.length === 1 ? samePerson[0] : null;
163
+ }
164
+ const exact = samePerson.find((c) => String(c.chatKey || '') === chat);
165
+ if (exact) return exact;
166
+ if (/^(?:private)[_:-]/i.test(chat)) {
167
+ const anyChat = list.find((c) => String(c.personId || '') === id);
168
+ if (anyChat) return anyChat;
169
+ }
170
+ }
171
+ if (!fallback || id) return null;
172
+ if (chat) {
173
+ const inChat = list
174
+ .filter((c) => String(c.chatKey || '') === chat)
175
+ .sort((a, b) => (Number(b.消息条数) || 0) - (Number(a.消息条数) || 0));
176
+ if (inChat.length) return inChat[0];
177
+ }
178
+ return null;
179
+ }
@@ -36,6 +36,61 @@ export function queryTerms(q) {
36
36
  return { cleaned, terms }
37
37
  }
38
38
 
39
+ // 只起语法作用的单字:算「查询里有多少意思被这段记忆接住了」时不计入
40
+ const STOP_CHARS = new Set([...'的了吗呢吧啊呀么着过在里那这个些次段事就也都还又很把被给跟和与及或是有我你他她它们嘛啦哦呃'])
41
+ // 聊天里的垫话:只是在问"那件事",本身不带内容。只在算覆盖率时跳过,不改 STOP(旧口径和 loose 不受影响)
42
+ const FILLER = new Set([
43
+ '怎么样', '怎样', '上次', '之前', '最近', '说说', '讲讲', '聊聊', '说过', '提过', '讲过', '记不记得', '还记得',
44
+ '跟我', '说的', '讲的', '提到', '那件', '那次', '那段', '那天', '那个时候',
45
+ 'remember', 'recall', 'tell', 'me', 'do', 'does', 'know', 'talk', 'about'
46
+ ])
47
+ // 停用词里只有这些(时间、代词、虚词)整个跳过;「买了 / 说了 / 去了」这类带动作的,动作那个字要算
48
+ const SKIP_WORDS = new Set([...[...STOP].filter((w) => !['买了', '说了', '去了', '来了', '做了', '看到', '了什'].includes(w)), ...FILLER])
49
+ // 任意长度的停用词都要能跳过(以前只看两字,「是不是」「有没有」「记不记得」从来没跳过)
50
+ const SKIP_LENS = [...new Set([...SKIP_WORDS].filter((w) => !/[a-z]/.test(w)).map((w) => w.length))].sort((a, b) => b - a)
51
+ // 单独出现的字在长记忆里很容易碰巧有:记忆越长,单字给的分越少
52
+ const ISOLATED_LEN = 60
53
+ // 可以跟在内容字右边、算作"连着"的助词和语气词
54
+ const SUFFIX = new Set([...'了的吗呢吧啊呀么着过'])
55
+
56
+ // 查询里要被接住的单位:拉丁字母按整词;其余按单字,并记下它左右两个两字组(用来判断是不是连着出现)
57
+ export function contentUnits(q) {
58
+ const lower = String(q || '').toLowerCase()
59
+ const units = []
60
+ for (const w of lower.match(/[a-z]+/g) || []) if (w.length >= 2 && !STOP.has(w) && !FILLER.has(w)) units.push({ u: w, pairs: [] })
61
+ for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
62
+ const skip = new Set()
63
+ for (let i = 0; i < run.length; i++) for (const L of SKIP_LENS) if (i + L <= run.length && SKIP_WORDS.has(run.slice(i, i + L))) for (let k = i; k < i + L; k++) skip.add(k)
64
+ const content = (i) => i >= 0 && i < run.length && !skip.has(i) && !STOP_CHARS.has(run[i])
65
+ for (let i = 0; i < run.length; i++) {
66
+ if (!content(i)) continue
67
+ // 两字组:左边只认内容字(「他想」的"他"不算,长记忆里随便一个"他想"都能接住);
68
+ // 右边还认紧跟着的语气、助词(「凉了」「好的」:形容词、动词后面常跟它们)
69
+ const right = content(i + 1) || (i + 1 < run.length && SUFFIX.has(run[i + 1]))
70
+ units.push({ u: run[i], pairs: [content(i - 1) ? run.slice(i - 1, i + 1) : '', right ? run.slice(i, i + 2) : ''].filter(Boolean) })
71
+ }
72
+ }
73
+ return units
74
+ }
75
+
76
+ // 覆盖率:查询里的意思有几成在这段记忆里找得到(0~1)
77
+ // 和左右任一个内容字连着出现在记忆里 → 1 分;只是单独出现 → 0.5 × min(1, 60 / 记忆长度) 分;没有 → 0
78
+ // 「灯塔里的猫」:灯塔连着在,猫不在 → 2/3,不算想起来;「守灯人修透镜那段」→ 5.5/6
79
+ export function coverage(units, text) {
80
+ if (!units.length) return 0
81
+ const t = normalizeText(text)
82
+ let got = 0
83
+ for (const x of units) {
84
+ if (!x.pairs.length) { if (t.includes(x.u)) got += 1; continue }
85
+ if (x.pairs.some((p) => t.includes(p))) got += 1
86
+ else if (t.includes(x.u)) got += 0.5 * Math.min(1, ISOLATED_LEN / Math.max(1, t.length))
87
+ }
88
+ return got / units.length
89
+ }
90
+
91
+ // strict 的门槛:至少对上一个两字词(有个落脚点),并且查询的意思至少有这么多被接住
92
+ export const MIN_COVER = 0.7
93
+
39
94
  // mode='strict':长查询(≥8 字)要求 ≥minRatio 的词命中,宁可不召回也不硬凑
40
95
  // mode='loose':只要求 minOverlap 个词命中
41
96
  export function requiredOverlap({ cleaned, terms }, { mode = 'strict', minOverlap = 1, minRatio = 0.6 } = {}) {
@@ -1,25 +1,25 @@
1
- export interface RecallEvent {
2
- id: string
3
- at: string
4
- query: string
5
- chatKey: string
6
- backfilled?: boolean
7
- }
8
-
9
- export function eventsFile(memDir: string): string
10
-
11
- export function append(memDir: string, event: {
12
- id: string
13
- query?: string
14
- chatKey?: string
15
- backfilled?: boolean
16
- }, opts?: { timeoutMs?: number }): RecallEvent
17
-
18
- export function readAll(memDir: string): { rows: RecallEvent[]; bad: number }
19
-
20
- /** until:只数这一刻(毫秒时间戳)之前(含)的想起 */
21
- export function countByExp(memDir: string, opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
22
-
23
- export function list(memDir: string, opts?: { id?: string; limit?: number }): RecallEvent[]
24
-
1
+ export interface RecallEvent {
2
+ id: string
3
+ at: string
4
+ query: string
5
+ chatKey: string
6
+ backfilled?: boolean
7
+ }
8
+
9
+ export function eventsFile(memDir: string): string
10
+
11
+ export function append(memDir: string, event: {
12
+ id: string
13
+ query?: string
14
+ chatKey?: string
15
+ backfilled?: boolean
16
+ }, opts?: { timeoutMs?: number }): RecallEvent
17
+
18
+ export function readAll(memDir: string): { rows: RecallEvent[]; bad: number }
19
+
20
+ /** until:只数这一刻(毫秒时间戳)之前(含)的想起 */
21
+ export function countByExp(memDir: string, opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
22
+
23
+ export function list(memDir: string, opts?: { id?: string; limit?: number }): RecallEvent[]
24
+
25
25
  export const internals: { FILE: string }