whale-memory-core 0.21.0 → 0.21.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/lib/fact-store.js CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
+ import { withFileLock, writeFileAtomic } from './file-lock.js';
11
12
 
12
13
  const FILE = 'fact-cards.jsonl';
13
14
 
@@ -15,6 +16,23 @@ function fileOf(dir) {
15
16
  return path.join(String(dir || ''), FILE);
16
17
  }
17
18
 
19
+ // 上次写到一半崩掉留下的临时文件:拿到锁以后清掉(锁保证没有别的写者在用)。
20
+ function cleanupTemps(file) {
21
+ const dir = path.dirname(file);
22
+ const prefix = path.basename(file) + '.tmp-';
23
+ let names = [];
24
+ try { names = fs.readdirSync(dir); } catch { return; }
25
+ for (const name of names) {
26
+ if (!name.startsWith(prefix)) continue;
27
+ try { fs.rmSync(path.join(dir, name), { force: true }); } catch { /* 下一轮再清 */ }
28
+ }
29
+ }
30
+
31
+ function serializeFacts(rows) {
32
+ const lines = rows.map((f) => JSON.stringify(f)).join('\n');
33
+ return lines ? `${lines}\n` : '';
34
+ }
35
+
18
36
  /** 读全部事实卡;文件不存在返回空数组。 */
19
37
  export function loadFacts(dir) {
20
38
  const file = fileOf(dir);
@@ -32,25 +50,49 @@ export function loadFacts(dir) {
32
50
  }
33
51
 
34
52
  /**
35
- * 合并写入:同 kind + value 只留一条,更新时间和次数,不重复堆积。
53
+ * 合并写入:同 kind + value + 主体 只留一条,更新时间和次数,不重复堆积。
54
+ * 主体必须进合并键:Alice 喜欢咖啡和 Bob 喜欢咖啡是两条事实,不能合成一个人。
55
+ *
56
+ * 并发安全:整段「重读 → 合并 → 写回」都在 file-lock 里,写回走临时文件 + fsync + rename;
57
+ * 并发写不会互相覆盖,写到一半崩掉也不会把正式文件写成半截。
36
58
  * @returns {{added:number, updated:number}}
37
59
  */
38
60
  export function saveFacts(dir, facts) {
39
- const existing = loadFacts(dir);
40
- const byKey = new Map(existing.map((f) => [`${f.kind}|${f.value}`, f]));
61
+ const dirPath = String(dir || '');
62
+ const incoming = Array.isArray(facts) ? facts : [];
63
+ if (!dirPath) {
64
+ const merged = mergeFacts([], incoming);
65
+ return { added: merged.added, updated: merged.updated };
66
+ }
67
+ fs.mkdirSync(dirPath, { recursive: true });
68
+ const file = fileOf(dirPath);
69
+ return withFileLock(file + '.lock', () => {
70
+ const merged = mergeFacts(loadFacts(dirPath), incoming);
71
+ cleanupTemps(file);
72
+ writeFileAtomic(file, serializeFacts(merged.rows));
73
+ return { added: merged.added, updated: merged.updated };
74
+ });
75
+ }
76
+
77
+ function mergeFacts(existing, facts) {
78
+ const keyOf = (f) => `${f.kind}|${String(f.subject || '').trim()}|${f.value}`;
79
+ const byKey = new Map(existing.map((f) => [keyOf(f), f]));
41
80
  let added = 0;
42
81
  let updated = 0;
43
82
  for (const fact of Array.isArray(facts) ? facts : []) {
44
83
  if (!fact?.kind || !fact?.value) continue;
45
- const key = `${fact.kind}|${fact.value}`;
84
+ const subject = String(fact.subject || '').trim();
85
+ const key = `${fact.kind}|${subject}|${fact.value}`;
86
+ const chatKey = String(fact.chatKey || '');
46
87
  const cur = byKey.get(key);
47
88
  if (!cur) {
48
89
  byKey.set(key, {
49
90
  kind: fact.kind,
50
91
  value: fact.value,
51
- subject: String(fact.subject || ''),
92
+ subject,
52
93
  quote: String(fact.quote || '').slice(0, 80),
53
- chatKey: String(fact.chatKey || ''),
94
+ chatKey,
95
+ sources: chatKey ? [chatKey] : [],
54
96
  ts: Number(fact.ts) || Date.now(),
55
97
  count: 1
56
98
  });
@@ -58,21 +100,20 @@ export function saveFacts(dir, facts) {
58
100
  continue;
59
101
  }
60
102
  cur.count = (Number(cur.count) || 1) + 1;
103
+ // 会话来源单独留一份:同一主体在不同会话里说过,不能只记住最后一次。
104
+ if (chatKey) {
105
+ const sources = Array.isArray(cur.sources) ? cur.sources : (cur.chatKey ? [cur.chatKey] : []);
106
+ if (!sources.includes(chatKey)) sources.push(chatKey);
107
+ cur.sources = sources;
108
+ cur.chatKey = chatKey;
109
+ }
61
110
  if ((Number(fact.ts) || 0) >= (Number(cur.ts) || 0)) {
62
111
  cur.ts = Number(fact.ts) || cur.ts;
63
112
  cur.quote = String(fact.quote || cur.quote || '').slice(0, 80);
64
- cur.chatKey = String(fact.chatKey || cur.chatKey || '');
65
- cur.subject = String(fact.subject || cur.subject || '');
66
113
  }
67
114
  updated += 1;
68
115
  }
69
- const dirPath = String(dir || '');
70
- if (dirPath) {
71
- fs.mkdirSync(dirPath, { recursive: true });
72
- const lines = [...byKey.values()].map((f) => JSON.stringify(f)).join('\n');
73
- fs.writeFileSync(fileOf(dir), lines ? `${lines}\n` : '', 'utf8');
74
- }
75
- return { added, updated };
116
+ return { rows: [...byKey.values()], added, updated };
76
117
  }
77
118
 
78
119
  /** 这个值能不能安全地说出来:短、是名词短语、不含动词和否定。 */
@@ -1 +1,4 @@
1
- export function withFileLock<T>(lockPath: string, fn: () => T, opts?: { timeoutMs?: number }): T
1
+ export function withFileLock<T>(lockPath: string, fn: () => T, opts?: { timeoutMs?: number }): T
2
+
3
+ /** 原子写文件(临时文件 + fsync + rename):写成功返回目标路径,失败抛错且不留临时文件 */
4
+ export function writeFileAtomic(file: string, data: string | Uint8Array): string
package/lib/file-lock.js CHANGED
@@ -1,27 +1,165 @@
1
1
  // 跨进程文件锁:mkdir 独占 + 忙等重试;Windows 上并发 mkdir/rm 会短暂 EPERM/ENOENT,按“忙”处理
2
+ //
3
+ // 抢锁规则(2026-11 修):
4
+ // - 锁目录里写 owner.json(pid + hostname + token + 心跳时间),抢锁时先看持有者是否还活着。
5
+ // - 同一台机器:用 pid 存活校验(process.kill(pid, 0))。持有者还活着就绝不抢,哪怕锁很旧。
6
+ // - 别的机器/认不出持有者:用心跳判断;心跳过期才回收。心跳只在拿到锁时写一次,
7
+ // 所以跨机共享目录上的长任务仍可能被误判——跨机写入应在更高层串行化。
8
+ // - 回收先原子 rename 成 tombstone,只有一个竞争者能 rename 成功,避免两个写入者同时进入。
9
+ // - 释放时核对 token,只删自己的锁,不误删别人刚抢到的锁。
2
10
  import fs from 'node:fs'
3
11
  import path from 'node:path'
12
+ import os from 'node:os'
13
+ import crypto from 'node:crypto'
4
14
 
5
15
  const BUSY = new Set(['EEXIST', 'EPERM', 'ENOENT', 'EBUSY', 'EACCES'])
16
+ const OWNER_FILE = 'owner.json'
17
+ const DEFAULT_TIMEOUT_MS = 3000
18
+ const DEFAULT_STALE_MS = 10000
19
+ const DEFAULT_POLL_MS = 20
20
+ const LOCKED_MESSAGE = 'The file is locked by another process; try again shortly.(文件被另一个进程锁着,稍后再试。)'
6
21
 
7
- export function withFileLock(lockPath, fn, { timeoutMs = 3000 } = {}) {
22
+ // 临时文件 + fsync + rename 原子替换。中途崩了只会留下 <file>.tmp-*,正式文件保持旧内容。
23
+ export function writeFileAtomic(file, data) {
24
+ const target = String(file)
25
+ const dir = path.dirname(target)
26
+ const tmp = target + '.tmp-' + process.pid + '-' + crypto.randomUUID()
27
+ let fd
28
+ try {
29
+ fd = fs.openSync(tmp, 'w')
30
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8')
31
+ let offset = 0
32
+ while (offset < buf.length) offset += fs.writeSync(fd, buf, offset, buf.length - offset)
33
+ fs.fsyncSync(fd)
34
+ fs.closeSync(fd)
35
+ fd = undefined
36
+ renameWithRetry(tmp, target)
37
+ } catch (error) {
38
+ if (fd !== undefined) { try { fs.closeSync(fd) } catch { } }
39
+ try { fs.rmSync(tmp, { force: true }) } catch { }
40
+ throw error
41
+ }
42
+ // 目录项也落盘(POSIX 上才有意义;Windows 打开目录会失败,静默跳过)
43
+ try {
44
+ const dirFd = fs.openSync(dir, 'r')
45
+ try { fs.fsyncSync(dirFd) } finally { fs.closeSync(dirFd) }
46
+ } catch { }
47
+ return target
48
+ }
49
+
50
+ function renameWithRetry(from, to) {
51
+ for (let attempt = 0; ; attempt += 1) {
52
+ try { return fs.renameSync(from, to) } catch (error) {
53
+ if (attempt >= 9 || !BUSY.has(error.code)) throw error
54
+ sleep(10)
55
+ }
56
+ }
57
+ }
58
+
59
+ export function withFileLock(lockPath, fn, { timeoutMs = DEFAULT_TIMEOUT_MS, staleMs = DEFAULT_STALE_MS, pollMs = DEFAULT_POLL_MS } = {}) {
60
+ const waitMs = Number.isFinite(timeoutMs) && timeoutMs >= 0 ? timeoutMs : DEFAULT_TIMEOUT_MS
61
+ const staleAfter = Number.isFinite(staleMs) && staleMs >= 0 ? staleMs : DEFAULT_STALE_MS
62
+ const interval = Number.isFinite(pollMs) && pollMs > 0 ? pollMs : DEFAULT_POLL_MS
63
+ const token = crypto.randomUUID()
64
+ const owner = {
65
+ pid: process.pid,
66
+ hostname: os.hostname(),
67
+ token,
68
+ acquiredAt: Date.now(),
69
+ heartbeatAt: Date.now()
70
+ }
8
71
  const start = Date.now()
9
72
  for (;;) {
73
+ if (acquire(lockPath, owner)) break
74
+ // 过时锁只在持有者已退出(或跨机心跳过期)时回收;活着就继续等。
75
+ tryReclaimIfStale(lockPath, staleAfter)
76
+ if (Date.now() - start >= waitMs) throw new Error(LOCKED_MESSAGE)
77
+ sleep(interval)
78
+ }
79
+ try { return fn() } finally { release(lockPath, token) }
80
+ }
81
+
82
+ function acquire(lockPath, owner) {
83
+ try {
84
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true })
85
+ fs.mkdirSync(lockPath)
86
+ } catch (error) {
87
+ if (error.code === 'EEXIST') return false
88
+ if (BUSY.has(error.code)) return false
89
+ throw error
90
+ }
91
+ try {
92
+ fs.writeFileSync(path.join(lockPath, OWNER_FILE), JSON.stringify(owner), 'utf8')
93
+ } catch (error) {
94
+ try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch { }
95
+ throw error
96
+ }
97
+ return true
98
+ }
99
+
100
+ function readOwner(lockPath) {
101
+ try {
102
+ const row = JSON.parse(fs.readFileSync(path.join(lockPath, OWNER_FILE), 'utf8'))
103
+ return row && typeof row === 'object' ? row : null
104
+ } catch { return null }
105
+ }
106
+
107
+ // 'alive' | 'dead' | 'unknown'(别的机器、字段缺失、旧版锁目录)
108
+ function ownerStatus(owner) {
109
+ const pid = Number(owner?.pid)
110
+ const hostname = typeof owner?.hostname === 'string' ? owner.hostname : ''
111
+ const sameHost = hostname === '' ? pid === process.pid : hostname === os.hostname()
112
+ if (sameHost) {
113
+ if (!Number.isInteger(pid) || pid <= 0) return 'unknown'
114
+ if (pid === process.pid) return 'alive'
10
115
  try {
11
- fs.mkdirSync(path.dirname(lockPath), { recursive: true })
12
- fs.mkdirSync(lockPath)
13
- break
14
- } catch (e) {
15
- if (!BUSY.has(e.code)) throw e
16
- try {
17
- const st = fs.statSync(lockPath)
18
- if (Date.now() - st.mtimeMs > 10000) { fs.rmSync(lockPath, { recursive: true, force: true }); continue }
19
- } catch { /* 锁刚被释放 */ }
20
- if (Date.now() - start > timeoutMs) throw new Error('The file is locked by another process; try again shortly.(文件被另一个进程锁着,稍后再试。)')
21
- sleep(20)
116
+ process.kill(pid, 0)
117
+ return 'alive'
118
+ } catch (error) {
119
+ if (error.code === 'EPERM') return 'alive' // 系统进程/权限不足:当成活着,宁可等
120
+ if (error.code === 'ESRCH') return 'dead'
121
+ return 'unknown'
22
122
  }
23
123
  }
24
- try { return fn() } finally { try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch { } }
124
+ return 'unknown'
125
+ }
126
+
127
+ // 返回 true 表示这轮尝试过回收(或锁已经不在),调用方睡一下再重试
128
+ function tryReclaimIfStale(lockPath, staleMs) {
129
+ let stats
130
+ try { stats = fs.statSync(lockPath) } catch { return true }
131
+ const now = Date.now()
132
+ const age = now - stats.mtimeMs
133
+ const owner = readOwner(lockPath)
134
+ if (owner) {
135
+ const status = ownerStatus(owner)
136
+ if (status === 'alive') return false
137
+ if (status === 'dead') return takeOver(lockPath)
138
+ const beat = Number(owner.heartbeatAt) || Number(owner.acquiredAt) || stats.mtimeMs
139
+ if (now - beat <= staleMs) return false
140
+ return takeOver(lockPath)
141
+ }
142
+ if (age <= staleMs) return false
143
+ return takeOver(lockPath)
144
+ }
145
+
146
+ function takeOver(lockPath) {
147
+ const tombstone = lockPath + '.stale-' + process.pid + '-' + crypto.randomUUID()
148
+ try {
149
+ fs.renameSync(lockPath, tombstone)
150
+ } catch {
151
+ // 另一个竞争者先回收了(ENOENT),或 Windows 上暂时不让改名;下一轮再看
152
+ return false
153
+ }
154
+ try { fs.rmSync(tombstone, { recursive: true, force: true }) } catch { }
155
+ return true
156
+ }
157
+
158
+ function release(lockPath, token) {
159
+ const owner = readOwner(lockPath)
160
+ // 锁已经被别人回收/替换时不能删:只释放自己拿到的这一把。
161
+ if (!owner || owner.token !== token) return
162
+ try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch { }
25
163
  }
26
164
 
27
165
  // 阻塞式小睡,不空转 CPU;Node 主线程允许 Atomics.wait
package/lib/injection.js CHANGED
@@ -44,13 +44,19 @@ export function surface(memDir, { chatKey = '', text = '', seen = {}, now = Date
44
44
  const last = Number(seen[hit.id] || 0)
45
45
  if (last && now - last < DAY) return { block: '', reason: 'recently-shown' }
46
46
 
47
+ let confirmed = false
47
48
  return {
48
49
  block: renderTwoPart(hit),
49
50
  id: hit.id,
50
51
  reason: 'ok',
51
52
  confirm() {
52
- markRecalled(memDir, hit.id)
53
+ // 同一次展示只记一次:宿主重试或重复确认不会把想起次数加成 2。
54
+ if (confirmed) return true
55
+ // 落盘失败要如实返回 false,并且不占掉 seen,下次还能再试。
56
+ const wrote = markRecalled(memDir, hit.id)
57
+ if (!wrote) return false
53
58
  seen[hit.id] = now
59
+ confirmed = true
54
60
  return true
55
61
  }
56
62
  }
@@ -1,5 +1,10 @@
1
1
  // 查询匹配:self-experience 与 self-memory 共用同一套口径,防编造的门槛只在这里定义
2
- // 中文等按相邻两字切;拉丁字母按整词切(不切成字母对,否则 "the" 会命中一切);统一小写
2
+ // 中文等按相邻两字切;拉丁字母按整词切、也按整词匹配(不切成字母对,否则 "the" 会命中一切;
3
+ // 也不能拿子串去命中,否则 "art" 会命中 "started"、"he" 会命中 "the");统一小写
4
+ //
5
+ // ⚠️ 适用边界:这套口径用来在「她自己的经历」里找工作——候选集是她自己的记忆,先验很强。
6
+ // 别拿它当跨窗口/跨房间的检索门槛:那边的候选集大得多、先验弱得多,1 个内容词命中
7
+ // 就从「勉强能召回」变成「噪声发生器」。实测 15 轮真实样本 0 条有用,见 docs/pitfalls.md 第 10 条。
3
8
 
4
9
  // 高频但不携带信息的词:不参与重叠计算,避免「今天/什么/我的」把不相关的东西拉进来
5
10
  const STOP = new Set([
@@ -19,18 +24,27 @@ export function normalizeText(s) {
19
24
  return String(s || '').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')
20
25
  }
21
26
 
27
+ // 拉丁词按整词比:normalizeText 会把空格抹掉,抹完再 includes 就成了子串比。
28
+ // 这里单独把原文切成小写整词,只用来和拉丁词对词
29
+ export function wordTokens(s) {
30
+ return new Set(String(s || '').toLowerCase().match(/[a-z]+/g) || [])
31
+ }
32
+
33
+ const LATIN_TERM = /^[a-z]+$/
34
+
22
35
  // 查询 → 待匹配的词:拉丁字母连写成词,其余(汉字、数字等)按相邻两字切
23
36
  export function queryTerms(q) {
24
37
  const lower = String(q || '').toLowerCase()
25
38
  const cleaned = normalizeText(lower)
26
39
  const terms = new Set()
27
40
  for (const w of lower.match(/[a-z]+/g) || []) {
28
- if (w.length >= 2 && !STOP.has(w)) terms.add(w)
41
+ if (w.length >= 2 && !STOP.has(w) && !FILLER.has(w)) terms.add(w)
29
42
  }
30
43
  for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
31
44
  for (let i = 0; i + 2 <= run.length; i++) {
32
45
  const g = run.slice(i, i + 2)
33
- if (!STOP.has(g)) terms.add(g)
46
+ // 垫话本身不携带内容:「说说 / 上次 / 之前」这类两字组单独命中,不该把一段记忆叫出来
47
+ if (!STOP.has(g) && !FILLER.has(g)) terms.add(g)
34
48
  }
35
49
  }
36
50
  return { cleaned, terms }
@@ -38,7 +52,7 @@ export function queryTerms(q) {
38
52
 
39
53
  // 只起语法作用的单字:算「查询里有多少意思被这段记忆接住了」时不计入
40
54
  const STOP_CHARS = new Set([...'的了吗呢吧啊呀么着过在里那这个些次段事就也都还又很把被给跟和与及或是有我你他她它们嘛啦哦呃'])
41
- // 聊天里的垫话:只是在问"那件事",本身不带内容。只在算覆盖率时跳过,不改 STOP(旧口径和 loose 不受影响)
55
+ // 聊天里的垫话:只是在问"那件事",本身不带内容。只在算覆盖率时跳过,不改 STOP(旧口径不受影响)
42
56
  const FILLER = new Set([
43
57
  '怎么样', '怎样', '上次', '之前', '最近', '说说', '讲讲', '聊聊', '说过', '提过', '讲过', '记不记得', '还记得',
44
58
  '跟我', '说的', '讲的', '提到', '那件', '那次', '那段', '那天', '那个时候',
@@ -52,12 +66,20 @@ const SKIP_LENS = [...new Set([...SKIP_WORDS].filter((w) => !/[a-z]/.test(w)).ma
52
66
  const ISOLATED_LEN = 60
53
67
  // 可以跟在内容字右边、算作"连着"的助词和语气词
54
68
  const SUFFIX = new Set([...'了的吗呢吧啊呀么着过'])
69
+ // 没有相邻内容字可以作证的单字(通常是「的 / 了」后面那个名词,如「守灯人的猫」的「猫」):
70
+ // 它没出现却按 KEY_WEIGHT 份算——那句话里单独的那个名词不在,就不是把这件事想起来了。
71
+ // 否则「守灯人的猫」会以 3/4 的覆盖率把「守灯人」那条叫出来,而那条根本没有猫。
72
+ const KEY_WEIGHT = 1.5
73
+ // 询问、数量用字:它们是"在问什么",不是这条经历欠她的内容,缺了不算前提错(「交给谁」不该被拦下)
74
+ const NOT_KEY = new Set([...'谁哪几什么多少一二三四五六七八九十百千万半两个只件种样点咋啥'])
55
75
 
56
76
  // 查询里要被接住的单位:拉丁字母按整词;其余按单字,并记下它左右两个两字组(用来判断是不是连着出现)
57
77
  export function contentUnits(q) {
58
78
  const lower = String(q || '').toLowerCase()
59
79
  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: [] })
80
+ for (const w of lower.match(/[a-z]+/g) || []) {
81
+ if (w.length >= 2 && !STOP.has(w) && !FILLER.has(w)) units.push({ u: w, word: true, pairs: [] })
82
+ }
61
83
  for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
62
84
  const skip = new Set()
63
85
  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)
@@ -74,36 +96,63 @@ export function contentUnits(q) {
74
96
  }
75
97
 
76
98
  // 覆盖率:查询里的意思有几成在这段记忆里找得到(0~1)
77
- // 和左右任一个内容字连着出现在记忆里 → 1 分;只是单独出现 → 0.5 × min(1, 60 / 记忆长度) 分;没有 → 0
78
- // 「灯塔里的猫」:灯塔连着在,猫不在 → 2/3,不算想起来;「守灯人修透镜那段」→ 5.5/6
99
+ // 和左右任一个内容字连着出现 → 1 分
100
+ // 只是单独出现 → 0.5 × min(1, 60 / 记忆长度) 分(孤立单字没有邻字作证,不能白送满分)
101
+ // 没有 → 0 分
102
+ // 拉丁词只有整词出现才得分(art 不命中 started,he 不命中 the)
103
+ // 孤立单字没出现时按 KEY_WEIGHT 份算:关键那个单独的名词不在,就不是这件事
79
104
  export function coverage(units, text) {
80
105
  if (!units.length) return 0
81
106
  const t = normalizeText(text)
107
+ const words = wordTokens(text)
108
+ // 查询只剩一个内容单元时(「夜里」:里是虚词不算,只剩「夜」),它出现就是全部意思都在;
109
+ // 不给这个豁免的话,「夜里」会被自己的孤立半份压到 0.5,连它自己那条都招不回来
110
+ const whole = units.length === 1
82
111
  let got = 0
112
+ let total = 0
83
113
  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))
114
+ if (x.word) {
115
+ total += 1
116
+ if (words.has(x.u)) got += 1
117
+ continue
118
+ }
119
+ const isolated = !x.pairs.length
120
+ if (!isolated) {
121
+ total += 1
122
+ if (x.pairs.some((p) => t.includes(p))) got += 1
123
+ else if (t.includes(x.u)) got += 0.5 * Math.min(1, ISOLATED_LEN / Math.max(1, t.length))
124
+ continue
125
+ }
126
+ const here = t.includes(x.u)
127
+ if (here) got += whole ? 1 : 0.5 * Math.min(1, ISOLATED_LEN / Math.max(1, t.length))
128
+ // 出现了只说半份;没出现又是个实在的名词,就多算半份,把覆盖率压向门槛以下
129
+ total += !here && !NOT_KEY.has(x.u) ? KEY_WEIGHT : 1
87
130
  }
88
- return got / units.length
131
+ return total ? got / total : 0
89
132
  }
90
133
 
91
134
  // strict 的门槛:至少对上一个两字词(有个落脚点),并且查询的意思至少有这么多被接住
92
135
  export const MIN_COVER = 0.7
136
+ // loose 也有最低比例,只是比 strict 低:一段长问句里只碰上一个词,不该把不相干的东西叫出来
137
+ export const LOOSE_MIN_RATIO = 0.34
93
138
 
94
139
  // mode='strict':长查询(≥8 字)要求 ≥minRatio 的词命中,宁可不召回也不硬凑
95
- // mode='loose':只要求 minOverlap 个词命中
140
+ // mode='loose':比 strict 松,但比例门槛还在(否则一个垫话两字组就能召回一整段)
96
141
  export function requiredOverlap({ cleaned, terms }, { mode = 'strict', minOverlap = 1, minRatio = 0.6 } = {}) {
97
- return (mode !== 'loose' && cleaned.length >= 8)
98
- ? Math.max(minOverlap, Math.ceil(terms.size * minRatio))
99
- : minOverlap
142
+ if (String(cleaned || '').length < 8) return minOverlap
143
+ const ratio = mode === 'loose' ? Math.min(minRatio, LOOSE_MIN_RATIO) : minRatio
144
+ return Math.max(minOverlap, Math.ceil(terms.size * ratio))
100
145
  }
101
146
 
102
- // 文本里命中了哪些词(文本先做同样的归一化)
147
+ // 文本里命中了哪些词(拉丁词按整词比;中文两字组按归一化后的文本比)
103
148
  export function matchedTerms(terms, text) {
104
149
  const t = normalizeText(text)
105
150
  const out = new Set()
106
151
  if (!t) return out
107
- for (const g of terms) if (t.includes(g)) out.add(g)
152
+ const words = wordTokens(text)
153
+ for (const g of terms) {
154
+ if (LATIN_TERM.test(g)) { if (words.has(g)) out.add(g); continue }
155
+ if (t.includes(g)) out.add(g)
156
+ }
108
157
  return out
109
- }
158
+ }
@@ -2,6 +2,10 @@
2
2
  export function baseChatKey(chatKey: string): string
3
3
  /** 这个键是不是人设级 */
4
4
  export function isPersonaScoped(chatKey: string): boolean
5
+ /** 这个键是不是群 / 公共场景(group_1、qq:group:1、private:group_123、群聊……) */
6
+ export function isGroupScope(chatKey: string): boolean
7
+ /** 这个键是不是认得出来的一对一私聊;带群标记或认不出的一律 false(宁可不给) */
8
+ export function isPrivateScope(chatKey: string): boolean
5
9
  /** 一次查询应覆盖的键:人设级 = [人设键, 会话键];会话级 = [会话键](不反向并入,避免串台) */
6
10
  export function scopeKeysFor(chatKey: string): string[]
7
11
  /** 记录是否落在查询范围内 */
package/lib/scope-key.js CHANGED
@@ -6,6 +6,9 @@
6
6
  * - 人设级查询 = 人设级记录 + 同会话的会话级记录
7
7
  * - 会话级查询 = 只认会话级记录(不反向并入人设记录,避免把某人的记忆串给所有人)
8
8
  *
9
+ * 另外,这里也放"这个会话是不是一对一的私聊"这一条判断:
10
+ * 醒来块、注入、未说出口抽屉、跨窗口可见性都问同一个实现,别让每个出口各写一份正则。
11
+ *
9
12
  * 纯函数,宿主无关。
10
13
  */
11
14
 
@@ -21,6 +24,37 @@ export function isPersonaScoped(chatKey) {
21
24
  return PERSONA_SUFFIX.test(String(chatKey || '').trim());
22
25
  }
23
26
 
27
+ // 一对一会话的写法:private_10001 / private:10001 / local_owner / local:owner。
28
+ // 分隔符后面必须有东西:光一个 `private:` 认不出是谁,不给。
29
+ const PRIVATE_PREFIX = /^(?:private|local)[:_](.+)$/i;
30
+
31
+ // 群 / 公共场景的标记。前后都要是边界(键首、分隔符、数字、结尾),
32
+ // 所以 `private_groupie_42` 这种账号名不算群;`group_1`、`group:1`、`qq:group:1`、
33
+ // `private:group_123`、`local_group_1` 都算。中文"群"当整体标记看。
34
+ const GROUP_MARK = /(?:^|[:_\-#.@])(?:groupchat|groupdm|group|guild|channel|chatroom|conference)(?=$|[:_\-#.@0-9])/i;
35
+ const GROUP_CJK = /群/;
36
+
37
+ /** 这个键是不是群 / 公共场景(group_1、qq:group:1、private:group_123、群聊……)。 */
38
+ export function isGroupScope(chatKey) {
39
+ const base = baseChatKey(chatKey);
40
+ if (!base) return false;
41
+ return GROUP_MARK.test(base) || GROUP_CJK.test(base);
42
+ }
43
+
44
+ /**
45
+ * 这个键是不是认得出来的一对一私聊。
46
+ *
47
+ * 只认 `private_` / `private:` / `local_` / `local:` 开头;带群标记的(`private:group_123`、
48
+ * `local_group_1`……)和认不出来的写法(`group_1`、`qq:group:1`、空键)一律 false。
49
+ * 这是"宁可不给"的方向:醒来块、注入、抽屉都靠它,错放行一次就是把私话带进群里。
50
+ */
51
+ export function isPrivateScope(chatKey) {
52
+ const base = baseChatKey(chatKey);
53
+ if (!base) return false;
54
+ if (!PRIVATE_PREFIX.test(base)) return false;
55
+ return !isGroupScope(base);
56
+ }
57
+
24
58
  /**
25
59
  * 一次查询应该覆盖哪些键。
26
60
  * @param {string} chatKey 当前会话键
@@ -20,6 +20,6 @@ export function eventsFile(memDir: string): string
20
20
  /** 同一把锁里重读 → 判断 → 追加;已是这个状态就 noop,不写第二条 */
21
21
  export function decide(memDir: string, opts: { id: string; action: SealAction; note?: string }, lockOpts?: Record<string, unknown>): { row: SealEvent | null; noop: boolean }
22
22
  export function readAll(memDir: string): { rows: SealEvent[]; bad: number }
23
- /** 现在(或截至 until)仍封存着的经历 */
24
- export function sealedByExp(memDir: string, opts?: { until?: number | null }): Map<string, SealedInfo>
23
+ /** 现在(或截至 until)仍封存着的经历;strict 时坏行会抛 SEAL_EVENTS_CORRUPT */
24
+ export function sealedByExp(memDir: string, opts?: { until?: number | null; strict?: boolean }): Map<string, SealedInfo>
25
25
  export const internals: { FILE: string }
@@ -42,17 +42,30 @@ export function decide(memDir, { id, action, note = '' } = {}, opts = {}) {
42
42
  if (!ACTIONS.has(action)) throw new Error('action must be seal / unseal(action 只能是 seal / unseal)')
43
43
  fs.mkdirSync(memDir, { recursive: true })
44
44
  return withFileLock(eventsFile(memDir) + '.lock', () => {
45
- const rows = readAll(memDir).rows.filter((r) => r.id === String(id))
45
+ const all = readAll(memDir)
46
+ const rows = all.rows.filter((r) => r.id === String(id))
46
47
  const last = rows[rows.length - 1] || null
47
48
  const sealedNow = Boolean(last && last.action === 'seal')
48
- if ((action === 'seal' && sealedNow) || (action === 'unseal' && !sealedNow)) return { row: last, noop: true }
49
+ // 有坏行时状态不确定:不做"重复操作"的合并,直接按她的请求追加,
50
+ // 让最后一次显式动作成为真正生效的那条。
51
+ if (!all.bad && ((action === 'seal' && sealedNow) || (action === 'unseal' && !sealedNow))) return { row: last, noop: true }
49
52
  return { row: appendUnlocked(memDir, makeRow({ id, action, note })), noop: false }
50
53
  }, opts)
51
54
  }
52
55
 
53
56
  export function readAll(memDir) {
54
57
  let raw = ''
55
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
58
+ try {
59
+ raw = fs.readFileSync(eventsFile(memDir), 'utf8')
60
+ } catch (error) {
61
+ // 只有"还没有这个文件"能当空;权限、磁盘、路径是目录这类错误必须抛出去。
62
+ // 否则正文可读、封存日志读不出来时,召回/醒来/书会当成"她什么都没封存"。
63
+ if (error?.code === 'ENOENT') return { rows: [], bad: 0 }
64
+ const wrapped = new Error('封存日志读不出来:' + String(error?.message || error))
65
+ wrapped.code = 'SEAL_EVENTS_UNREADABLE'
66
+ wrapped.cause = error
67
+ throw wrapped
68
+ }
56
69
  const rows = []
57
70
  let bad = 0
58
71
  for (const line of raw.split('\n')) {
@@ -67,8 +80,16 @@ export function readAll(memDir) {
67
80
  }
68
81
 
69
82
  // 每个经历 id 现在是否封存着:只收最后一次是 seal 的;until 用于翻回那天(那时还没封存就不算)
70
- export function sealedByExp(memDir, { until = null } = {}) {
71
- const { rows } = readAll(memDir)
83
+ // strict:展示路径用。日志里有坏行时"某条经历唯一一次封存"可能正好坏掉,
84
+ // 这时不能默认可见——把"状态未知"抛给调用方(fail closed)。
85
+ export function sealedByExp(memDir, { until = null, strict = false } = {}) {
86
+ const { rows, bad } = readAll(memDir)
87
+ if (strict && bad > 0) {
88
+ const error = new Error('封存日志有 ' + bad + ' 行无法解析,封存状态不确定')
89
+ error.code = 'SEAL_EVENTS_CORRUPT'
90
+ error.bad = bad
91
+ throw error
92
+ }
72
93
  const last = new Map()
73
94
  for (const r of rows) {
74
95
  if (!before(r, until)) continue
@@ -83,7 +83,10 @@ export interface Experience {
83
83
 
84
84
  export const LIMITS: Record<string, number>
85
85
 
86
- export function loadAll(dir: string, opts?: { asOf?: AsOf }): Experience[]
86
+ export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean }): Experience[]
87
+
88
+ /** 经历文件里解析不了的行数:展示路径遇到坏行会 fail closed,这个用于诊断和"先备份再修复" */
89
+ export function badLines(dir: string): number
87
90
 
88
91
  export function addExperience(dir: string, opts: {
89
92
  text: string