whale-memory-core 0.19.1 → 0.20.0

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/README.md CHANGED
@@ -76,4 +76,19 @@ node demo.mjs
76
76
 
77
77
  一条经历一行 JSON,格式见 [`docs/schema.md`](../../docs/schema.md)。三条虚构样本在 [`examples/samples/`](../../examples/samples/)。
78
78
 
79
- 移植说明见仓库根目录 [`docs/porting.md`](../../docs/porting.md)。
79
+ 移植说明见仓库根目录 [`docs/porting.md`](../../docs/porting.md)。
80
+ | 模块 | 作用 |
81
+ |---|---|
82
+ | `self-experience.js` | 经历两层(then / later)、重要度、两段式回想 |
83
+ | `self-memory.js` | 经历 + 日记的统一读取与渲染 |
84
+ | `waking.js` | 醒来块:每天第一次唤醒给昨天的时间线 |
85
+ | `self-prompt.js` | 提示词 overlay:版本只追加、可回退 |
86
+ | `self-settings.js` | 她自己的设置(软限制归她) |
87
+ | `time-sense.js` | 人话时间:刚刚 / 昨天 20:30 / 上周三 / 2 个月前 |
88
+ | `relative-window.js` | 把「前几天 / 上周三 / 两周前」翻成时间窗口 |
89
+ | `person-card.js` | 把「这个人是谁」压成一行;匹配不到就不写 |
90
+ | `scope-key.js` | 会话作用域键:会话级与人设级的不对称规则 |
91
+ | `conversation-privacy.js` | 跨窗口可见性判定 + 确定性脱敏 |
92
+ | `fact-card.js` | 规则抽事实:项目、预算、喜恶、所在地、关系 |
93
+ | `fact-store.js` | 事实卡存储与相关性挑选(宁可不说,不乱说) |
94
+ | `fact-judge.js` | 模型抽事实的封装,引文必须能在原文找到 |
package/index.js CHANGED
@@ -19,3 +19,8 @@ export * as archive from './lib/archive.js'
19
19
  export * as timeSense from './lib/time-sense.js'
20
20
  export * as relativeWindow from './lib/relative-window.js'
21
21
  export * as personCard from './lib/person-card.js'
22
+ export * as scopeKey from './lib/scope-key.js'
23
+ export * as conversationPrivacy from './lib/conversation-privacy.js'
24
+ export * as factCard from './lib/fact-card.js'
25
+ export * as factStore from './lib/fact-store.js'
26
+ export * as factJudge from './lib/fact-judge.js'
@@ -0,0 +1,11 @@
1
+ /** 解析会话键:group_123 / private_9 / local:owner,可带 #p_xxx 人设后缀 */
2
+ export function roomOf(chatKey: string): { base: string; slot: string; key: string; group: boolean; private: boolean; local: boolean } | null
3
+ /** 这个会话是不是主人自己的窗口 */
4
+ export function isOwnerRoom(chatKey: string, ownerId: string): boolean
5
+ /** 跨窗口可见性判定:主人私聊不流向群;同房间只认同槽位;其余交给 isActive */
6
+ export function createAudience(policy?: { ownerId?: string; isActive?: (sourceKey: string, sourceBase: string) => boolean }): { permits: (sourceKey: string, destKey: string) => boolean }
7
+ /** 确定性脱敏:数字、链接、邮箱、密钥、长串 */
8
+ export function redactSensitive(value: string): string
9
+ /** 跨窗口引用别人私话时的使用规则 */
10
+ export const CROSS_ROOM_RULE: string
11
+ export function baseChatKey(chatKey: string): string
@@ -0,0 +1,87 @@
1
+ /**
2
+ * 跨窗口可见性:不同会话之间,谁的记忆可以给谁看。
3
+ *
4
+ * 这不是通用"全共享"或"全隔离"的二选一——真实产品里,主人私聊的内容
5
+ * 不能被带进群,但换一个窗口聊天时又应该接得上;别人的私聊则往往属于
6
+ * "本人不在场时不替他公开"的模糊地带。这里把这条判断题写成一个纯函数,
7
+ * 让宿主自己填策略,而不是把默认值藏进实现里。
8
+ *
9
+ * 纯函数,无 IO。
10
+ */
11
+ import { baseChatKey } from './scope-key.js';
12
+
13
+ /** 解析会话键:group_123 / private_9 / local:owner,可带 #p_xxx 人设后缀。 */
14
+ export function roomOf(chatKey) {
15
+ const raw = String(chatKey || '').trim();
16
+ if (!raw) return null;
17
+ const key = raw.replace(/:/, ':');
18
+ const m = /^(group_\d+|private_\d+|local:owner)(?:#(p_[A-Za-z0-9]{1,16}))?$/.exec(key);
19
+ if (!m) return null;
20
+ return {
21
+ base: m[1],
22
+ slot: m[2] || '',
23
+ key,
24
+ group: m[1].startsWith('group_'),
25
+ private: m[1].startsWith('private_'),
26
+ local: m[1] === 'local:owner'
27
+ };
28
+ }
29
+
30
+ /** 这个会话是不是"主人自己的窗口"。 */
31
+ export function isOwnerRoom(chatKey, ownerId) {
32
+ const room = roomOf(chatKey);
33
+ if (!room) return false;
34
+ return room.local || (room.private && room.base === `private_${ownerId}`);
35
+ }
36
+
37
+ /**
38
+ * 建一个可见性判定器。
39
+ *
40
+ * @param {object} policy
41
+ * @param {string} policy.ownerId 主人的账号 ID
42
+ * @param {(sourceKey:string, sourceBase:string)=>boolean} [policy.isActive] 额外的活跃性判断(例如人设槽位是否匹配)
43
+ * @returns {{permits:(sourceKey:string, destKey:string)=>boolean}}
44
+ */
45
+ export function createAudience({ ownerId = '', isActive = () => true } = {}) {
46
+ const cache = new Map();
47
+ function permits(sourceKey, destKey) {
48
+ const cacheKey = `${sourceKey}\u0000${destKey}`;
49
+ if (cache.has(cacheKey)) return cache.get(cacheKey);
50
+ const source = roomOf(sourceKey);
51
+ const dest = roomOf(destKey);
52
+ let allowed = false;
53
+ if (source && dest) {
54
+ if (source.base === dest.base) {
55
+ // 同一个房间内:只有完全同一套槽位才算"这里本来就看得到"
56
+ allowed = source.key === dest.key;
57
+ } else if (!(dest.group && isOwnerRoom(sourceKey, ownerId))) {
58
+ // 跨房间:主人私聊 / 本机主人不流向群;其余按 isActive 判断
59
+ allowed = isActive(source.key, source.base);
60
+ }
61
+ }
62
+ cache.set(cacheKey, allowed);
63
+ return allowed;
64
+ }
65
+ return { permits };
66
+ }
67
+
68
+ // 确定性脱敏:数字、链接、邮箱、密钥串。模型只能决定"要不要提",
69
+ // 而"长什么样可以被复述"在这里掐掉,不依赖模型自觉。
70
+ const SENSITIVE_RULES = [
71
+ [/\b\d{6,}\b/g, '(数字略)'],
72
+ [/https?:\/\/\S+/gi, '(链接略)'],
73
+ [/\b[\w.+-]+@[\w-]+\.[\w.]+\b/g, '(邮箱略)'],
74
+ [/(?:密码|口令|验证码|密钥|token|api[_-]?key)\s*[::=]?\s*\S+/gi, '(密钥略)'],
75
+ [/\b[A-Za-z0-9_-]{24,}\b/g, '(长串略)']
76
+ ];
77
+
78
+ export function redactSensitive(value) {
79
+ let text = String(value || '');
80
+ for (const [re, replacement] of SENSITIVE_RULES) text = text.replace(re, replacement);
81
+ return text;
82
+ }
83
+
84
+ /** 跨窗口引用别人私聊内容时,给模型的使用规则(放在召回条目之后,被裁剪时先裁它)。 */
85
+ export const CROSS_ROOM_RULE = '(这些是不同窗口的经历;别人的私话只能模糊带过,不复述原话、不带数字身份;拿不准就不提。)';
86
+
87
+ export { baseChatKey };
@@ -0,0 +1,6 @@
1
+ /** 从一句话里抽事实(规则兜底);返回空数组表示没抽到 */
2
+ export function extractFacts(text: string, meta?: { personId?: string; chatKey?: string; ts?: number; sourceId?: string }): Array<{ kind: string; value: string; subject: string; text: string; ts: number; personId: string; chatKey: string; sourceId: string }>
3
+ /** 合并:同 kind+value 留一条,记次数与最新时间 */
4
+ export function mergeFacts(facts: Array<Record<string, unknown>>): Array<Record<string, unknown>>
5
+ /** 渲染成一行 */
6
+ export function renderFact(fact: Record<string, unknown>): string
@@ -0,0 +1,126 @@
1
+ /**
2
+ * 事实抽取:从对话里认出「项目叫 X」「预算 X」「我爱吃 X」这类稳定事实。
3
+ *
4
+ * 为什么需要:她记得"那天聊了什么",但记不住"他爱吃黄焖鸡、项目叫鲸舟"。
5
+ * 实测:这类事实在原始消息里都有,源库 1194 张卡里却是 0 张——消息变成卡片时被当成事件吞掉了。
6
+ *
7
+ * 这一层只负责"认出并整理成一条结构化事实",写不写、写哪里由调用方决定。
8
+ * 纯函数,无 IO。
9
+ */
10
+
11
+ /** 值里不能带这些:它们说明后面接的是从句,不是名字。 */
12
+ const STOP_VALUE = /^(?:什么|啥|这个|那个|一下|这些|那些|他|她|它|我|你)$/;
13
+
14
+ function clean(value) {
15
+ return String(value || '')
16
+ .replace(/[\u0000-\u001f\u007f\u200b-\u200f\ufeff]/g, '')
17
+ .replace(/^[「『"'\s]+/, '')
18
+ .replace(/[」』"'\s]+$/, '')
19
+ .replace(/[,。;、,.;!?!?].*$/, '')
20
+ .trim();
21
+ }
22
+
23
+ function usable(value, { min = 1, max = 16 } = {}) {
24
+ const v = clean(value);
25
+ if (!v || v.length < min || v.length > max) return '';
26
+ if (STOP_VALUE.test(v)) return '';
27
+ return v;
28
+ }
29
+
30
+ /**
31
+ * 从一句话里抽事实。
32
+ * @param {string} text 原始消息
33
+ * @param {object} [meta] {personId, chatKey, ts, sourceId}
34
+ * @returns {Array<{kind: string, value: string, subject: string, text: string, ts: number, personId: string, chatKey: string, sourceId: string}>}
35
+ */
36
+ export function extractFacts(text, meta = {}) {
37
+ const raw = String(text || '');
38
+ if (!raw.trim()) return [];
39
+ const out = [];
40
+ const push = (kind, value, subject = '') => {
41
+ const v = usable(value, { max: kind === 'budget' ? 12 : 20 });
42
+ if (!v) return;
43
+ out.push({
44
+ kind,
45
+ value: v,
46
+ subject,
47
+ text: raw.slice(0, 120),
48
+ ts: Number(meta.ts) || 0,
49
+ personId: String(meta.personId || ''),
50
+ chatKey: String(meta.chatKey || ''),
51
+ sourceId: String(meta.sourceId || '')
52
+ });
53
+ };
54
+
55
+ // 项目 / 名字:项目叫鲸舟 / 名字叫做 X / 代号是 X
56
+ let m = /(?:项目|产品|工程|计划|企划)(?:名|名字|代号)?\s*(?:叫|叫做|是|定为|取名)\s*[「『"]?([^,。;、,.!?!?」』"]{1,16})/.exec(raw);
57
+ if (m) push('project', m[1]);
58
+
59
+ // 预算 / 金额
60
+ m = /(?:预算|成本|花了|投入|报价|价格|工资|月薪)\s*(?:是|在|大概|差不多|一共|约)?\s*([0-9一二三四五六七八九十百千万两]{1,10}\s*[元块万]?)/.exec(raw);
61
+ if (m) push('budget', m[1]);
62
+
63
+ // 偏好:我喜欢 / 我爱吃 / 我不吃 / 我讨厌
64
+ m = /我(?:最|很|真的|特别)?(喜欢|爱吃|爱喝|讨厌|不喜欢|不吃|忌口)\s*([^,。;、,.!?!?]{1,16})/.exec(raw);
65
+ if (m) push(/讨厌|不喜欢|不吃|忌口/.test(m[1]) ? 'dislike' : 'like', m[2]);
66
+
67
+ // 居住 / 所在地
68
+ m = /我(?:现在)?(?:住在|家在|生活在)\s*([^,。;、,.!?!?]{2,14})/.exec(raw);
69
+ if (m) push('place', m[1]);
70
+
71
+ // 名字
72
+ m = /我(?:的名字)?(?:叫|叫做)\s*([^,。;、,.!?!?]{1,10})/.exec(raw);
73
+ if (m) push('name', m[1]);
74
+
75
+ // 关系:我的 X 是 Y
76
+ m = /我的(朋友|同事|室友|对象|女朋友|男朋友|女儿|儿子|爸爸|妈妈|师父|徒弟)\s*(?:叫|叫做|是)\s*([^,。;、,.!?!?]{1,10})/.exec(raw);
77
+ if (m) push('relation', m[2], m[1]);
78
+
79
+ // 去重(同一句里同 kind 同 value 只留一条)
80
+ const seen = new Set();
81
+ return out.filter((f) => {
82
+ const key = `${f.kind}|${f.value}`;
83
+ if (seen.has(key)) return false;
84
+ seen.add(key);
85
+ return true;
86
+ });
87
+ }
88
+
89
+ /** 把一批事实合并成卡片列表:同 kind+value 只留最近一条,并记次数。 */
90
+ export function mergeFacts(facts) {
91
+ const map = new Map();
92
+ for (const f of Array.isArray(facts) ? facts : []) {
93
+ if (!f || !f.kind || !f.value) continue;
94
+ const key = `${f.kind}|${f.value}`;
95
+ const cur = map.get(key);
96
+ if (!cur) {
97
+ map.set(key, { ...f, count: 1 });
98
+ continue;
99
+ }
100
+ cur.count += 1;
101
+ if ((Number(f.ts) || 0) >= (Number(cur.ts) || 0)) {
102
+ cur.ts = f.ts;
103
+ cur.text = f.text;
104
+ cur.sourceId = f.sourceId;
105
+ cur.personId = f.personId || cur.personId;
106
+ cur.chatKey = f.chatKey || cur.chatKey;
107
+ cur.subject = f.subject || cur.subject;
108
+ }
109
+ }
110
+ return [...map.values()].sort((a, b) => (Number(b.ts) || 0) - (Number(a.ts) || 0));
111
+ }
112
+
113
+ /** 渲染成一行,供写入记忆卡或展示。 */
114
+ export function renderFact(f) {
115
+ const label = {
116
+ project: '项目',
117
+ budget: '预算/金额',
118
+ like: '喜欢',
119
+ dislike: '不喜欢',
120
+ place: '所在地',
121
+ name: '称呼',
122
+ relation: '关系'
123
+ }[f.kind] || f.kind;
124
+ const who = f.subject ? `${f.subject}` : '他';
125
+ return `${who}的${label}:${f.value}`;
126
+ }
@@ -0,0 +1,3 @@
1
+ /** 把一批消息交给模型抽事实;引文对不上原文的条目不采信 */
2
+ export function judgeFacts(options: { messages: Array<{ ref?: string; sender?: string; text: string; ts?: number }>; chatCompletion: Function; maxMessages?: number; logger?: { warn?: Function } }): Promise<Array<{ kind: string; value: string; subject: string; quote: string; ts: number; ref: string }>>
3
+ export const FACT_KINDS: string[]
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 事实判断:把一段对话交给模型,问「这里有没有值得长期记住的稳定事实」。
3
+ *
4
+ * 为什么不用规则:实测规则抽不出「黄焖鸡吧,下饭」「最爱的还是咸蛋黄焗南瓜」这类隐性说法,
5
+ * 而它们恰恰是"她记得住人、记不住事"的缺口。
6
+ *
7
+ * 这一层只负责问和整理(不写存储);写不写、写哪里由调用方决定。
8
+ */
9
+
10
+ const KINDS = ['project', 'budget', 'like', 'dislike', 'place', 'name', 'relation', 'goal', 'other'];
11
+
12
+ const SYSTEM = `你在帮一位 AI 陪伴者整理"关于对方的稳定事实"。
13
+ 只从给出的对话里抽取:对方的项目/工作、金额与预算、喜恶(吃的、玩的、话题)、所在地、称呼、关系、长期打算。
14
+ 硬规则:
15
+ 1. 只抽稳定事实,不抽当下一句话的情绪、玩笑、假设和反问。
16
+ 2. 必须能在原文里找到依据;quote 必须逐字取自该条消息。
17
+ 3. 说话人自己说的事,subject 写 sender;别人问他、他确认的,也算。
18
+ 4. 不确定就不抽。宁少勿错。
19
+ 5. 输出 JSON:{"facts":[{"kind":"project|budget|like|dislike|place|name|relation|goal|other","value":"抽到的值(≤16字)","subject":"关于谁(用消息里的 sender 名字)","quote":"原文片段","ref":"该消息的 ref"}]}
20
+ 没有就返回 {"facts":[]}。不要输出任何解释。`;
21
+
22
+ function contentOf(response) {
23
+ const c = response?.choices?.[0]?.message?.content;
24
+ if (typeof c === 'string') return c;
25
+ if (Array.isArray(c)) return c.map((x) => (typeof x === 'string' ? x : x?.text || '')).join('');
26
+ return '';
27
+ }
28
+
29
+ function parseJson(text, failMessage) {
30
+ const raw = String(text || '').trim();
31
+ const start = raw.indexOf('{');
32
+ const end = raw.lastIndexOf('}');
33
+ if (start < 0 || end <= start) throw new Error(failMessage);
34
+ return JSON.parse(raw.slice(start, end + 1));
35
+ }
36
+
37
+ /**
38
+ * @param {object} opts
39
+ * @param {Array<{ref:string, sender:string, text:string, ts:number}>} opts.messages
40
+ * @param {Function} opts.chatCompletion
41
+ * @returns {Promise<Array<object>>} 规范化后的事实
42
+ */
43
+ export async function judgeFacts({ messages, chatCompletion, maxMessages = 40, logger = null } = {}) {
44
+ const rows = (Array.isArray(messages) ? messages : [])
45
+ .map((m, i) => ({
46
+ ref: String(m.ref || `M${i + 1}`),
47
+ sender: String(m.sender || '').slice(0, 20),
48
+ text: String(m.text || '').replace(/\s+/g, ' ').trim().slice(0, 200),
49
+ ts: Number(m.ts) || 0
50
+ }))
51
+ .filter((m) => m.text);
52
+ if (!rows.length) return [];
53
+
54
+ const batch = rows.slice(0, Math.max(1, Math.min(60, Number(maxMessages) || 40)));
55
+ const response = await chatCompletion({
56
+ messages: [
57
+ { role: 'system', content: SYSTEM },
58
+ { role: 'user', content: JSON.stringify(batch) }
59
+ ],
60
+ tools: null,
61
+ temperature: 0.1,
62
+ // 推理型模型会先想一大段,预算给小了 content 会是空的(实测 300 时全被思考吃掉)
63
+ maxTokens: Math.max(1200, Math.min(3000, 800 + batch.length * 30))
64
+ });
65
+
66
+ const parsed = parseJson(contentOf(response), '模型未返回有效 JSON');
67
+ const list = Array.isArray(parsed?.facts) ? parsed.facts : [];
68
+ const byRef = new Map(batch.map((m) => [m.ref, m]));
69
+ const out = [];
70
+ for (const row of list) {
71
+ const kind = String(row?.kind || '').toLowerCase();
72
+ const value = String(row?.value || '').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 20);
73
+ if (!KINDS.includes(kind) || !value) continue;
74
+ const ref = String(row?.ref || '');
75
+ const source = byRef.get(ref);
76
+ const quote = String(row?.quote || '').trim().slice(0, 80);
77
+ // 引文必须能在对应消息里找到,否则这条不采信
78
+ if (source && quote && !source.text.includes(quote.slice(0, 12))) {
79
+ logger?.warn?.('[fact-judge] 引文对不上原文,丢弃:', value);
80
+ continue;
81
+ }
82
+ out.push({
83
+ kind,
84
+ value,
85
+ subject: String(row?.subject || source?.sender || '').slice(0, 20),
86
+ quote: quote || (source ? source.text.slice(0, 40) : ''),
87
+ ts: source?.ts || 0,
88
+ ref
89
+ });
90
+ }
91
+ return out;
92
+ }
93
+
94
+ export { KINDS as FACT_KINDS };
@@ -0,0 +1,8 @@
1
+ /** 读全部事实卡;文件不存在返回空数组 */
2
+ export function loadFacts(dir: string): Array<Record<string, unknown>>
3
+ /** 合并写入(同 kind+value 更新而不堆积) */
4
+ export function saveFacts(dir: string, facts: Array<Record<string, unknown>>): { added: number; updated: number }
5
+ /** 挑和当前这句话最相关的事实;没有明显相关的返回空 */
6
+ export function relevantFacts(facts: Array<Record<string, unknown>>, query: string, options?: { limit?: number }): Array<Record<string, unknown>>
7
+ /** 渲染成一行提示词;没有事实返回空串 */
8
+ export function renderFactsLine(facts: Array<Record<string, unknown>>): string
@@ -0,0 +1,185 @@
1
+ /**
2
+ * 事实卡存储:把「关于他的稳定事实」单独放一个文件,不混进事件卡库。
3
+ *
4
+ * 为什么单独放:事件库是她记忆的主干,改格式风险高;事实卡是补充层,
5
+ * 坏了删掉就行,不影响她原来的记忆。
6
+ *
7
+ * 文件:<dir>/fact-cards.jsonl,一行一条,便于人工查看和手改。
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ const FILE = 'fact-cards.jsonl';
13
+
14
+ function fileOf(dir) {
15
+ return path.join(String(dir || ''), FILE);
16
+ }
17
+
18
+ /** 读全部事实卡;文件不存在返回空数组。 */
19
+ export function loadFacts(dir) {
20
+ const file = fileOf(dir);
21
+ if (!fs.existsSync(file)) return [];
22
+ const out = [];
23
+ for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
24
+ const text = line.trim();
25
+ if (!text) continue;
26
+ try {
27
+ const row = JSON.parse(text);
28
+ if (row && row.kind && row.value) out.push(row);
29
+ } catch { /* 坏行跳过,不影响其他 */ }
30
+ }
31
+ return out;
32
+ }
33
+
34
+ /**
35
+ * 合并写入:同 kind + value 只留一条,更新时间和次数,不重复堆积。
36
+ * @returns {{added:number, updated:number}}
37
+ */
38
+ export function saveFacts(dir, facts) {
39
+ const existing = loadFacts(dir);
40
+ const byKey = new Map(existing.map((f) => [`${f.kind}|${f.value}`, f]));
41
+ let added = 0;
42
+ let updated = 0;
43
+ for (const fact of Array.isArray(facts) ? facts : []) {
44
+ if (!fact?.kind || !fact?.value) continue;
45
+ const key = `${fact.kind}|${fact.value}`;
46
+ const cur = byKey.get(key);
47
+ if (!cur) {
48
+ byKey.set(key, {
49
+ kind: fact.kind,
50
+ value: fact.value,
51
+ subject: String(fact.subject || ''),
52
+ quote: String(fact.quote || '').slice(0, 80),
53
+ chatKey: String(fact.chatKey || ''),
54
+ ts: Number(fact.ts) || Date.now(),
55
+ count: 1
56
+ });
57
+ added += 1;
58
+ continue;
59
+ }
60
+ cur.count = (Number(cur.count) || 1) + 1;
61
+ if ((Number(fact.ts) || 0) >= (Number(cur.ts) || 0)) {
62
+ cur.ts = Number(fact.ts) || cur.ts;
63
+ 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
+ }
67
+ updated += 1;
68
+ }
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 };
76
+ }
77
+
78
+ /** 这个值能不能安全地说出来:短、是名词短语、不含动词和否定。 */
79
+ function valueLooksSafe(fact) {
80
+ const v = cleanValue(fact);
81
+ if (!v || v.length > 12) return false;
82
+ if (fact.kind === 'like' || fact.kind === 'dislike') {
83
+ if (/[喜欢吃喝玩花叫是不别想看去来]/.test(v)) return false;
84
+ }
85
+ return true;
86
+ }
87
+
88
+ const KIND_LABEL = {
89
+ project: '项目',
90
+ budget: '预算',
91
+ like: '喜欢',
92
+ dislike: '不喜欢',
93
+ place: '在',
94
+ name: '称呼',
95
+ relation: '关系',
96
+ goal: '打算'
97
+ };
98
+
99
+ const SELF_NAMES = new Set(['我', '鲸', 'self', '小鲸鱼', '鲸鲸']);
100
+
101
+ /** 事实关于谁:关于她自己的用「你」,关于别人的用名字。 */
102
+ function subjectOf(fact) {
103
+ const raw = String(fact?.subject || '').trim();
104
+ if (!raw || SELF_NAMES.has(raw)) return '你';
105
+ return raw.slice(0, 12);
106
+ }
107
+
108
+ /** 模型常把整句塞进 value:「我爸爸是山中晨雾」。这里去掉多余的主语和系词。 */
109
+ function cleanValue(fact) {
110
+ let v = String(fact?.value || '')
111
+ .replace(/^(?:我|他|她|你)(?:的)?/, '')
112
+ .replace(/^(?:是|叫|在)/, '')
113
+ .trim();
114
+ // 「不吃香菜」当 dislike 时,把否定词去掉,别渲染成「不喜欢不吃香菜」
115
+ if (fact?.kind === 'dislike') v = v.replace(/^(?:不|别)(?:爱|喜欢|吃|喝|玩|看|要)?/, '').trim();
116
+ // 值里带「不+动词」的,多半是句子不是名词短语,宁可不用
117
+ if (/[不别][好吃玩喝看说想]/.test(v)) return '';
118
+ return v.slice(0, 20);
119
+ }
120
+
121
+ function renderText(fact) {
122
+ const label = KIND_LABEL[fact.kind] || '记得';
123
+ const who = subjectOf(fact);
124
+ const value = cleanValue(fact) || String(fact?.value || '').slice(0, 20);
125
+ if (fact.kind === 'relation') return who === '你' ? `你${value}` : `${who}${value}`;
126
+ if (fact.kind === 'name') return who === '你' ? `别人叫你${value}` : `${who}叫${value}`;
127
+ if (fact.kind === 'place') return who === '你' ? `你在${value}` : `${who}在${value}`;
128
+ if (fact.kind === 'other') return who === '你' ? `你${value}` : `${who}${value}`;
129
+ return who === '你' ? `你${label}${value}` : `${who}${label}${value}`;
130
+ }
131
+
132
+ /**
133
+ * 挑和当前这句话最相关的事实。
134
+ * @param {Array} facts
135
+ * @param {string} query 当前消息
136
+ * @param {{limit?:number, now?:number}} options
137
+ */
138
+ export function relevantFacts(facts, query, { limit = 3 } = {}) {
139
+ const q = String(query || '');
140
+ const list = Array.isArray(facts) ? facts : [];
141
+ if (!list.length) return [];
142
+ // 只讲当前语境相关的:关于她自己的,或者这句话里点到的。别人的事不往里塞。
143
+ const SAFE_KINDS = new Set(['project', 'budget', 'like', 'dislike', 'place', 'name', 'relation']);
144
+ const scoped = list.filter((fact) => {
145
+ if (!SAFE_KINDS.has(String(fact.kind || ''))) return false;
146
+ if (!valueLooksSafe(fact)) return false;
147
+ const who = String(fact.subject || '').trim();
148
+ const isSelf = !who || ['我', '鲸', 'self', '小鲸鱼', '鲸鲸'].includes(who);
149
+ if (isSelf) return true;
150
+ return Boolean(q && fact.value && q.includes(String(fact.value).slice(0, 6)));
151
+ });
152
+ const asksName = /(叫|名字|谁|称呼|身份)/.test(q);
153
+ const asksProject = /(项目|工程|做啥|做什么|在忙)/.test(q);
154
+ const asksBudget = /(预算|钱|花|成本|价格)/.test(q);
155
+ const scoped2 = scoped.filter((fact) => {
156
+ const kind = String(fact.kind || '');
157
+ if (kind === 'name') return asksName;
158
+ if (kind === 'project') return asksProject || (q && q.includes(String(fact.value || '').slice(0, 4)));
159
+ if (kind === 'budget') return asksBudget || (q && q.includes(String(fact.value || '').slice(0, 3)));
160
+ if (kind === 'relation') return /(谁|爸|妈|女儿|关系|家人)/.test(q);
161
+ return true;
162
+ });
163
+ const scored = scoped2.map((fact) => {
164
+ let score = 0;
165
+ const value = String(fact.value || '');
166
+ if (q && value && q.includes(value)) score += 5; // 这句话直接提到了
167
+ else if (q && value && [...value].filter((ch) => q.includes(ch)).length >= 2) score += 1;
168
+ if (fact.kind === 'like' || fact.kind === 'dislike') score += 0.5; // 口味类允许泛提示
169
+ if (fact.kind === 'name' && asksName) score += 0.8;
170
+ if (fact.kind === 'project' && asksProject) score += 0.8;
171
+ if (fact.kind === 'budget' && asksBudget) score += 0.8;
172
+ if (fact.kind === 'relation' && /(谁|爸|妈|女儿|关系|家人)/.test(q)) score += 0.8;
173
+ return { fact, score };
174
+ });
175
+ scored.sort((a, b) => b.score - a.score);
176
+ return scored.filter((x) => x.score >= 0.6).slice(0, limit).map((x) => x.fact);
177
+ }
178
+
179
+ /** 渲染成一行提示词;没有事实返回空串。 */
180
+ export function renderFactsLine(facts) {
181
+ const list = (Array.isArray(facts) ? facts : []).filter((f) => f?.kind && f?.value);
182
+ if (!list.length) return '';
183
+ const parts = list.slice(0, 3).map(renderText);
184
+ return `(你还记得:${parts.join(';')}。)`;
185
+ }
@@ -0,0 +1,10 @@
1
+ /** 去掉人设后缀(#p_xxx),得到会话级键 */
2
+ export function baseChatKey(chatKey: string): string
3
+ /** 这个键是不是人设级 */
4
+ export function isPersonaScoped(chatKey: string): boolean
5
+ /** 一次查询应覆盖的键:人设级 = [人设键, 会话键];会话级 = [会话键](不反向并入,避免串台) */
6
+ export function scopeKeysFor(chatKey: string): string[]
7
+ /** 记录是否落在查询范围内 */
8
+ export function recordInScope(recordChatKey: string, queryChatKey: string): boolean
9
+ /** 一个键的所有写法(去重) */
10
+ export function variantsOf(chatKey: string): string[]
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 会话作用域键:同一个会话可能有两种写法——会话级 `group_123` 和人设级 `group_123#p_abcd`。
3
+ * 检索时如果只认精确键,人设级查询就看不到会话级的老记录。
4
+ *
5
+ * 规则(从 QQ Agent 插件的真实 bug 里提炼):
6
+ * - 人设级查询 = 人设级记录 + 同会话的会话级记录
7
+ * - 会话级查询 = 只认会话级记录(不反向并入人设记录,避免把某人的记忆串给所有人)
8
+ *
9
+ * 纯函数,宿主无关。
10
+ */
11
+
12
+ const PERSONA_SUFFIX = /#p_[A-Za-z0-9]+$/i;
13
+
14
+ /** 去掉人设后缀,得到会话级键。 */
15
+ export function baseChatKey(chatKey) {
16
+ return String(chatKey || '').trim().replace(PERSONA_SUFFIX, '');
17
+ }
18
+
19
+ /** 这个键是不是人设级。 */
20
+ export function isPersonaScoped(chatKey) {
21
+ return PERSONA_SUFFIX.test(String(chatKey || '').trim());
22
+ }
23
+
24
+ /**
25
+ * 一次查询应该覆盖哪些键。
26
+ * @param {string} chatKey 当前会话键
27
+ * @returns {string[]} 由具体到宽泛;会话级查询只有一个
28
+ */
29
+ export function scopeKeysFor(chatKey) {
30
+ const raw = String(chatKey || '').trim();
31
+ if (!raw) return [];
32
+ const base = baseChatKey(raw);
33
+ if (!base || base === raw) return [raw];
34
+ return [raw, base];
35
+ }
36
+
37
+ /**
38
+ * 一条记录的会话键是否落在本次查询范围内。
39
+ * @param {string} recordChatKey 记录自己的键
40
+ * @param {string} queryChatKey 查询用的键
41
+ */
42
+ export function recordInScope(recordChatKey, queryChatKey) {
43
+ const record = String(recordChatKey || '').trim();
44
+ const query = String(queryChatKey || '').trim();
45
+ if (!query) return true; // 不限定会话 = 全局
46
+ if (!record) return false;
47
+ return scopeKeysFor(query).includes(record);
48
+ }
49
+
50
+ /** 供测试与迁移用:把一个键的两种写法都列出来。 */
51
+ export function variantsOf(chatKey) {
52
+ const raw = String(chatKey || '').trim();
53
+ const base = baseChatKey(raw);
54
+ if (!base) return [];
55
+ return [...new Set([base, raw])];
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -104,6 +104,22 @@
104
104
  "./person-card": {
105
105
  "types": "./lib/person-card.d.ts",
106
106
  "default": "./lib/person-card.js"
107
+ },
108
+ "./conversation-privacy": {
109
+ "types": "./lib/conversation-privacy.d.ts",
110
+ "default": "./lib/conversation-privacy.js"
111
+ },
112
+ "./fact-card": {
113
+ "types": "./lib/fact-card.d.ts",
114
+ "default": "./lib/fact-card.js"
115
+ },
116
+ "./fact-store": {
117
+ "types": "./lib/fact-store.d.ts",
118
+ "default": "./lib/fact-store.js"
119
+ },
120
+ "./fact-judge": {
121
+ "types": "./lib/fact-judge.d.ts",
122
+ "default": "./lib/fact-judge.js"
107
123
  }
108
124
  },
109
125
  "files": [