whale-memory-core 0.8.2 → 0.10.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.
@@ -32,6 +32,7 @@ export interface Experience {
32
32
  later: LaterEntry[]
33
33
  recalls?: number
34
34
  lastRecalledAt?: string
35
+ matchedIn?: Array<'then' | 'quote' | 'later'>
35
36
  status?: string
36
37
  legacy?: boolean
37
38
  }
@@ -69,6 +70,7 @@ export function recall(dir: string, query: string, opts?: {
69
70
  minOverlap?: number
70
71
  mark?: boolean
71
72
  minRatio?: number
73
+ mode?: 'strict' | 'loose'
72
74
  }): Experience[]
73
75
 
74
76
  export function renderTwoPart(entry: Experience, opts?: { now?: Date; laterCount?: number }): string
@@ -1,6 +1,7 @@
1
1
  // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
+ import crypto from 'node:crypto'
4
5
  import * as recallEvents from './recall-events.js'
5
6
  import * as laterEvents from './later-events.js'
6
7
 
@@ -45,6 +46,14 @@ function tooLong(name, value, max) {
45
46
  return String(value || '')
46
47
  }
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
+
48
57
  function normalize(r) {
49
58
  if (!r) return null
50
59
  if (r.then && typeof r.then === 'object') {
@@ -52,7 +61,7 @@ function normalize(r) {
52
61
  }
53
62
  // 旧格式:text/thought 在顶层
54
63
  return {
55
- id: r.id || ('exp_legacy_' + (r.at || Date.now()).toString().replace(/\D/g, '').slice(0, 12)),
64
+ id: r.id || legacyId(r),
56
65
  at: r.at || '',
57
66
  day: r.day || String(r.at || '').slice(0, 10),
58
67
  author: 'self',
@@ -197,29 +206,48 @@ function queryBigrams(q) {
197
206
 
198
207
  // 相关度 × 重要度:重要的先被想起
199
208
  // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛
200
- // 长查询要求按比例命中,避免「命中一个二字词就算相关」
209
+ // mode='strict'(默认):长查询要求 ≥60% 命中,宁可不召回也不硬凑
210
+ // mode='loose':只要求至少一个实词命中,适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
201
211
  // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
202
- export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6 } = {}) {
212
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict' } = {}) {
203
213
  const rows = loadAll(dir)
204
214
  const q = String(query || '')
205
215
  const { cleaned, bigrams } = queryBigrams(q)
206
- const required = (q && cleaned.length >= 8)
216
+ const strict = mode !== 'loose'
217
+ const required = (strict && q && cleaned.length >= 8)
207
218
  ? Math.max(minOverlap, Math.ceil(bigrams.size * minRatio))
208
219
  : minOverlap
209
220
 
210
221
  const measure = (r) => {
211
- const s = (r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' '))
212
- const t = s.replace(/[\s\p{P}\p{S}]+/gu, '')
213
- let n = 0
214
- for (const g of bigrams) if (t.includes(g)) n++
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, '')
215
243
  // 记录自身的 bigram 规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
216
- const size = Math.max(1, t.length - 1)
217
- return { n, size }
244
+ const size = Math.max(1, all.length - 1)
245
+ return { n: matched.size, size, matchedIn: fields }
218
246
  }
219
247
  const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
220
248
  const picked = rows.map((r) => {
221
- const { n, size } = measure(r)
222
- return { r, n, s: (n / Math.sqrt(size)) * weightOf(r) }
249
+ const { n, size, matchedIn } = measure(r)
250
+ return { r: { ...r, matchedIn }, n, s: (n / Math.sqrt(size)) * weightOf(r) }
223
251
  })
224
252
  .filter((x) => (q ? x.n >= required : true))
225
253
  .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
@@ -1,6 +1,7 @@
1
1
  // 她自己的设置:软限制归她,硬熔断归系统
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
+ import { addExperience } from './self-experience.js'
4
5
 
5
6
  export const DEFAULTS = {
6
7
  ownTime: '21:00-21:40',
@@ -25,15 +26,13 @@ export function save(dataDir, patch, reason = '') {
25
26
  const next = { ...cur, ...patch, updatedAt: new Date().toISOString() }
26
27
  fs.writeFileSync(f, JSON.stringify(next, null, 1), 'utf8')
27
28
  try {
28
- const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
29
- fs.appendFileSync(path.join(dir, 'self-experience.jsonl'), JSON.stringify({
30
- id: 'exp_set_' + Date.now().toString(36),
31
- at: new Date().toISOString(),
32
- day: new Date().toLocaleDateString('sv-SE'),
33
- author: 'self', source: 'own-decision', kind: '决定',
29
+ // 走同一条追加入口:末尾没换行、文件损坏之类的问题都由 addExperience 处理
30
+ addExperience(path.join(dataDir, 'plugin-data', 'biomimetic-memory'), {
34
31
  text: '我把自己的设置改了:' + JSON.stringify(patch),
35
- thought: String(reason || '').slice(0, 200)
36
- }) + '\n', 'utf8')
37
- } catch {}
32
+ thought: String(reason || '').slice(0, 200),
33
+ kind: '决定',
34
+ source: 'own-decision'
35
+ })
36
+ } catch { }
38
37
  return next
39
38
  }
package/lib/waking.js CHANGED
@@ -12,15 +12,20 @@ function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
12
12
 
13
13
  // 只读:算出「今天该给她看什么」,不写任何文件
14
14
  // 调用方确认真的把这段注入了,再调 consumeWaking 记「已展示」
15
- export function buildWakingBlock(dataDir, chatKey, { now = new Date() } = {}) {
16
- // 注入范围由调用方决定:这里只按「会话 + 日期」判断是否已经展示过
15
+ // 安全默认:没有 chatKey、或群聊(未显式 allowGroup)→ 返回空
16
+ // 醒来块里可能有昨天私下的话,默认不该流到群里
17
+ export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
18
+ const key = String(chatKey || '').trim()
19
+ if (!key) return ''
20
+ if (!allowGroup && /^group/i.test(key)) return ''
21
+
17
22
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
18
23
  const today = dayStr(now)
19
24
  const flag = path.join(dir, 'waking-flags.json')
20
25
  let flags = {}
21
26
  try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
22
- const key = chatKey + '|' + today
23
- if (flags[key]) return ''
27
+ const dedupeKey = key + '|' + today
28
+ if (flags[dedupeKey]) return ''
24
29
 
25
30
  const rows = readJsonl(path.join(dir, 'self-experience.jsonl')).map((r) => {
26
31
  if (r.then) return { day: r.day, text: r.then.text, unfinished: r.then.unfinished, weight: r.weight, later: r.later || [] }
@@ -46,13 +51,17 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date() } = {}) {
46
51
  }
47
52
 
48
53
  // 确认已展示:写入 flags,之后同一天同一会话不会再出
49
- export function consumeWaking(dataDir, chatKey, { now = new Date() } = {}) {
54
+ export function consumeWaking(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
55
+ const key = String(chatKey || '').trim()
56
+ if (!key) return false
57
+ if (!allowGroup && /^group/i.test(key)) return false
58
+
50
59
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
51
60
  fs.mkdirSync(dir, { recursive: true })
52
61
  const flag = path.join(dir, 'waking-flags.json')
53
62
  let flags = {}
54
63
  try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
55
- flags[chatKey + '|' + dayStr(now)] = new Date().toISOString()
64
+ flags[key + '|' + dayStr(now)] = new Date().toISOString()
56
65
  fs.writeFileSync(flag, JSON.stringify(flags), 'utf8')
57
66
  return true
58
67
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.8.2",
3
+ "version": "0.10.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",