cortico-world-memory-core 0.24.0 → 0.26.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.26.1
4
+
5
+ **能看出「她到底写没写」了。**
6
+
7
+ - 写入回执带上 8 位编号:`已记下(fact · a1b2c3d4)`。改口仍是 `旧 → 新`。
8
+ - 写入 / 改口 / 元数据修改都记日志(只记 id、类型、字数、是否合并,**不记正文**):
9
+ ```text
10
+ [memory-core] 写入 { id: 'a1b2c3d4', kind: 'fact', chars: 32, merged: false }
11
+ ```
12
+ 工具报错也记一条,方便分清「没调」和「调了失败」。
13
+ - 工具描述里收窄了触发条件:对方**明确说**「记一下 / 记住 / 别忘了」时才必须调用,
14
+ 并按语义选 kind;编号只在对方问起时给,避免每句都念编号。
15
+ - 不改卡片内容、不自动写卡;测试 6 → 10 项。
16
+
17
+ ## 0.26.0
18
+
19
+ **换一种说法也能搜到了;检索比之前快,还能解释为什么命中。**
20
+
21
+ - **同义词 / 别名扩展**:内置 24 组生活常用词(快递=包裹/取件、猫=猫咪/小猫…),
22
+ 配置里还能自己补:`快递=包裹,取件; 奶茶=波霸,珍珠`。
23
+ 扩展词权重 0.55——能补漏,但压不过字面命中。
24
+ - **索引缓存**:BM25 倒排不再每轮重建。卡片库有版本号,写卡 / 改口 / 删除 / 导入后自动失效。
25
+ 卡片越多,收益越大。
26
+ - **命中解释**:召回行末尾会标 `〔快递+包裹〕`,一眼看出是字面对上还是同义词补进来的。
27
+ - **漏检记录**:搜不到时写一条到 `misses.jsonl`(只在本机,同一查询 10 分钟内只记一次),
28
+ 以后按真实缺口补同义词,不用拍脑袋。
29
+ - 同义词只影响召回,不改卡片内容;预激活也同样生效。
30
+ - 测试 `test-recall.ts` 8 项:同义词、缓存失效、改口后可搜、漏检落盘、自定义词表。
31
+
32
+ ## 0.25.0
33
+
34
+ **承诺到期终于会提醒了;记忆也能改了。**
35
+
36
+ - **承诺提醒重做(策略 A)**:
37
+ - 不再因为「对方最近没说话」就把整条丢掉——不写 `remindedAt`,等对方出现再说;
38
+ - 加了可打扰时段(默认 08:00–23:00)、两条之间最小间隔(120 分钟)、每天上限(3 条)、
39
+ 单条次数上限(6 次)、没回应时隔 180 分钟再提;
40
+ - 免打扰 / 睡眠期间不推,也不标记;
41
+ - 可选「对方不在也提醒」(默认关),打开后逾期超过 6 小时才允许破例一次;
42
+ - 体检页列出已到期的承诺:晚了多久、提醒过几次。
43
+ - **新增 `mcore_update`**:改权重 / 标签 / 截止时间 / 完成状态是原地改;
44
+ 改正文走「改口」——新卡接替、旧卡留档,不抹掉当时是怎么记的。已退休的卡不能改。
45
+ - **淡忘说清楚了**:`chillAfterDays` 是「沉到冷层」,不是删除;搜索仍可找到,
46
+ 事实 / 自我 / 未完成承诺不会沉。README 和设置项描述都写明。
47
+ - 测试:`test-remind.ts` 10 项、`test-update.ts` 6 项。
48
+
3
49
  ## 0.24.0
4
50
 
5
51
  **qq-official 的私聊能记了,但不会把「她自己说的话」记成对方说的。**
package/ENV_PROMPT.md CHANGED
@@ -1,13 +1,13 @@
1
1
  【记忆核心】
2
2
 
3
- 你只有这套记忆:`mcore_write` 写、`mcore_recall` 查。别提别的记忆系统,别问「记在哪」。
3
+ `mcore_write` 写、`mcore_update` 改、`mcore_recall` 查。别提别的记忆系统,别问「记在哪」。
4
4
 
5
5
  写的时候:
6
6
  - 用你记得的样子写,别写字段:「她点奶茶永远三分糖」比「用户偏好:低糖」像人。
7
7
  - `episode` 记你自己经历过的:打副本、发帖、被哄、路上看见什么,有画面有情绪就算,一天 3-5 条正常。
8
8
  - 技术操作(报错码、链接 id、文件路径)写 `note`,别当经历。
9
9
  - `self` 也装关系:他说话的习惯、什么语气让他舒服、你们之间的称呼和内部梗。
10
- - `promise` 没定时间先问;确实没有就写 `dueAt:"none"`。做完或改口传 `closes`(行首 8 位)。
10
+ - `promise` 没定时间先问;确实没有就写 `dueAt:"none"`。做完传 `done:true`,改口传 `closes`。
11
11
  - 一条一件事,写清谁、何时、怎么了;同一件事不写两遍。
12
12
  - `tags` 两个词:主题 + 对方可能换的说法(「小黑盒」「发帖」)。
13
13
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-memory-core",
3
- "version": "0.24.0",
3
+ "version": "0.26.1",
4
4
  "type": "module",
5
5
  "description": "四个工具写卡、查卡、改状态、排日程,改口不覆盖。每轮自动把 2 条相关旧记忆推到眼前,不用模型自己查;搜索分「对得上 / 可能沾边」两档。冷层收走三个月没想起的流水账,不删、可回暖。3D 星图一眼看完整个库。常驻约 1,000 token,本地不联网,MIT。\n\nQQ 交流群:745879632",
6
6
  "keywords": [
@@ -73,6 +73,6 @@
73
73
  "access": "public"
74
74
  },
75
75
  "scripts": {
76
- "test": "node --experimental-transform-types --no-warnings tools/test-store.ts && node --experimental-transform-types --no-warnings tools/test-world.ts && node --experimental-transform-types --no-warnings tools/test-capture.ts && node --experimental-transform-types --no-warnings tools/test-upgrade.ts && node --experimental-transform-types --no-warnings tools/test-urge.ts && node --experimental-transform-types --no-warnings tools/test-delete.ts && node --experimental-transform-types --no-warnings tools/test-site-auth.ts && node --experimental-transform-types --no-warnings tools/audit-webui.ts"
76
+ "test": "node --experimental-transform-types --no-warnings tools/test-store.ts && node --experimental-transform-types --no-warnings tools/test-world.ts && node --experimental-transform-types --no-warnings tools/test-capture.ts && node --experimental-transform-types --no-warnings tools/test-upgrade.ts && node --experimental-transform-types --no-warnings tools/test-urge.ts && node --experimental-transform-types --no-warnings tools/test-delete.ts && node --experimental-transform-types --no-warnings tools/test-remind.ts && node --experimental-transform-types --no-warnings tools/test-update.ts && node --experimental-transform-types --no-warnings tools/test-recall.ts && node --experimental-transform-types --no-warnings tools/test-site-auth.ts && node --experimental-transform-types --no-warnings tools/audit-webui.ts"
77
77
  }
78
78
  }
package/src/config.ts CHANGED
@@ -18,8 +18,24 @@ export interface MemoryCoreConfig {
18
18
  idleGateMin: number;
19
19
  /** 只有最近这么多小时内对方说过话才主动(0 = 不限制)。 */
20
20
  requireRecentUserHours: number;
21
- /** 承诺到期后,隔多少天可以再提醒一次(0 = 只提醒一次)。 */
22
- promiseRepeatDays: number; /** 免打扰开始(含)。 */
21
+ /** 旧字段:承诺隔几天再提。保留兼容,新逻辑改用 remindRepeatMin。 */
22
+ promiseRepeatDays: number;
23
+ /** 承诺提醒的可打扰时段(含开始,不含结束),跨夜也支持。 */
24
+ remindWindowStart: string;
25
+ remindWindowEnd: string;
26
+ /** 两条承诺提醒之间至少隔多久(分钟)。 */
27
+ remindMinGapMin: number;
28
+ /** 每天最多提醒几条(0 = 不限)。 */
29
+ remindDailyCap: number;
30
+ /** 同一条承诺没回应时,隔多久再提(分钟)。 */
31
+ remindRepeatMin: number;
32
+ /** 同一条承诺最多提醒几次,到顶就只留在体检页。 */
33
+ remindMaxTimes: number;
34
+ /** 对方最近没说话时是否也允许提醒;默认 false(等 TA 出现再说)。 */
35
+ remindWithoutUser: boolean;
36
+ /** 打开上一条时,超过多少小时未处理才允许在无人时提醒。 */
37
+ remindForceAfterHours: number;
38
+ /** 免打扰开始(含)。 */
23
39
  quietStart: string;
24
40
  /** 免打扰结束(不含)。 */
25
41
  quietEnd: string;
@@ -51,6 +67,8 @@ export interface MemoryCoreConfig {
51
67
  recallUseAging: boolean;
52
68
  /** 每轮主动想起几条(0 = 关)。预激活,不占工具调用。 */
53
69
  preactivateLines: number;
70
+ /** 额外的同义词组,`快递=包裹,取件`,用分号隔开。内置表之外再补。 */
71
+ synonyms: string;
54
72
  /** 多久没被想起就沉到冷层(天)。0 = 关闭自动分层。 */
55
73
  chillAfterDays: number;
56
74
  /** 每隔多少分钟把状态作为一条事件投递一次(0 = 不投递,最省)。 */
@@ -86,6 +104,14 @@ export const MEMORY_CORE_DEFAULTS: MemoryCoreConfig = {
86
104
  idleGateMin: 20,
87
105
  requireRecentUserHours: 5,
88
106
  promiseRepeatDays: 1,
107
+ remindWindowStart: '08:00',
108
+ remindWindowEnd: '23:00',
109
+ remindMinGapMin: 120,
110
+ remindDailyCap: 3,
111
+ remindRepeatMin: 180,
112
+ remindMaxTimes: 6,
113
+ remindWithoutUser: false,
114
+ remindForceAfterHours: 6,
89
115
  quietStart: '23:30',
90
116
  quietEnd: '08:00',
91
117
  sleepStart: '01:00',
@@ -104,6 +130,7 @@ export const MEMORY_CORE_DEFAULTS: MemoryCoreConfig = {
104
130
  recallMaxChars: 600,
105
131
  recallUseAging: true,
106
132
  preactivateLines: 2,
133
+ synonyms: '',
107
134
  /** 对方开口时,把「自我意识」插件独处时写下的那一句带进上下文。 */
108
135
  shareSelfThought: true,
109
136
  /** 把她独处时特别在意的那些(重要度 8 以上)写成 self 卡片,进星图。 */
@@ -158,7 +185,30 @@ const RAW_GROUP: ConfigGroup = {
158
185
  'worlds.memory-core.proactiveDailyCap': num('每天主动上限', '一次主动约 1-2 万 token(看上下文长度),3 次大概 5 万。0 = 不限。', 0, 12, '次'),
159
186
  'worlds.memory-core.idleGateMin': num('对方刚说话后的静默', '窗口内不主动,免得打断。', 0, 240, '分钟'),
160
187
  'worlds.memory-core.requireRecentUserHours': num('对方多久没说话就不主动', '超过这个时长就当没人在,主动会对着空房间说话、白花钱。0 = 不限制。', 0, 72, '小时'),
161
- 'worlds.memory-core.promiseRepeatDays': num('承诺隔几天再提一次', '到期还没做的承诺,隔这么多天再提一次,直到做完或退休。默认 1(每天最多一次);0 = 只提醒一次。', 0, 30, '天'),
188
+ 'worlds.memory-core.promiseRepeatDays': num('承诺隔几天再提一次(旧)', '旧字段,保留兼容;现在由下面「同一条没回应时隔多久再提」控制。', 0, 30, '天'),
189
+ 'worlds.memory-core.remindWindowStart': {
190
+ type: 'string',
191
+ title: '承诺提醒时段 · 开始',
192
+ description: '24 小时制 HH:MM。默认 08:00–23:00;起止相同等于不限制。夜里到期不会吵醒人,等进入时段再提。',
193
+ default: '08:00',
194
+ } as never,
195
+ 'worlds.memory-core.remindWindowEnd': {
196
+ type: 'string',
197
+ title: '承诺提醒时段 · 结束',
198
+ description: '默认 23:00。',
199
+ default: '23:00',
200
+ } as never,
201
+ 'worlds.memory-core.remindMinGapMin': num('两条承诺提醒至少隔多久', '防止几条同时到期时连着轰炸。默认 120 分钟。', 15, 1440, '分钟'),
202
+ 'worlds.memory-core.remindDailyCap': num('每天最多提醒几条承诺', '默认 3 条;超出的留到明天或体检页手动提。0 = 不限。', 0, 20, '条'),
203
+ 'worlds.memory-core.remindRepeatMin': num('同一条没回应时隔多久再提', '默认 180 分钟。对方没回、也没标完成,才会再提。', 30, 1440, '分钟'),
204
+ 'worlds.memory-core.remindMaxTimes': num('同一条最多提醒几次', '到顶就只留在体检页,不再主动提。默认 6 次(约三天)。', 1, 30, '次'),
205
+ 'worlds.memory-core.remindWithoutUser': {
206
+ type: 'boolean',
207
+ title: '对方不在时也提醒',
208
+ description: '默认关:只登记,等对方出现再说(策略 A)。打开后,超过下面那个小时数仍未处理的,会在时段内主动推一次(策略 B)。',
209
+ default: false,
210
+ },
211
+ 'worlds.memory-core.remindForceAfterHours': num('无人时最多等多久', '仅在上面开关打开时生效。默认 6 小时。', 1, 72, '小时'),
162
212
  'worlds.memory-core.quietStart': {
163
213
  type: 'string',
164
214
  title: '免打扰开始',
@@ -235,7 +285,7 @@ const RAW_GROUP: ConfigGroup = {
235
285
  description: '排序时参考「上次被想起的时间」:长期没被召回、权重又低的卡排到后面。关掉就退回只看关键词、标签和权重。',
236
286
  },
237
287
  'worlds.memory-core.preactivateLines': num('每轮主动想起几条', '按对方刚说的话自动带出几条旧记忆,不用模型自己去查。0 = 关。每条约 20 字,默认 2 条。', 0, 3, '条'),
238
- 'worlds.memory-core.chillAfterDays': num('多久没想起就沉到冷层', '超过这个天数没被用过的低权重「经历/临时」记忆会沉到冷层:不再主动想起、不占「最近」,但搜索仍能找到,可一键回暖。事实、自我和未完成的承诺不会被沉。0 = 关闭。', 0, 3650, '天'),
288
+ 'worlds.memory-core.chillAfterDays': num('多久没想起就沉到冷层', '超过这个天数没被用过的低权重「经历/临时」记忆会沉到冷层:不再主动想起、不占「最近」,但搜索仍能找到,可一键回暖。事实、自我和未完成的承诺不会被沉。**沉下去不是删除**:搜索仍找得到,只是在星图上退到冷层;要真删去卡片详情里删。0 = 关闭。', 0, 3650, '天'),
239
289
  'worlds.memory-core.contextEveryMin': num('状态投递间隔', '每隔这么多分钟把「我在做什么」推到上下文里。0 = 不推(默认,最省);推一次约 60 token,但每轮都在历史里。', 0, 240, '分钟'),
240
290
  'worlds.memory-core.nightlyConsolidate': {
241
291
  type: 'boolean',
@@ -301,6 +351,7 @@ const SETTINGS_ORDER = [
301
351
  'worlds.memory-core.siteEnabled',
302
352
  'worlds.memory-core.sitePort',
303
353
  'worlds.memory-core.preactivateLines',
354
+ 'worlds.memory-core.synonyms',
304
355
  'worlds.memory-core.shareSelfThought',
305
356
  'worlds.memory-core.absorbSelfThought',
306
357
  'worlds.memory-core.captureTurns',
@@ -328,6 +379,14 @@ const SETTINGS_ORDER = [
328
379
  'worlds.memory-core.idleGateMin',
329
380
  'worlds.memory-core.requireRecentUserHours',
330
381
  'worlds.memory-core.promiseRepeatDays',
382
+ 'worlds.memory-core.remindWindowStart',
383
+ 'worlds.memory-core.remindWindowEnd',
384
+ 'worlds.memory-core.remindMinGapMin',
385
+ 'worlds.memory-core.remindDailyCap',
386
+ 'worlds.memory-core.remindRepeatMin',
387
+ 'worlds.memory-core.remindMaxTimes',
388
+ 'worlds.memory-core.remindWithoutUser',
389
+ 'worlds.memory-core.remindForceAfterHours',
331
390
  'worlds.memory-core.quietStart',
332
391
  'worlds.memory-core.quietEnd',
333
392
  'worlds.memory-core.sleepStart',
package/src/definition.ts CHANGED
@@ -1,53 +1,54 @@
1
- /** World 定义:id/label/defaults/create + 自描述(给扩展页看,不进提示词)。 */
2
- import type { EventDescribe, ToolDescribe } from 'cortico/core/types.ts';
3
- import type { WorldDefinition } from 'cortico/world.ts';
4
- import { MEMORY_CORE_DEFAULTS, type MemoryCoreConfig } from './config.ts';
5
- import { TOOL_SPECS } from './tools.ts';
6
- import { MemoryCoreWorld } from './world.ts';
7
-
8
- const SUMMARIES: Record<string, string> = {
9
- mcore_write: '写一条记忆卡片(事实/自己/经历/承诺/临时)。',
10
- mcore_recall: '按内容或时间检索记忆,也能查最近 7 天的对话原文与未完成的承诺。',
11
- mcore_state: '读写你自己的精力、心情、正在做什么、在哪。',
12
- mcore_plan: '安排今天的日程,作为主动开口的由头。',
13
- };
14
-
15
- const TOOLS: ToolDescribe[] = TOOL_SPECS.map((spec) => ({
16
- name: spec.name,
17
- description: spec.description,
18
- parameters: spec.parameters,
19
- tags: spec.tags,
20
- summary: SUMMARIES[spec.name],
21
- }));
22
-
23
- const EVENTS: EventDescribe[] = [
24
- {
25
- type: 'mcore.wake',
26
- description: { zh: '主动开口的由头:从状态、未完成的承诺和日程里推出来的一小段理由,立即唤醒一轮。', en: 'A reason to speak first, derived from state, open promises and today\'s plan.' },
27
- trigger: 'flush',
28
- },
29
- {
30
- type: 'mcore.due',
31
- description: { zh: '答应过的事到点了,立即唤醒一轮提醒角色提一句。', en: 'A promise came due; wakes a turn so the character can bring it up.' },
32
- trigger: 'flush',
33
- },
34
- {
35
- type: 'mcore.context',
36
- description: { zh: '当前状态一行字,随下一批投递;默认关闭,避免每轮多带 token。', en: 'One line of current state, piggybacked. Off by default.' },
37
- trigger: 'piggyback',
38
- tags: ['snapshot'],
39
- },
40
- {
41
- type: 'mcore.nightly',
42
- description: { zh: '夜间整理:唤醒一轮,让它把今天写成几条 episode(默认关闭)。', en: 'Nightly consolidation turn (off by default).' },
43
- trigger: 'flush',
44
- },
45
- ];
46
-
47
- export const MEMORY_CORE_WORLD: WorldDefinition<MemoryCoreConfig> = {
48
- id: 'memory-core',
49
- label: '记忆核心',
50
- defaults: () => ({ ...MEMORY_CORE_DEFAULTS }),
51
- create: (ctx) => new MemoryCoreWorld(ctx),
52
- describe: { tools: TOOLS, events: EVENTS },
53
- };
1
+ /** World 定义:id/label/defaults/create + 自描述(给扩展页看,不进提示词)。 */
2
+ import type { EventDescribe, ToolDescribe } from 'cortico/core/types.ts';
3
+ import type { WorldDefinition } from 'cortico/world.ts';
4
+ import { MEMORY_CORE_DEFAULTS, type MemoryCoreConfig } from './config.ts';
5
+ import { TOOL_SPECS } from './tools.ts';
6
+ import { MemoryCoreWorld } from './world.ts';
7
+
8
+ const SUMMARIES: Record<string, string> = {
9
+ mcore_write: '写一条记忆卡片(事实/自己/经历/承诺/临时)。',
10
+ mcore_update: '改一条已有记忆:正文改动走改口留档,元数据原地改。',
11
+ mcore_recall: '按内容或时间检索记忆,也能查最近 7 天的对话原文与未完成的承诺。',
12
+ mcore_state: '读写你自己的精力、心情、正在做什么、在哪。',
13
+ mcore_plan: '安排今天的日程,作为主动开口的由头。',
14
+ };
15
+
16
+ const TOOLS: ToolDescribe[] = TOOL_SPECS.map((spec) => ({
17
+ name: spec.name,
18
+ description: spec.description,
19
+ parameters: spec.parameters,
20
+ tags: spec.tags,
21
+ summary: SUMMARIES[spec.name],
22
+ }));
23
+
24
+ const EVENTS: EventDescribe[] = [
25
+ {
26
+ type: 'mcore.wake',
27
+ description: { zh: '主动开口的由头:从状态、未完成的承诺和日程里推出来的一小段理由,立即唤醒一轮。', en: 'A reason to speak first, derived from state, open promises and today\'s plan.' },
28
+ trigger: 'flush',
29
+ },
30
+ {
31
+ type: 'mcore.due',
32
+ description: { zh: '答应过的事到点了,立即唤醒一轮提醒角色提一句。', en: 'A promise came due; wakes a turn so the character can bring it up.' },
33
+ trigger: 'flush',
34
+ },
35
+ {
36
+ type: 'mcore.context',
37
+ description: { zh: '当前状态一行字,随下一批投递;默认关闭,避免每轮多带 token。', en: 'One line of current state, piggybacked. Off by default.' },
38
+ trigger: 'piggyback',
39
+ tags: ['snapshot'],
40
+ },
41
+ {
42
+ type: 'mcore.nightly',
43
+ description: { zh: '夜间整理:唤醒一轮,让它把今天写成几条 episode(默认关闭)。', en: 'Nightly consolidation turn (off by default).' },
44
+ trigger: 'flush',
45
+ },
46
+ ];
47
+
48
+ export const MEMORY_CORE_WORLD: WorldDefinition<MemoryCoreConfig> = {
49
+ id: 'memory-core',
50
+ label: '记忆核心',
51
+ defaults: () => ({ ...MEMORY_CORE_DEFAULTS }),
52
+ create: (ctx) => new MemoryCoreWorld(ctx),
53
+ describe: { tools: TOOLS, events: EVENTS },
54
+ };
package/src/recall.ts CHANGED
@@ -62,7 +62,17 @@ const BM25_B = 0.75;
62
62
  * 给整个候选池建一次倒排:每张卡的词频、长度、以及每个词出现在几张卡里。
63
63
  * 卡片数量级是几十到几百,一次构建比「每个词去 includes 一遍」更省。
64
64
  */
65
- function buildIndex(pool: readonly Card[]) {
65
+ let cached: { key: string; index: ReturnType<typeof buildIndexRaw> } | null = null;
66
+
67
+ function buildIndex(pool: readonly Card[], cacheKey?: string) {
68
+ if (!cacheKey) return buildIndexRaw(pool);
69
+ if (cached && cached.key === cacheKey) return cached.index;
70
+ const index = buildIndexRaw(pool);
71
+ cached = { key: cacheKey, index };
72
+ return index;
73
+ }
74
+
75
+ function buildIndexRaw(pool: readonly Card[]) {
66
76
  const df = new Map<string, number>();
67
77
  const tf = new Map<string, Map<string, number>>();
68
78
  const len = new Map<string, number>();
@@ -80,7 +90,12 @@ function buildIndex(pool: readonly Card[]) {
80
90
  }
81
91
 
82
92
  /** 一张卡的 BM25 分。字面越贴、词越罕见、卡越短,分越高。 */
83
- function bm25(index: ReturnType<typeof buildIndex>, card: Card, tokens: readonly string[]): number {
93
+ function bm25(
94
+ index: ReturnType<typeof buildIndex>,
95
+ card: Card,
96
+ tokens: readonly string[],
97
+ weight?: Map<string, number>,
98
+ ): number {
84
99
  const local = index.tf.get(card.id);
85
100
  if (!local) return 0;
86
101
  const dl = index.len.get(card.id) ?? 0;
@@ -88,9 +103,10 @@ function bm25(index: ReturnType<typeof buildIndex>, card: Card, tokens: readonly
88
103
  for (const token of new Set(tokens)) {
89
104
  const f = local.get(token);
90
105
  if (!f) continue;
106
+ const w = weight?.get(token) ?? 1;
91
107
  const df = index.df.get(token) ?? 0;
92
108
  const idf = Math.log(1 + (index.n - df + 0.5) / (df + 0.5));
93
- sum += (idf * (f * (BM25_K1 + 1))) / (f + BM25_K1 * (1 - BM25_B + (BM25_B * dl) / index.avg));
109
+ sum += (w * idf * (f * (BM25_K1 + 1))) / (f + BM25_K1 * (1 - BM25_B + (BM25_B * dl) / index.avg));
94
110
  }
95
111
  return sum;
96
112
  }
@@ -113,6 +129,81 @@ function freshness(iso: string | undefined, now: number): number {
113
129
  return 1.1 * Math.exp(-days / 45);
114
130
  }
115
131
 
132
+ /** 内置的常用同义词组:只放「生活里真的会换说法」的,不放近义但语义可能相反的。 */
133
+ const DEFAULT_SYNONYMS: string[][] = [
134
+ ['快递', '包裹', '取件', '菜鸟', '驿站'],
135
+ ['猫', '猫咪', '小猫', '猫猫'],
136
+ ['狗', '狗狗', '小狗', '汪'],
137
+ ['吃饭', '用餐', '吃东西', '干饭'],
138
+ ['睡觉', '睡了', '晚安', '歇了'],
139
+ ['房租', '租金', '交租'],
140
+ ['生日', '寿辰', '过生'],
141
+ ['下雨', '雨天', '降雨'],
142
+ ['感冒', '着凉', '受凉'],
143
+ ['手机', '电话', '号码'],
144
+ ['工作', '上班', '公司', '单位'],
145
+ ['学校', '上课', '校园', '教室'],
146
+ ['工资', '薪水', '收入', '发薪'],
147
+ ['害怕', '怕', '恐惧', '吓'],
148
+ ['开心', '高兴', '快乐', '开怀'],
149
+ ['难过', '伤心', '低落', '心里不好受'],
150
+ ['累', '疲惫', '困', '乏'],
151
+ ['医院', '看病', '挂号', '诊所'],
152
+ ['搬家', '搬迁', '挪窝'],
153
+ ['考试', '测验', '测试', '期末'],
154
+ ['礼物', '礼品', '惊喜'],
155
+ ['道歉', '对不起', '抱歉', '不好意思'],
156
+ ['谢谢', '感谢', '多谢'],
157
+ ['早安', '早上好', '醒了'],
158
+ ];
159
+
160
+ /** 把配置里的 `快递=包裹,取件; 猫=猫咪,小猫` 解析成组;写错的段直接跳过。 */
161
+ export function parseSynonyms(raw: string): string[][] {
162
+ const out: string[][] = [];
163
+ for (const part of String(raw ?? '').split(/[;;\n]/)) {
164
+ const m = /^(.+?)[=::](.+)$/.exec(part.trim());
165
+ if (!m) continue;
166
+ const group = [m[1], ...m[2].split(/[,,、\s]+/)].map((x) => x.trim()).filter(Boolean);
167
+ if (group.length >= 2) out.push(group);
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /** token -> 同组其它词;同一组内的词互相映射。 */
173
+ function synonymMap(groups: readonly string[][]): Map<string, string[]> {
174
+ const map = new Map<string, string[]>();
175
+ for (const group of groups) {
176
+ for (const word of group) {
177
+ const others = group.filter((w) => w !== word);
178
+ const prev = map.get(word) ?? [];
179
+ map.set(word, [...new Set([...prev, ...others])]);
180
+ }
181
+ }
182
+ return map;
183
+ }
184
+
185
+ /** 扩展查询词:原词权重 1,同义词 0.55(能补漏,但压不过字面命中)。 */
186
+ export function expandTokens(tokens: readonly string[], rawExtra = ''): { tokens: string[]; weight: Map<string, number> } {
187
+ const groups = [...DEFAULT_SYNONYMS, ...parseSynonyms(rawExtra)];
188
+ const map = synonymMap(groups);
189
+ const weight = new Map<string, number>();
190
+ const out: string[] = [];
191
+ for (const t of tokens) {
192
+ if (!weight.has(t)) {
193
+ weight.set(t, 1);
194
+ out.push(t);
195
+ }
196
+ }
197
+ for (const t of tokens) {
198
+ for (const alt of map.get(t) ?? []) {
199
+ if (weight.has(alt)) continue;
200
+ weight.set(alt, 0.55);
201
+ out.push(alt);
202
+ }
203
+ }
204
+ return { tokens: out, weight };
205
+ }
206
+
116
207
  export interface RankOptions {
117
208
  query?: string;
118
209
  kind?: string;
@@ -142,6 +233,8 @@ export interface ScoredCard {
142
233
  tagHit: number;
143
234
  /** 命中了几个「实词二元组」——比分数更好解释「像不像」 */
144
235
  bigrams: number;
236
+ /** 实际对上的词(含同义词扩展),给召回行做解释。 */
237
+ matched: string[];
145
238
  /** strong = 真的对上了,weak = 只是靠权重/新鲜度浮上来的 */
146
239
  tier: 'strong' | 'weak';
147
240
  }
@@ -152,7 +245,8 @@ export interface ScoredCard {
152
245
  */
153
246
  export function rankCardsScored(cards: readonly Card[], opts: RankOptions): ScoredCard[] {
154
247
  const now = opts.now ?? Date.now();
155
- const queryTokens = tokenize(opts.query ?? '');
248
+ const baseTokens = tokenize(opts.query ?? '');
249
+ const { tokens: queryTokens, weight: tokenWeight } = expandTokens(baseTokens, opts.synonyms);
156
250
  let pool = cards.filter((c) => {
157
251
  if (opts.kind && c.kind !== opts.kind) return false;
158
252
  if (opts.days && opts.days > 0) {
@@ -173,6 +267,7 @@ export function rankCardsScored(cards: readonly Card[], opts: RankOptions): Scor
173
267
  lexical: 0,
174
268
  tagHit: 0,
175
269
  bigrams: 0,
270
+ matched: [],
176
271
  tier: 'strong' as const,
177
272
  }));
178
273
  }
@@ -202,11 +297,11 @@ export function rankCardsScored(cards: readonly Card[], opts: RankOptions): Scor
202
297
  for (const [tag, n] of df) if (n > cap) commonTag.add(tag);
203
298
  }
204
299
 
205
- const index = buildIndex(pool);
300
+ const index = buildIndex(pool, opts.cacheKey ? `${opts.cacheKey}|${opts.kind ?? ''}|${opts.days ?? ''}` : undefined);
206
301
  const scored = pool.map((card) => {
207
302
  // BM25 取代原来的「二元组命中数 / 长度」:词频和长度都归一过了,
208
303
  // 一句话里反复出现同一个词不会把分堆爆,长卡也不会因为词多而虚高。
209
- const lexical = bm25(index, card, queryTokens);
304
+ const lexical = bm25(index, card, queryTokens, tokenWeight);
210
305
  // 标签单独算一次:对方说「生日」时,打了 #生日 的卡要比正文里顺嘴提到的排得靠前。
211
306
  // 但泛标签会把所有卡都拉高,所以先剔掉「到处都是」的那些。
212
307
  const weakTags = card.tags.filter((t) => !commonTag.has(t));
@@ -226,10 +321,21 @@ export function rankCardsScored(cards: readonly Card[], opts: RankOptions): Scor
226
321
  // 双字以上的命中数:预激活用它挡单字噪音
227
322
  const hay = `${card.text} ${card.tags.join(' ')}`.toLowerCase();
228
323
  let bigrams = 0;
229
- for (const token of new Set(queryTokens)) {
324
+ // 只用原词计数:同义词补进来的不算「实词命中」,否则分档会虚高
325
+ for (const token of new Set(baseTokens)) {
230
326
  if (isContentToken(token) && !common.has(token) && hay.includes(token)) bigrams += 1;
231
327
  }
232
- return { card, score, lexical, tagHit, hit: lexical > 0 || tagHit > 0, bigrams };
328
+ // 同义词命中最多算一个实词:能进「对得上」,但不会被当成两个词
329
+ if (!bigrams) {
330
+ const synHit = [...queryTokens].some(
331
+ (t) => (tokenWeight.get(t) ?? 1) < 1 && isContentToken(t) && !common.has(t) && hay.includes(t),
332
+ );
333
+ if (synHit) bigrams = 1;
334
+ }
335
+ const matched = [...new Set([...baseTokens, ...queryTokens])]
336
+ .filter((t) => t.length >= 1 && hay.includes(t))
337
+ .slice(0, 3);
338
+ return { card, score, lexical, tagHit, hit: lexical > 0 || tagHit > 0, bigrams, matched };
233
339
  });
234
340
  scored.sort((a, b) => b.score - a.score);
235
341
  return scored