whale-memory-core 0.5.1 → 0.6.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
@@ -37,7 +37,7 @@ import * as exp from 'whale-memory-core/self-experience'
37
37
  npm install whale-memory-core
38
38
  ```
39
39
 
40
- 已发布在 npm:`whale-memory-core@0.1.0`([npmjs.com](https://www.npmjs.com/package/whale-memory-core))。也可以从仓库本地安装:`npm install ./packages/core`。
40
+ 已发布在 npm:`whale-memory-core`([npmjs.com](https://www.npmjs.com/package/whale-memory-core),最新版本以 npm 为准)。也可以从仓库本地安装:`npm install ./packages/core`。
41
41
 
42
42
  ## 运行示例
43
43
 
@@ -0,0 +1,26 @@
1
+ // 跨进程文件锁:mkdir 独占 + 忙等重试;Windows 上并发 mkdir/rm 会短暂 EPERM/ENOENT,按“忙”处理
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ const BUSY = new Set(['EEXIST', 'EPERM', 'ENOENT', 'EBUSY', 'EACCES'])
6
+
7
+ export function withFileLock(lockPath, fn, { timeoutMs = 3000 } = {}) {
8
+ const start = Date.now()
9
+ for (;;) {
10
+ 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('文件被另一个进程锁着,稍后再试。')
21
+ const t = Date.now()
22
+ while (Date.now() - t < 20) { /* 短等待 */ }
23
+ }
24
+ }
25
+ try { return fn() } finally { try { fs.rmSync(lockPath, { recursive: true, force: true }) } catch { } }
26
+ }
@@ -0,0 +1,76 @@
1
+ // 改主意是事件:只追加,不改 then,也不重写经历文件
2
+ // 一行一个 { id, at, day, thought, reason? }
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { withFileLock } from './file-lock.js'
6
+
7
+ const FILE = 'later-events.jsonl'
8
+
9
+ export function eventsFile(memDir) {
10
+ return path.join(memDir, FILE)
11
+ }
12
+
13
+ export function append(memDir, { id, thought, reason = '' } = {}, opts = {}) {
14
+ if (!String(id || '').trim()) throw new Error('id 不能为空')
15
+ if (!String(thought || '').trim()) throw new Error('thought 不能为空')
16
+ const now = new Date()
17
+ const row = {
18
+ id: String(id),
19
+ at: now.toISOString(),
20
+ day: now.toLocaleDateString('sv-SE'),
21
+ thought: String(thought),
22
+ reason: String(reason || '')
23
+ }
24
+
25
+ fs.mkdirSync(memDir, { recursive: true })
26
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
27
+ const file = eventsFile(memDir)
28
+ let prefix = ''
29
+ try {
30
+ const st = fs.statSync(file)
31
+ if (st.size) {
32
+ const fd = fs.openSync(file, 'r')
33
+ const buf = Buffer.alloc(1)
34
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
35
+ fs.closeSync(fd)
36
+ if (buf[0] !== 10) prefix = '\n'
37
+ }
38
+ } catch { }
39
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
40
+ return row
41
+ }, opts)
42
+ }
43
+
44
+ export function readAll(memDir) {
45
+ let raw = ''
46
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
47
+ const rows = []
48
+ let bad = 0
49
+ for (const line of raw.split('\n')) {
50
+ if (!line.trim()) continue
51
+ try {
52
+ const r = JSON.parse(line)
53
+ if (r && r.id && r.thought) rows.push(r)
54
+ else bad += 1
55
+ } catch { bad += 1 }
56
+ }
57
+ return { rows, bad }
58
+ }
59
+
60
+ export function groupByExp(memDir) {
61
+ const { rows } = readAll(memDir)
62
+ const map = new Map()
63
+ for (const r of rows) {
64
+ const list = map.get(r.id) || []
65
+ list.push(r)
66
+ map.set(r.id, list)
67
+ }
68
+ return map
69
+ }
70
+
71
+ export function list(memDir, { id = '', limit = 20 } = {}) {
72
+ const { rows } = readAll(memDir)
73
+ return rows.filter((r) => !id || r.id === id).slice(-limit).reverse()
74
+ }
75
+
76
+ export const internals = { FILE }
@@ -3,6 +3,7 @@
3
3
  // 参数是记忆目录本身(<data>/plugin-data/biomimetic-memory),与 self-experience 一致
4
4
  import fs from 'node:fs'
5
5
  import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
6
7
 
7
8
  const FILE = 'recall-events.jsonl'
8
9
 
@@ -14,31 +15,7 @@ function ensureDir(memDir) {
14
15
  fs.mkdirSync(memDir, { recursive: true })
15
16
  }
16
17
 
17
- // 单写者锁:多进程追加时排队;超时报错,不静默丢事件
18
- // Windows 上并发 mkdir/rm 同一路径会短暂返回 EPERM/ENOENT,当成“忙”重试
19
- const BUSY = new Set(['EEXIST', 'EPERM', 'ENOENT', 'EBUSY', 'EACCES'])
20
18
 
21
- function withLock(memDir, fn, { timeoutMs = 3000 } = {}) {
22
- const lock = eventsFile(memDir) + '.lock'
23
- const start = Date.now()
24
- for (;;) {
25
- try {
26
- fs.mkdirSync(memDir, { recursive: true })
27
- fs.mkdirSync(lock)
28
- break
29
- } catch (e) {
30
- if (!BUSY.has(e.code)) throw e
31
- try {
32
- const st = fs.statSync(lock)
33
- if (Date.now() - st.mtimeMs > 10000) { fs.rmSync(lock, { recursive: true, force: true }); continue }
34
- } catch { }
35
- if (Date.now() - start > timeoutMs) throw new Error('recall-events 被另一个进程锁着,稍后再试。')
36
- const t = Date.now()
37
- while (Date.now() - t < 20) { }
38
- }
39
- }
40
- try { return fn() } finally { try { fs.rmSync(lock, { recursive: true, force: true }) } catch { } }
41
- }
42
19
 
43
20
  export function append(memDir, { id, query = '', chatKey = '', backfilled = false } = {}, opts = {}) {
44
21
  if (!String(id || '').trim()) throw new Error('id 不能为空')
@@ -51,7 +28,7 @@ export function append(memDir, { id, query = '', chatKey = '', backfilled = fals
51
28
  if (backfilled) row.backfilled = true
52
29
 
53
30
  ensureDir(memDir)
54
- return withLock(memDir, () => {
31
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
55
32
  const file = eventsFile(memDir)
56
33
  let prefix = ''
57
34
  try {
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
4
  import * as recallEvents from './recall-events.js'
5
+ import * as laterEvents from './later-events.js'
5
6
 
6
7
  const FILE = 'self-experience.jsonl'
7
8
  const WEIGHTS = new Set(['important', 'normal', 'minor'])
@@ -36,7 +37,7 @@ function writeAll(dir, rows) {
36
37
  }
37
38
 
38
39
  // 字段上限:写的时候超了就报错,不静默截断
39
- export const LIMITS = { text: 2000, scene: 500, thought: 1000, unfinished: 300, feelings: 8, kind: 20 }
40
+ export const LIMITS = { text: 2000, scene: 500, thought: 1000, unfinished: 300, feelings: 8, kind: 20, laterThought: 1000, laterReason: 200 }
40
41
 
41
42
  function tooLong(name, value, max) {
42
43
  const n = String(value || '').length
@@ -75,14 +76,27 @@ function normalize(r) {
75
76
 
76
77
  export function loadAll(dir) {
77
78
  const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
79
+ if (!rows.length) return rows
80
+
78
81
  // 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段
79
82
  let counts = new Map()
80
83
  try { counts = recallEvents.countByExp(dir) } catch { /* 事件文件坏了也不影响读经历 */ }
81
- if (!counts.size) return rows
84
+
85
+ // 改主意:旧 later 数组 + later-events 事件,按时间合并
86
+ let laterMap = new Map()
87
+ try { laterMap = laterEvents.groupByExp(dir) } catch { }
88
+
82
89
  return rows.map((r) => {
83
90
  const c = counts.get(r.id)
84
- if (!c) return r
85
- return { ...r, recalls: c.count, lastRecalledAt: c.lastAt || r.lastRecalledAt || '' }
91
+ const extra = laterMap.get(r.id) || []
92
+ const merged = [...(r.later || []), ...extra]
93
+ .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
94
+ const next = { ...r, later: merged }
95
+ if (c) {
96
+ next.recalls = c.count
97
+ next.lastRecalledAt = c.lastAt || r.lastRecalledAt || ''
98
+ }
99
+ return next
86
100
  })
87
101
  }
88
102
 
@@ -133,24 +147,25 @@ export function addExperience(dir, { text, scene = '', feeling = [], thought = '
133
147
  return row
134
148
  }
135
149
 
136
- // 改主意 / 回头想:只往 later 里加,不动"当时"
150
+ // 改主意 / 回头想:只追加一条 later 事件,不读全量、不重写经历文件
137
151
  export function reviseExperience(dir, { id, thought, reason = '' }) {
138
- const rows = readAll(dir, { rewriting: true })
139
- const i = rows.findIndex((r) => r.id === id)
140
- if (i < 0) return { ok: false, error: '找不到这条经历' }
141
- const cur = normalize(rows[i])
142
- cur.later = Array.isArray(cur.later) ? cur.later : []
143
- cur.later.push({ at: new Date().toISOString(), day: new Date().toLocaleDateString('sv-SE'), thought: String(thought || '').slice(0, 300), reason: String(reason || '').slice(0, 200) })
144
- rows[i] = cur
145
- writeAll(dir, rows)
146
- return { ok: true, entry: cur }
152
+ if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
153
+ if (!String(thought || '').trim()) return { ok: false, error: 'thought 不能是空的。' }
154
+ try {
155
+ const safeThought = tooLong('thought', thought, LIMITS.laterThought)
156
+ const safeReason = tooLong('reason', reason, LIMITS.laterReason)
157
+ const row = laterEvents.append(dir, { id: String(id), thought: safeThought, reason: safeReason })
158
+ return { ok: true, id: row.id, at: row.at }
159
+ } catch (e) {
160
+ return { ok: false, error: String(e && e.message ? e.message : e) }
161
+ }
147
162
  }
148
163
 
149
164
  // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
165
+ // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
150
166
  export function markRecalled(dir, id) {
151
- const exists = readAll(dir).map(normalize).some((r) => r && r.id === id)
152
- if (!exists) return false
153
- recallEvents.append(dir, { id })
167
+ if (!String(id || '').trim()) return false
168
+ try { recallEvents.append(dir, { id: String(id) }) } catch { return false }
154
169
  return true
155
170
  }
156
171
 
@@ -159,10 +174,9 @@ export function currentView(dir, id) {
159
174
  return rows.find((r) => r.id === id) || null
160
175
  }
161
176
 
162
- // 相关度 + 重要度:重要的先被想起
163
177
  // 相关度 × 重要度:重要的先被想起
164
178
  // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛
165
- // mark=false(默认):只读;mark=true 才记一次"想起"(会重写文件,单写者场景用)
179
+ // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
166
180
  export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false } = {}) {
167
181
  const rows = loadAll(dir)
168
182
  const q = String(query || '')
@@ -187,10 +201,12 @@ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false } =
187
201
 
188
202
  if (!mark || !picked.length) return picked
189
203
 
190
- // 记一笔之后再读回,返回的对象里计数已经是新的
191
- for (const r of picked) { try { markRecalled(dir, r.id) } catch { /* 坏文件时不阻断召回 */ } }
192
- const byId = new Map(loadAll(dir).map((r) => [r.id, r]))
193
- return picked.map((r) => byId.get(r.id) || r)
204
+ // 记完就地 +1,不回读全量;下一次读取自然会对上
205
+ const at = new Date().toISOString()
206
+ for (const r of picked) {
207
+ try { recallEvents.append(dir, { id: r.id, query: q }) } catch { /* 坏文件时不阻断召回 */ }
208
+ }
209
+ return picked.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
194
210
  }
195
211
 
196
212
  // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.5.1",
3
+ "version": "0.6.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",
@@ -11,7 +11,9 @@
11
11
  "./waking": "./lib/waking.js",
12
12
  "./self-prompt": "./lib/self-prompt.js",
13
13
  "./self-settings": "./lib/self-settings.js",
14
- "./recall-events": "./lib/recall-events.js"
14
+ "./recall-events": "./lib/recall-events.js",
15
+ "./later-events": "./lib/later-events.js",
16
+ "./file-lock": "./lib/file-lock.js"
15
17
  },
16
18
  "files": [
17
19
  "index.js",