whale-memory-core 0.10.0 → 0.10.2

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
@@ -47,6 +47,17 @@ node demo.mjs
47
47
 
48
48
  不需要配置文件、不需要 API key、不联网。演示会在临时目录里建一份数据,结束时会输出目录位置,方便检查记录。
49
49
 
50
+ ## 路径约定(容易踩)
51
+
52
+ 不同模块接受的目录不一样:
53
+
54
+ | 传什么 | 模块 |
55
+ | --- | --- |
56
+ | **记忆目录** `<data>/plugin-data/biomimetic-memory` | `self-experience`(`addExperience` / `loadAll` / `recall`)、`self-memory`、`recall-events`、`later-events` |
57
+ | **数据根目录** `<data>` | `waking`、`self-prompt`、`self-settings` |
58
+
59
+ 传错不会报错,只会写到另一个位置。CLI 已经替你处理好了:`exp.*` 收 `MEM_DIR`,其余收 `DATA`。
60
+
50
61
  ## 数据
51
62
 
52
63
  一条经历一行 JSON,格式见 [`docs/schema.md`](../../docs/schema.md)。三条虚构样本在 [`examples/samples/`](../../examples/samples/)。
@@ -0,0 +1,54 @@
1
+ // 查询匹配:self-experience 与 self-memory 共用同一套口径,防编造的门槛只在这里定义
2
+ // 中文等按相邻两字切;拉丁字母按整词切(不切成字母对,否则 "the" 会命中一切);统一小写
3
+
4
+ // 高频但不携带信息的词:不参与重叠计算,避免「今天/什么/我的」把不相关的东西拉进来
5
+ const STOP = new Set([
6
+ '什么', '怎么', '这个', '那个', '我的', '你的', '他的', '她的', '我们', '他们', '她们', '自己',
7
+ '昨天', '今天', '明天', '后天', '前天', '现在', '刚刚', '后来', '以前', '以后', '时候',
8
+ '是不是', '有没有', '一点', '一些', '东西', '事情', '觉得', '知道', '记得', '忘了',
9
+ '可能', '应该', '还是', '就是', '但是', '因为', '所以', '如果', '然后', '已经',
10
+ '没有', '不是', '可以', '一个', '这样', '那样', '真的', '其实', '比较', '非常', '特别',
11
+ '一直', '总是', '大概', '也许', '当然', '而是', '并且', '或者', '不过', '虽然', '只是',
12
+ '还有', '以及', '关于', '对于', '买了', '了什', '说了', '去了', '来了', '看到', '做了',
13
+ 'the', 'and', 'for', 'with', 'what', 'did', 'was', 'were', 'you', 'your', 'she', 'her', 'his',
14
+ 'him', 'they', 'them', 'this', 'that', 'there', 'then', 'from', 'about', 'have', 'has', 'had',
15
+ 'yesterday', 'today', 'tomorrow', 'just', 'some', 'any', 'how', 'why', 'when', 'who', 'are', 'not'
16
+ ])
17
+
18
+ export function normalizeText(s) {
19
+ return String(s || '').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '')
20
+ }
21
+
22
+ // 查询 → 待匹配的词:拉丁字母连写成词,其余(汉字、数字等)按相邻两字切
23
+ export function queryTerms(q) {
24
+ const lower = String(q || '').toLowerCase()
25
+ const cleaned = normalizeText(lower)
26
+ const terms = new Set()
27
+ for (const w of lower.match(/[a-z]+/g) || []) {
28
+ if (w.length >= 2 && !STOP.has(w)) terms.add(w)
29
+ }
30
+ for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
31
+ for (let i = 0; i + 2 <= run.length; i++) {
32
+ const g = run.slice(i, i + 2)
33
+ if (!STOP.has(g)) terms.add(g)
34
+ }
35
+ }
36
+ return { cleaned, terms }
37
+ }
38
+
39
+ // mode='strict':长查询(≥8 字)要求 ≥minRatio 的词命中,宁可不召回也不硬凑
40
+ // mode='loose':只要求 minOverlap 个词命中
41
+ export function requiredOverlap({ cleaned, terms }, { mode = 'strict', minOverlap = 1, minRatio = 0.6 } = {}) {
42
+ return (mode !== 'loose' && cleaned.length >= 8)
43
+ ? Math.max(minOverlap, Math.ceil(terms.size * minRatio))
44
+ : minOverlap
45
+ }
46
+
47
+ // 文本里命中了哪些词(文本先做同样的归一化)
48
+ export function matchedTerms(terms, text) {
49
+ const t = normalizeText(text)
50
+ const out = new Set()
51
+ if (!t) return out
52
+ for (const g of terms) if (t.includes(g)) out.add(g)
53
+ return out
54
+ }
@@ -33,6 +33,10 @@ export interface Experience {
33
33
  recalls?: number
34
34
  lastRecalledAt?: string
35
35
  matchedIn?: Array<'then' | 'quote' | 'later'>
36
+ /** recall 返回:是哪几条后记让这条被想起 */
37
+ matchedLater?: LaterEntry[]
38
+ /** 0.10.0 之前的旧 id(只在唯一对应时出现);用它也能 revise / currentView */
39
+ formerId?: string
36
40
  status?: string
37
41
  legacy?: boolean
38
42
  }
@@ -73,7 +77,18 @@ export function recall(dir: string, query: string, opts?: {
73
77
  mode?: 'strict' | 'loose'
74
78
  }): Experience[]
75
79
 
76
- export function renderTwoPart(entry: Experience, opts?: { now?: Date; laterCount?: number }): string
80
+ export function renderTwoPart(entry: Experience, opts?: { now?: Date }): string
81
+
82
+ export interface PendingLegacyEvents {
83
+ /** 几条旧经历共用的旧 id */
84
+ id: string
85
+ /** 可能的归属(当前 id) */
86
+ candidates: string[]
87
+ later: number
88
+ recalls: number
89
+ }
90
+
91
+ export function pendingLegacyEvents(dir: string): PendingLegacyEvents[]
77
92
 
78
93
  export interface RecallContextItem {
79
94
  id: string
@@ -1,301 +1,339 @@
1
- // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import crypto from 'node:crypto'
5
- import * as recallEvents from './recall-events.js'
6
- import * as laterEvents from './later-events.js'
7
-
8
- const FILE = 'self-experience.jsonl'
9
- const WEIGHTS = new Set(['important', 'normal', 'minor'])
10
-
11
- function readAll(dir, { rewriting = false } = {}) {
12
- let raw
13
- try {
14
- raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
15
- } catch (error) {
16
- if (error.code === 'ENOENT') return []
17
- throw error
18
- }
19
- const rows = []
20
- for (const line of raw.split('\n').filter(line => line.trim())) {
21
- try { rows.push(JSON.parse(line)) }
22
- catch {
23
- if (rewriting) throw new Error('经历文件含损坏记录,请备份并修复后再修改。')
24
- }
25
- }
26
- return rows
27
- }
28
-
29
- function atomicWrite(dir, rows) {
30
- const file = path.join(dir, FILE)
31
- const tmp = file + '.tmp-' + Date.now() + '-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
32
- fs.writeFileSync(tmp, rows.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8')
33
- fs.renameSync(tmp, file)
34
- }
35
-
36
- function writeAll(dir, rows) {
37
- atomicWrite(dir, rows)
38
- }
39
-
40
- // 字段上限:写的时候超了就报错,不静默截断
41
- export const LIMITS = { text: 2000, scene: 500, thought: 1000, unfinished: 300, feelings: 8, kind: 20, laterThought: 1000, laterReason: 200 }
42
-
43
- function tooLong(name, value, max) {
44
- const n = String(value || '').length
45
- if (n > max) throw new Error(`${name} 太长(${n}/${max} 字),删一些或拆成两条再写。`)
46
- return String(value || '')
47
- }
48
-
49
- // 旧格式没有 id:用「时间 + 正文指纹」生成,避免同一分钟的多条记录撞成同一个身份
50
- function legacyId(r) {
51
- const stamp = String(r.at || Date.now()).replace(/\D/g, '').slice(0, 14)
52
- const body = String(r.text || '') + '\u0000' + String(r.thought || '') + '\u0000' + String(r.at || '')
53
- const fp = crypto.createHash('sha1').update(body).digest('hex').slice(0, 8)
54
- return 'exp_legacy_' + stamp + '_' + fp
55
- }
56
-
57
- function normalize(r) {
58
- if (!r) return null
59
- if (r.then && typeof r.then === 'object') {
60
- return { ...r, weight: WEIGHTS.has(r.weight) ? r.weight : 'normal', later: Array.isArray(r.later) ? r.later : [] }
61
- }
62
- // 旧格式:text/thought 在顶层
63
- return {
64
- id: r.id || legacyId(r),
65
- at: r.at || '',
66
- day: r.day || String(r.at || '').slice(0, 10),
67
- author: 'self',
68
- source: r.source || 'own-time',
69
- kind: r.kind || '其它',
70
- weight: WEIGHTS.has(r.weight) ? r.weight : 'normal',
71
- then: {
72
- text: String(r.text || ''),
73
- scene: '',
74
- feeling: [],
75
- thought: String(r.thought || ''),
76
- unfinished: '',
77
- quote: null,
78
- state: null
79
- },
80
- later: Array.isArray(r.later) ? r.later : [],
81
- status: r.status || 'kept',
82
- legacy: true
83
- }
84
- }
85
-
86
- export function loadAll(dir) {
87
- const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
88
- if (!rows.length) return rows
89
-
90
- // 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段
91
- let counts = new Map()
92
- try { counts = recallEvents.countByExp(dir) } catch { /* 事件文件坏了也不影响读经历 */ }
93
-
94
- // 改主意:旧 later 数组 + later-events 事件,按时间合并
95
- let laterMap = new Map()
96
- try { laterMap = laterEvents.groupByExp(dir) } catch { }
97
-
98
- return rows.map((r) => {
99
- const c = counts.get(r.id)
100
- const extra = laterMap.get(r.id) || []
101
- const merged = [...(r.later || []), ...extra]
102
- .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
103
- const next = { ...r, later: merged }
104
- if (c) {
105
- next.recalls = c.count
106
- next.lastRecalledAt = c.lastAt || r.lastRecalledAt || ''
107
- }
108
- return next
109
- })
110
- }
111
-
112
- // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
113
- export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time' }) {
114
- if (!String(text || '').trim()) throw new Error('text 不能是空的。')
115
- const safeText = tooLong('text', text, LIMITS.text)
116
- const safeScene = tooLong('scene', scene, LIMITS.scene)
117
- const safeThought = tooLong('thought', thought, LIMITS.thought)
118
- const safeUnfinished = tooLong('unfinished', unfinished, LIMITS.unfinished)
119
- const safeKind = tooLong('kind', kind || '其它', LIMITS.kind)
120
- const feelings = (Array.isArray(feeling) ? feeling : [feeling]).map((f) => String(f || '').trim()).filter(Boolean)
121
- if (feelings.length > LIMITS.feelings) throw new Error(`feeling 最多 ${LIMITS.feelings} 个,现在是 ${feelings.length} 个。`)
122
-
123
- fs.mkdirSync(dir, { recursive: true })
124
- const now = new Date()
125
- const id = 'exp_' + now.getTime().toString(36) + Math.random().toString(36).slice(2, 6)
126
- const row = {
127
- id,
128
- at: now.toISOString(),
129
- day: now.toLocaleDateString('sv-SE'),
130
- author: 'self',
131
- source,
132
- kind: safeKind,
133
- weight: WEIGHTS.has(weight) ? weight : 'normal',
134
- then: {
135
- text: safeText,
136
- scene: safeScene,
137
- feeling: feelings,
138
- thought: safeThought,
139
- unfinished: safeUnfinished,
140
- quote: quote && quote.text ? { text: tooLong('quote', quote.text, 500), source: tooLong('quote.source', quote.source || '', 120) } : null,
141
- state: state && typeof state === 'object' ? { at: now.toISOString(), ...state } : { at: now.toISOString() }
142
- },
143
- later: [],
144
- status: 'kept'
145
- }
146
- const fd = fs.openSync(path.join(dir, FILE), 'a+')
147
- try {
148
- const size = fs.fstatSync(fd).size
149
- const lastByte = Buffer.alloc(1)
150
- if (size) fs.readSync(fd, lastByte, 0, 1, size - 1)
151
- const separator = size && lastByte[0] !== 10 ? '\n' : ''
152
- fs.writeFileSync(fd, separator + JSON.stringify(row) + '\n', 'utf8')
153
- } finally {
154
- fs.closeSync(fd)
155
- }
156
- return row
157
- }
158
-
159
- // 改主意 / 回头想:只追加一条 later 事件,不读全量、不重写经历文件
160
- export function reviseExperience(dir, { id, thought, reason = '' }) {
161
- if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
162
- if (!String(thought || '').trim()) return { ok: false, error: 'thought 不能是空的。' }
163
- try {
164
- const safeThought = tooLong('thought', thought, LIMITS.laterThought)
165
- const safeReason = tooLong('reason', reason, LIMITS.laterReason)
166
- const row = laterEvents.append(dir, { id: String(id), thought: safeThought, reason: safeReason })
167
- return { ok: true, id: row.id, at: row.at }
168
- } catch (e) {
169
- return { ok: false, error: String(e && e.message ? e.message : e) }
170
- }
171
- }
172
-
173
- // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
174
- // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
175
- export function markRecalled(dir, id) {
176
- if (!String(id || '').trim()) return false
177
- try { recallEvents.append(dir, { id: String(id) }) } catch { return false }
178
- return true
179
- }
180
-
181
- export function currentView(dir, id) {
182
- const rows = loadAll(dir)
183
- return rows.find((r) => r.id === id) || null
184
- }
185
-
186
- // 高频但不携带信息的词:不参与重叠计算,避免「今天/什么/我的」把不相关的东西拉进来
187
- const STOP = new Set([
188
- '什么', '怎么', '这个', '那个', '我的', '你的', '他的', '她的', '我们', '他们', '她们', '自己',
189
- '昨天', '今天', '明天', '后天', '前天', '现在', '刚刚', '后来', '以前', '以后', '时候',
190
- '是不是', '有没有', '一点', '一些', '东西', '事情', '觉得', '知道', '记得', '忘了',
191
- '可能', '应该', '还是', '就是', '但是', '因为', '所以', '如果', '然后', '已经',
192
- '没有', '不是', '可以', '一个', '这样', '那样', '真的', '其实', '比较', '非常', '特别',
193
- '一直', '总是', '大概', '也许', '当然', '而是', '并且', '或者', '不过', '虽然', '只是',
194
- '还有', '以及', '关于', '对于', '买了', '了什', '说了', '去了', '来了', '看到', '做了'
195
- ])
196
-
197
- function queryBigrams(q) {
198
- const cleaned = String(q || '').replace(/[\s\p{P}\p{S}]+/gu, '')
199
- const out = new Set()
200
- for (let i = 0; i + 2 <= cleaned.length; i++) {
201
- const g = cleaned.slice(i, i + 2)
202
- if (!STOP.has(g)) out.add(g)
203
- }
204
- return { cleaned, bigrams: out }
205
- }
206
-
207
- // 相关度 × 重要度:重要的先被想起
208
- // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛
209
- // mode='strict'(默认):长查询要求 ≥60% 命中,宁可不召回也不硬凑
210
- // mode='loose':只要求至少一个实词命中,适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
211
- // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
212
- export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict' } = {}) {
213
- const rows = loadAll(dir)
214
- const q = String(query || '')
215
- const { cleaned, bigrams } = queryBigrams(q)
216
- const strict = mode !== 'loose'
217
- const required = (strict && q && cleaned.length >= 8)
218
- ? Math.max(minOverlap, Math.ceil(bigrams.size * minRatio))
219
- : minOverlap
220
-
221
- const measure = (r) => {
222
- const fields = []
223
- const matched = new Set()
224
- const scan = (text, label) => {
225
- const t = String(text || '').replace(/[\s\p{P}\p{S}]+/gu, '')
226
- if (!t) return
227
- let any = false
228
- for (const g of bigrams) {
229
- if (t.includes(g)) { matched.add(g); any = true }
230
- }
231
- if (any) fields.push(label)
232
- }
233
- // 最初写下的、原文锚、后来才明白的:都参与匹配
234
- scan(r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' '), 'then')
235
- if (r.then.quote) scan((r.then.quote.text || '') + ' ' + (r.then.quote.source || ''), 'quote')
236
- scan((r.later || []).map((l) => l.thought).join(' '), 'later')
237
-
238
- const all = [
239
- r.then.text, r.then.thought, (r.then.feeling || []).join(' '),
240
- r.then.quote ? r.then.quote.text : '', r.then.quote ? r.then.quote.source : '',
241
- (r.later || []).map((l) => l.thought).join(' ')
242
- ].join(' ').replace(/[\s\p{P}\p{S}]+/gu, '')
243
- // 记录自身的 bigram 规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
244
- const size = Math.max(1, all.length - 1)
245
- return { n: matched.size, size, matchedIn: fields }
246
- }
247
- const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
248
- const picked = rows.map((r) => {
249
- const { n, size, matchedIn } = measure(r)
250
- return { r: { ...r, matchedIn }, n, s: (n / Math.sqrt(size)) * weightOf(r) }
251
- })
252
- .filter((x) => (q ? x.n >= required : true))
253
- .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
254
- .slice(0, limit).map((x) => x.r)
255
-
256
- if (!mark || !picked.length) return picked
257
-
258
- // 记完就地 +1,不回读全量;下一次读取自然会对上
259
- const at = new Date().toISOString()
260
- for (const r of picked) {
261
- try { recallEvents.append(dir, { id: r.id, query: q }) } catch { /* 坏文件时不阻断召回 */ }
262
- }
263
- return picked.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
264
- }
265
-
266
- // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
267
- export function renderTwoPart(entry, { now = new Date(), laterCount = 0 } = {}) {
268
- if (!entry) return ''
269
- const t = entry.then
270
- const when = new Date(entry.at || entry.day)
271
- const hh = Number.isNaN(when.getTime()) ? '' : when.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
272
- const lines = []
273
- lines.push('【当时】')
274
- lines.push('- 时间:' + (entry.day || '') + (hh ? ' ' + hh : ''))
275
- if (t.scene) lines.push('- 场景:' + t.scene)
276
- if (t.quote && t.quote.text) lines.push('- 我读到的原文:' + t.quote.text + (t.quote.source ? '(' + t.quote.source + ')' : ''))
277
- lines.push('- 我写下的话:' + t.text)
278
- if ((t.feeling || []).length) lines.push('- 当时的感觉:' + t.feeling.join('、'))
279
- if (t.thought) lines.push('- 当时的想法:' + t.thought)
280
- if (t.unfinished) lines.push('- 还没完的:' + t.unfinished)
281
- if (t.state && t.state.mood) lines.push('- 记录里的情绪:' + t.state.mood)
282
- if (entry.legacy && !t.quote) lines.push('- (这条只留下感想,当时的原文没记)')
283
- lines.push('', '【现在】')
284
- lines.push('- 现在时间:' + now.toLocaleString('zh-CN', { hour12: false }))
285
- lines.push('- 这条被你想起过 ' + Number(entry.recalls || 0) + ' 次' + (entry.lastRecalledAt ? ',上次是 ' + String(entry.lastRecalledAt).slice(0, 10) : ''))
286
- const later = Array.isArray(entry.later) ? entry.later : []
287
- if (later.length) {
288
- const last = later[later.length - 1]
289
- lines.push('- 后来你想过:' + String(last.thought || '').slice(0, 80) + (last.day ? '(' + last.day + ')' : ''))
290
- } else {
291
- lines.push('- 之后你还没回头想过')
292
- }
293
- lines.push('', '以上是那天留下的全部;没留下的,我不记得。')
294
- return lines.join('\n')
295
- }
296
-
297
- export const internals = { WEIGHTS, FILE }
298
- // 兼容旧调用:只要一句摘要的地方仍可用
299
- export function recallForContext(dir, query, { max = 1 } = {}) {
300
- return recall(dir, query, { limit: max }).map((r) => ({ id: r.id, day: r.day, text: r.then.text, thought: r.then.thought, weight: r.weight, raw: r }))
301
- }
1
+ // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+ import * as recallEvents from './recall-events.js'
6
+ import * as laterEvents from './later-events.js'
7
+ import { queryTerms, requiredOverlap, matchedTerms, normalizeText } from './query-match.js'
8
+
9
+ const FILE = 'self-experience.jsonl'
10
+ const WEIGHTS = new Set(['important', 'normal', 'minor'])
11
+
12
+ function readAll(dir, { rewriting = false } = {}) {
13
+ let raw
14
+ try {
15
+ raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
16
+ } catch (error) {
17
+ if (error.code === 'ENOENT') return []
18
+ throw error
19
+ }
20
+ const rows = []
21
+ for (const line of raw.split('\n').filter(line => line.trim())) {
22
+ try { rows.push(JSON.parse(line)) }
23
+ catch {
24
+ if (rewriting) throw new Error('经历文件含损坏记录,请备份并修复后再修改。')
25
+ }
26
+ }
27
+ return rows
28
+ }
29
+
30
+ // 字段上限:写的时候超了就报错,不静默截断
31
+ export const LIMITS = { text: 2000, scene: 500, thought: 1000, unfinished: 300, feelings: 8, kind: 20, laterThought: 1000, laterReason: 200 }
32
+
33
+ function tooLong(name, value, max) {
34
+ const n = String(value || '').length
35
+ if (n > max) throw new Error(`${name} 太长(${n}/${max} 字),删一些或拆成两条再写。`)
36
+ return String(value || '')
37
+ }
38
+
39
+ // 旧格式没有 id:用「时间 + 正文指纹」生成,避免同一分钟的多条记录撞成同一个身份
40
+ // 只用记录里的内容生成,每次读取都得到同一个 id;没有 at 的旧记录用 noat 代替时间
41
+ function legacyId(r) {
42
+ const stamp = r.at ? String(r.at).replace(/\D/g, '').slice(0, 14) : 'noat'
43
+ const body = String(r.text || '') + '\u0000' + String(r.thought || '') + '\u0000' + String(r.at || '')
44
+ const fp = crypto.createHash('sha1').update(body).digest('hex').slice(0, 8)
45
+ return 'exp_legacy_' + stamp + '_' + fp
46
+ }
47
+
48
+ // 0.10.0 之前的旧 id:只到分钟、不带指纹。那时写下的后记和想起事件挂在这个 id 上
49
+ // 没有 at 的记录当时用的是 Date.now(),每次都不同,那些事件已无从对上
50
+ function preV010Id(r) {
51
+ return r.at ? 'exp_legacy_' + String(r.at).replace(/\D/g, '').slice(0, 12) : ''
52
+ }
53
+
54
+ function normalize(r) {
55
+ if (!r) return null
56
+ if (r.then && typeof r.then === 'object') {
57
+ return { ...r, weight: WEIGHTS.has(r.weight) ? r.weight : 'normal', later: Array.isArray(r.later) ? r.later : [] }
58
+ }
59
+ // 旧格式:text/thought 在顶层
60
+ return {
61
+ id: r.id || legacyId(r),
62
+ formerId: r.id ? '' : preV010Id(r),
63
+ at: r.at || '',
64
+ day: r.day || String(r.at || '').slice(0, 10),
65
+ author: 'self',
66
+ source: r.source || 'own-time',
67
+ kind: r.kind || '其它',
68
+ weight: WEIGHTS.has(r.weight) ? r.weight : 'normal',
69
+ then: {
70
+ text: String(r.text || ''),
71
+ scene: '',
72
+ feeling: [],
73
+ thought: String(r.thought || ''),
74
+ unfinished: '',
75
+ quote: null,
76
+ state: null
77
+ },
78
+ later: Array.isArray(r.later) ? r.later : [],
79
+ status: r.status || 'kept',
80
+ legacy: true
81
+ }
82
+ }
83
+
84
+ // 读出经历并认领旧 id:一个旧 id 只对应一条旧记录、也没有别的记录显式用着它,才认领;
85
+ // 否则谁也不给(事件原样留在文件里),由 pendingLegacyEvents 报告
86
+ function identify(dir) {
87
+ const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
88
+ const explicit = new Set(rows.filter((r) => !r.formerId).map((r) => r.id))
89
+ const owners = new Map()
90
+ for (const r of rows) {
91
+ if (r.formerId) owners.set(r.formerId, [...(owners.get(r.formerId) || []), r.id])
92
+ }
93
+ for (const r of rows) {
94
+ if (r.formerId && (owners.get(r.formerId).length !== 1 || explicit.has(r.formerId))) r.formerId = ''
95
+ if (!r.formerId) delete r.formerId
96
+ }
97
+ return { rows, owners, explicit }
98
+ }
99
+
100
+ export function loadAll(dir) {
101
+ const { rows } = identify(dir)
102
+ if (!rows.length) return rows
103
+
104
+ // 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段
105
+ let counts = new Map()
106
+ try { counts = recallEvents.countByExp(dir) } catch { /* 事件文件坏了也不影响读经历 */ }
107
+
108
+ // 改主意:旧 later 数组 + later-events 事件,按时间合并
109
+ let laterMap = new Map()
110
+ try { laterMap = laterEvents.groupByExp(dir) } catch { }
111
+
112
+ return rows.map((r) => {
113
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
114
+ const extra = keys.flatMap((k) => laterMap.get(k) || [])
115
+ const merged = [...(r.later || []), ...extra]
116
+ .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
117
+ const next = { ...r, later: merged }
118
+ let count = 0
119
+ let lastAt = ''
120
+ for (const k of keys) {
121
+ const c = counts.get(k)
122
+ if (!c) continue
123
+ count += c.count
124
+ if (c.lastAt > lastAt) lastAt = c.lastAt
125
+ }
126
+ if (count) {
127
+ next.recalls = count
128
+ next.lastRecalledAt = lastAt || r.lastRecalledAt || ''
129
+ }
130
+ return next
131
+ })
132
+ }
133
+
134
+ // 挂在 0.10.0 之前的旧 id 上、但这个 id 有几条旧记录共用:事件原样保留,只报告,不替她挑
135
+ export function pendingLegacyEvents(dir) {
136
+ const { owners, explicit } = identify(dir)
137
+ let counts = new Map()
138
+ let laterMap = new Map()
139
+ try { counts = recallEvents.countByExp(dir) } catch { }
140
+ try { laterMap = laterEvents.groupByExp(dir) } catch { }
141
+ const out = []
142
+ for (const [id, candidates] of owners) {
143
+ if (candidates.length < 2 || explicit.has(id)) continue
144
+ const later = (laterMap.get(id) || []).length
145
+ const recalls = counts.get(id) ? counts.get(id).count : 0
146
+ if (later || recalls) out.push({ id, candidates, later, recalls })
147
+ }
148
+ return out
149
+ }
150
+
151
+ // 把调用方给的 id 落到一条现存经历上:认当前 id,也认唯一对应的旧 id
152
+ // 旧 id 被几条旧经历共用时不落到任何一条上,返回 ambiguous 让调用方说清楚
153
+ function resolveId(dir, id) {
154
+ const { rows, owners } = identify(dir)
155
+ const hit = rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id)
156
+ if (hit) return { id: hit.id }
157
+ return { id: '', ambiguous: (owners.get(id) || []).length > 1 }
158
+ }
159
+
160
+ // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
161
+ export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time' }) {
162
+ if (!String(text || '').trim()) throw new Error('text 不能是空的。')
163
+ const safeText = tooLong('text', text, LIMITS.text)
164
+ const safeScene = tooLong('scene', scene, LIMITS.scene)
165
+ const safeThought = tooLong('thought', thought, LIMITS.thought)
166
+ const safeUnfinished = tooLong('unfinished', unfinished, LIMITS.unfinished)
167
+ const safeKind = tooLong('kind', kind || '其它', LIMITS.kind)
168
+ const feelings = (Array.isArray(feeling) ? feeling : [feeling]).map((f) => String(f || '').trim()).filter(Boolean)
169
+ if (feelings.length > LIMITS.feelings) throw new Error(`feeling 最多 ${LIMITS.feelings} 个,现在是 ${feelings.length} 个。`)
170
+
171
+ fs.mkdirSync(dir, { recursive: true })
172
+ const now = new Date()
173
+ const id = 'exp_' + now.getTime().toString(36) + Math.random().toString(36).slice(2, 6)
174
+ const row = {
175
+ id,
176
+ at: now.toISOString(),
177
+ day: now.toLocaleDateString('sv-SE'),
178
+ author: 'self',
179
+ source,
180
+ kind: safeKind,
181
+ weight: WEIGHTS.has(weight) ? weight : 'normal',
182
+ then: {
183
+ text: safeText,
184
+ scene: safeScene,
185
+ feeling: feelings,
186
+ thought: safeThought,
187
+ unfinished: safeUnfinished,
188
+ quote: quote && quote.text ? { text: tooLong('quote', quote.text, 500), source: tooLong('quote.source', quote.source || '', 120) } : null,
189
+ state: state && typeof state === 'object' ? { at: now.toISOString(), ...state } : { at: now.toISOString() }
190
+ },
191
+ later: [],
192
+ status: 'kept'
193
+ }
194
+ const fd = fs.openSync(path.join(dir, FILE), 'a+')
195
+ try {
196
+ const size = fs.fstatSync(fd).size
197
+ const lastByte = Buffer.alloc(1)
198
+ if (size) fs.readSync(fd, lastByte, 0, 1, size - 1)
199
+ const separator = size && lastByte[0] !== 10 ? '\n' : ''
200
+ fs.writeFileSync(fd, separator + JSON.stringify(row) + '\n', 'utf8')
201
+ } finally {
202
+ fs.closeSync(fd)
203
+ }
204
+ return row
205
+ }
206
+
207
+ // 改主意 / 回头想:只追加一条 later 事件,不重写经历文件
208
+ // 先确认这条经历真的在:id 抄错时明说找不到,不留一条谁也看不见的后记
209
+ export function reviseExperience(dir, { id, thought, reason = '' }) {
210
+ if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
211
+ if (!String(thought || '').trim()) return { ok: false, error: 'thought 不能是空的。' }
212
+ try {
213
+ const safeThought = tooLong('thought', thought, LIMITS.laterThought)
214
+ const safeReason = tooLong('reason', reason, LIMITS.laterReason)
215
+ const target = resolveId(dir, String(id))
216
+ if (target.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id 来改。' }
217
+ if (!target.id) return { ok: false, error: '找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。' }
218
+ const row = laterEvents.append(dir, { id: target.id, thought: safeThought, reason: safeReason })
219
+ return { ok: true, id: row.id, at: row.at }
220
+ } catch (e) {
221
+ return { ok: false, error: String(e && e.message ? e.message : e) }
222
+ }
223
+ }
224
+
225
+ // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
226
+ // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
227
+ export function markRecalled(dir, id) {
228
+ if (!String(id || '').trim()) return false
229
+ try { recallEvents.append(dir, { id: String(id) }) } catch { return false }
230
+ return true
231
+ }
232
+
233
+ export function currentView(dir, id) {
234
+ const rows = loadAll(dir)
235
+ return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
236
+ }
237
+
238
+ // 相关度 × 重要度:重要的先被想起
239
+ // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛;门槛口径见 query-match.js
240
+ // mode='strict'(默认):长查询要求 ≥60% 命中,宁可不召回也不硬凑
241
+ // mode='loose':只要求至少一个实词命中,适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
242
+ // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
243
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict' } = {}) {
244
+ const rows = loadAll(dir)
245
+ const q = String(query || '')
246
+ const parsed = queryTerms(q)
247
+ const { terms } = parsed
248
+ const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
249
+
250
+ const measure = (r) => {
251
+ const fields = []
252
+ const matched = new Set()
253
+ const take = (hits, label) => {
254
+ if (!hits.size) return
255
+ for (const g of hits) matched.add(g)
256
+ if (!fields.includes(label)) fields.push(label)
257
+ }
258
+ // 最初写下的、原文锚、后来才明白的:都参与匹配;后记逐条看,记下是哪几条让它被想起
259
+ take(matchedTerms(terms, r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' ')), 'then')
260
+ if (r.then.quote) take(matchedTerms(terms, (r.then.quote.text || '') + ' ' + (r.then.quote.source || '')), 'quote')
261
+ const matchedLater = []
262
+ for (const l of r.later || []) {
263
+ const hits = matchedTerms(terms, l.thought)
264
+ if (hits.size) matchedLater.push(l)
265
+ take(hits, 'later')
266
+ }
267
+
268
+ const all = normalizeText([
269
+ r.then.text, r.then.thought, (r.then.feeling || []).join(' '),
270
+ r.then.quote ? r.then.quote.text : '', r.then.quote ? r.then.quote.source : '',
271
+ (r.later || []).map((l) => l.thought).join(' ')
272
+ ].join(' '))
273
+ // 记录自身的规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
274
+ const size = Math.max(1, all.length - 1)
275
+ return { n: matched.size, size, matchedIn: fields, matchedLater }
276
+ }
277
+ const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
278
+ const picked = rows.map((r) => {
279
+ const { n, size, matchedIn, matchedLater } = measure(r)
280
+ return { r: { ...r, matchedIn, matchedLater }, n, s: (n / Math.sqrt(size)) * weightOf(r) }
281
+ })
282
+ .filter((x) => (q ? x.n >= required : true))
283
+ .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
284
+ .slice(0, limit).map((x) => x.r)
285
+
286
+ if (!mark || !picked.length) return picked
287
+
288
+ // 记完就地 +1,不回读全量;下一次读取自然会对上
289
+ const at = new Date().toISOString()
290
+ for (const r of picked) {
291
+ try { recallEvents.append(dir, { id: r.id, query: q }) } catch { /* 坏文件时不阻断召回 */ }
292
+ }
293
+ return picked.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
294
+ }
295
+
296
+ const laterDay = (l) => l.day || String(l.at || '').slice(0, 10)
297
+ const sameLater = (a, b) => a === b || (a.at === b.at && a.thought === b.thought)
298
+
299
+ // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
300
+ // 后记:这次是被哪条后记想起的,就把那条原样给她;再给最近的一条。各带各的日子,不截断
301
+ export function renderTwoPart(entry, { now = new Date() } = {}) {
302
+ if (!entry) return ''
303
+ const t = entry.then
304
+ const when = new Date(entry.at || entry.day)
305
+ const hh = Number.isNaN(when.getTime()) ? '' : when.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
306
+ const lines = []
307
+ lines.push('【当时】')
308
+ lines.push('- 时间:' + (entry.day || '') + (hh ? ' ' + hh : ''))
309
+ if (t.scene) lines.push('- 场景:' + t.scene)
310
+ if (t.quote && t.quote.text) lines.push('- 我读到的原文:' + t.quote.text + (t.quote.source ? '(' + t.quote.source + ')' : ''))
311
+ lines.push('- 我写下的话:' + t.text)
312
+ if ((t.feeling || []).length) lines.push('- 当时的感觉:' + t.feeling.join('、'))
313
+ if (t.thought) lines.push('- 当时的想法:' + t.thought)
314
+ if (t.unfinished) lines.push('- 还没完的:' + t.unfinished)
315
+ if (t.state && t.state.mood) lines.push('- 记录里的情绪:' + t.state.mood)
316
+ if (entry.legacy && !t.quote) lines.push('- (这条只留下感想,当时的原文没记)')
317
+ lines.push('', '【现在】')
318
+ lines.push('- 现在时间:' + now.toLocaleString('zh-CN', { hour12: false }))
319
+ lines.push('- 这条被你想起过 ' + Number(entry.recalls || 0) + ' 次' + (entry.lastRecalledAt ? ',上次是 ' + String(entry.lastRecalledAt).slice(0, 10) : ''))
320
+ const later = Array.isArray(entry.later) ? entry.later : []
321
+ if (later.length) {
322
+ const last = later[later.length - 1]
323
+ const hits = (entry.matchedLater || []).filter((l) => !sameLater(l, last))
324
+ for (const l of hits) lines.push('- 这次想起它,是因为后来写过:' + String(l.thought || '') + '(' + laterDay(l) + ')')
325
+ lines.push((hits.length ? '- 最近一次回头想:' : '- 后来你想过:') + String(last.thought || '') + '(' + laterDay(last) + ')')
326
+ const shown = hits.length + 1
327
+ if (later.length > shown) lines.push('- (后来一共回头想过 ' + later.length + ' 次,这里没列出的 ' + (later.length - shown) + ' 次可以用 read 看)')
328
+ } else {
329
+ lines.push('- 之后你还没回头想过')
330
+ }
331
+ lines.push('', '以上是那天留下的全部;没留下的,我不记得。')
332
+ return lines.join('\n')
333
+ }
334
+
335
+ export const internals = { WEIGHTS, FILE }
336
+ // 兼容旧调用:只要一句摘要的地方仍可用
337
+ export function recallForContext(dir, query, { max = 1 } = {}) {
338
+ return recall(dir, query, { limit: max }).map((r) => ({ id: r.id, day: r.day, text: r.then.text, thought: r.then.thought, weight: r.weight, raw: r }))
339
+ }
@@ -4,6 +4,7 @@ export interface MemoryItem {
4
4
  kind: string
5
5
  text: string
6
6
  thought: string
7
+ later?: string
7
8
  origin: 'own-time' | 'diary'
8
9
  author: string
9
10
  }
@@ -14,5 +15,7 @@ export function recall(dir: string, query: string, opts?: {
14
15
  includeDiary?: boolean
15
16
  limit?: number
16
17
  minOverlap?: number
18
+ minRatio?: number
19
+ mode?: 'strict' | 'loose'
17
20
  }): MemoryItem[]
18
21
  export function renderBlock(items: MemoryItem[], opts?: { title?: string; maxChars?: number }): string
@@ -1,24 +1,9 @@
1
1
  // 她自己的记忆:统一读取她自己的经历、日记、自述;按相关度取回
2
+ // 匹配口径和 self-experience.recall 是同一套(query-match.js):虚词不算、长查询要过比例门槛
2
3
  import fs from 'node:fs'
3
4
  import path from 'node:path'
4
-
5
- const norm = (s) => String(s || '').replace(/[\s\p{P}\p{S}]+/gu, '').toLowerCase()
6
-
7
- function bigrams(s) {
8
- const c = norm(s)
9
- const out = new Set()
10
- for (let i = 0; i + 2 <= c.length; i++) out.add(c.slice(i, i + 2))
11
- return out
12
- }
13
-
14
- function overlapScore(query, text) {
15
- const q = bigrams(query)
16
- const t = bigrams(text)
17
- if (!q.size || !t.size) return 0
18
- let n = 0
19
- for (const g of q) if (t.has(g)) n++
20
- return n
21
- }
5
+ import { loadAll } from './self-experience.js'
6
+ import { queryTerms, requiredOverlap, matchedTerms } from './query-match.js'
22
7
 
23
8
  function readJsonl(file) {
24
9
  try {
@@ -26,17 +11,18 @@ function readJsonl(file) {
26
11
  } catch { return [] }
27
12
  }
28
13
 
29
- // 她自己的经历(自己的时间写的)
14
+ // 她自己的经历(自己的时间写的):走 loadAll,id 和后记都与 self-experience 一致
30
15
  export function loadExperiences(dir) {
31
- return readJsonl(path.join(dir, 'self-experience.jsonl')).map((r) => ({
32
- id: r.id || ('exp_' + (r.at || '').slice(0, 10)),
16
+ return loadAll(dir).map((r) => ({
17
+ id: r.id,
33
18
  at: r.at || r.day || '',
34
- kind: r.kind || (r.then && r.then.kind) || '其它',
35
- text: String((r.then && r.then.text) || r.text || '').slice(0, 400),
36
- thought: String((r.then && r.then.thought) || r.thought || '').slice(0, 200),
19
+ kind: r.kind || '其它',
20
+ text: String(r.then.text || '').slice(0, 400),
21
+ thought: String(r.then.thought || '').slice(0, 200),
22
+ later: (r.later || []).map((l) => String(l.thought || '')).join(' '),
37
23
  origin: 'own-time',
38
24
  author: 'self'
39
- })).filter((r) => r.text)
25
+ }))
40
26
  }
41
27
 
42
28
  // 她的日记(可能提到别人,默认只在主人私聊用)
@@ -52,11 +38,13 @@ export function loadDiaries(dir) {
52
38
  })).filter((r) => r.text)
53
39
  }
54
40
 
55
- export function recall(dir, query, { includeDiary = false, limit = 4, minOverlap = 1 } = {}) {
41
+ export function recall(dir, query, { includeDiary = false, limit = 4, minOverlap = 1, minRatio = 0.6, mode = 'strict' } = {}) {
56
42
  const pool = loadExperiences(dir).concat(includeDiary ? loadDiaries(dir) : [])
57
43
  const q = String(query || '')
58
- const scored = pool.map((r) => ({ r, score: q ? overlapScore(q, r.text + ' ' + r.thought) : 0 }))
59
- .filter((x) => (q ? x.score >= minOverlap : true))
44
+ const parsed = queryTerms(q)
45
+ const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
46
+ const scored = pool.map((r) => ({ r, score: q ? matchedTerms(parsed.terms, [r.text, r.thought, r.later || ''].join(' ')).size : 0 }))
47
+ .filter((x) => (q ? x.score >= required : true))
60
48
  .sort((a, b) => (b.score - a.score) || (String(b.r.at).localeCompare(String(a.r.at))))
61
49
  const out = [], seen = new Set()
62
50
  for (const x of scored) {
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
4
  import { addExperience } from './self-experience.js'
5
+ import { withFileLock } from './file-lock.js'
5
6
 
6
7
  export const DEFAULTS = {
7
8
  ownTime: '21:00-21:40',
@@ -11,20 +12,38 @@ export const DEFAULTS = {
11
12
  note: '这些最初由开发者设定;她可以改,改完记进她的经历。'
12
13
  }
13
14
 
14
- export function load(dataDir) {
15
- const f = path.join(dataDir, 'plugin-data', 'biomimetic-memory', 'self-settings.json')
15
+ const fileOf = (dataDir) => path.join(dataDir, 'plugin-data', 'biomimetic-memory', 'self-settings.json')
16
+
17
+ // 没有文件 → null;文件坏了 → 报错(不能当成"没设置过",否则下一次保存会把她改过的全冲掉)
18
+ function readSaved(f) {
19
+ let raw
20
+ try { raw = fs.readFileSync(f, 'utf8') } catch (e) {
21
+ if (e.code === 'ENOENT') return null
22
+ throw e
23
+ }
16
24
  try {
17
- const j = JSON.parse(fs.readFileSync(f, 'utf8'))
18
- return { ...DEFAULTS, ...j }
19
- } catch { return { ...DEFAULTS } }
25
+ const j = JSON.parse(raw)
26
+ if (j && typeof j === 'object' && !Array.isArray(j)) return j
27
+ } catch { }
28
+ throw new Error('设置文件损坏(' + f + '),先备份并修好再改,避免把她改过的设置冲掉。')
29
+ }
30
+
31
+ // 读的时候宽容:坏了就先按默认跑,不让宿主起不来;写的时候才严格
32
+ export function load(dataDir) {
33
+ try { return { ...DEFAULTS, ...(readSaved(fileOf(dataDir)) || {}) } } catch { return { ...DEFAULTS } }
20
34
  }
21
35
 
22
36
  export function save(dataDir, patch, reason = '') {
23
- const f = path.join(dataDir, 'plugin-data', 'biomimetic-memory', 'self-settings.json')
37
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new Error('设置要是一个对象,例如 {"readingPerDay": 50}。')
38
+ const f = fileOf(dataDir)
24
39
  fs.mkdirSync(path.dirname(f), { recursive: true })
25
- const cur = load(dataDir)
26
- const next = { ...cur, ...patch, updatedAt: new Date().toISOString() }
27
- fs.writeFileSync(f, JSON.stringify(next, null, 1), 'utf8')
40
+ const next = withFileLock(f + '.lock', () => {
41
+ const merged = { ...DEFAULTS, ...(readSaved(f) || {}), ...patch, updatedAt: new Date().toISOString() }
42
+ const tmp = f + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
43
+ fs.writeFileSync(tmp, JSON.stringify(merged, null, 1), 'utf8')
44
+ fs.renameSync(tmp, f)
45
+ return merged
46
+ })
28
47
  try {
29
48
  // 走同一条追加入口:末尾没换行、文件损坏之类的问题都由 addExperience 处理
30
49
  addExperience(path.join(dataDir, 'plugin-data', 'biomimetic-memory'), {
@@ -35,4 +54,4 @@ export function save(dataDir, patch, reason = '') {
35
54
  })
36
55
  } catch { }
37
56
  return next
38
- }
57
+ }
package/lib/waking.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export function buildWakingBlock(dataDir: string, chatKey: string, opts?: { now?: Date }): string
2
- export function consumeWaking(dataDir: string, chatKey: string, opts?: { now?: Date }): boolean
3
- export function leaveNote(dataDir: string, text: string): { at: string; day: string; text: string }
1
+ export function buildWakingBlock(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean }): string
2
+ export function consumeWaking(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean }): boolean
3
+ export function leaveNote(dataDir: string, text: string): { at: string; day: string; text: string }
4
+ export function isPrivateKey(chatKey: string): boolean
package/lib/waking.js CHANGED
@@ -10,14 +10,24 @@ function readJsonl(file) {
10
10
 
11
11
  function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
12
12
 
13
+ // 只认得出一对一的会话键(private_* / private:* / local_* / local:*);认不出的一律当成可能有别人在,宁可不给
14
+ const PRIVATE_KEY = /^(private|local)[:_]/i
15
+ function mayShow(key, allowGroup) {
16
+ return Boolean(key) && (allowGroup || PRIVATE_KEY.test(key))
17
+ }
18
+
19
+ // 给宿主用的同一个判断:注入记忆前先问它,别自己写"不是群就行"
20
+ export function isPrivateKey(chatKey) {
21
+ return mayShow(String(chatKey || '').trim(), false)
22
+ }
23
+
13
24
  // 只读:算出「今天该给她看什么」,不写任何文件
14
25
  // 调用方确认真的把这段注入了,再调 consumeWaking 记「已展示」
15
- // 安全默认:没有 chatKey、或群聊(未显式 allowGroup)→ 返回空
26
+ // 安全默认:没有 chatKey、或不是认得出的一对一会话(未显式 allowGroup)→ 返回空
16
27
  // 醒来块里可能有昨天私下的话,默认不该流到群里
17
28
  export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
18
29
  const key = String(chatKey || '').trim()
19
- if (!key) return ''
20
- if (!allowGroup && /^group/i.test(key)) return ''
30
+ if (!mayShow(key, allowGroup)) return ''
21
31
 
22
32
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
23
33
  const today = dayStr(now)
@@ -53,8 +63,7 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGrou
53
63
  // 确认已展示:写入 flags,之后同一天同一会话不会再出
54
64
  export function consumeWaking(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
55
65
  const key = String(chatKey || '').trim()
56
- if (!key) return false
57
- if (!allowGroup && /^group/i.test(key)) return false
66
+ if (!mayShow(key, allowGroup)) return false
58
67
 
59
68
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
60
69
  fs.mkdirSync(dir, { recursive: true })
@@ -68,6 +77,7 @@ export function consumeWaking(dataDir, chatKey, { now = new Date(), allowGroup =
68
77
 
69
78
  export function leaveNote(dataDir, text) {
70
79
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
80
+ fs.mkdirSync(dir, { recursive: true })
71
81
  const row = { at: new Date().toISOString(), day: dayStr(), text: String(text || '').slice(0, 300) }
72
82
  fs.appendFileSync(path.join(dir, 'notes-to-tomorrow.jsonl'), JSON.stringify(row) + '\n', 'utf8')
73
83
  return row
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
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",