whale-memory-core 0.2.1 → 0.4.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
@@ -14,12 +14,12 @@ import * as exp from 'whale-memory-core/self-experience'
14
14
  - 召回(相关度 × 重要度)、想起计数、两段式渲染
15
15
  - 醒来块、她自己的提示词 overlay、她自己的设置
16
16
 
17
- 不包含(这些在 `plugin/biomimetic-memory/` 里,属于 QQ Agent 的完整引擎):
17
+ 不包含(完整引擎与具体宿主部署耦合,不随本仓库分发):
18
18
 
19
19
  - vault 存储与索引、evidence-policy 取证、consolidator 合并、注入预算
20
20
  - 跨会话可见性判断、宿主工具注册
21
21
 
22
- 如果你要的是"一个 agent 的自传记忆",这个包够用;如果你要的是"完整记忆系统",看 [`docs/porting.md`](../../docs/porting.md) 里的边界说明,或直接读插件源码。
22
+ 如果你要的是"一个 agent 的自传记忆",这个包够用;如果你要的是"完整记忆系统",看 [`docs/architecture.md`](../../docs/architecture.md) 与 [`docs/porting.md`](../../docs/porting.md)。
23
23
 
24
24
  包名 `whale-memory-core`,入口:`whale-memory-core`(命名导出)以及五个子路径:`/self-experience`、`/self-memory`、`/waking`、`/self-prompt`、`/self-settings`。
25
25
 
package/demo.mjs CHANGED
@@ -25,8 +25,8 @@ const e = exp.addExperience(dir, {
25
25
  })
26
26
  console.log('\n[写] id=', e.id, '| 重要度=', e.weight)
27
27
 
28
- // 2) 第二天她想起(相关话题触发)
29
- const hits = exp.recall(dir, '那本书里那个人后来怎样了', { limit: 1 })
28
+ // 2) 第二天她想起(相关话题触发);mark:true 表示这次取回也记一次“想起”
29
+ const hits = exp.recall(dir, '那本书里那个人后来怎样了', { limit: 1, mark: true })
30
30
  console.log('\n[想起]\n' + exp.renderTwoPart(hits[0]))
31
31
 
32
32
  // 3) 她改主意:只往 later 追加,不动"当时"
@@ -25,7 +25,7 @@ function readAll(dir, { rewriting = false } = {}) {
25
25
 
26
26
  function atomicWrite(dir, rows) {
27
27
  const file = path.join(dir, FILE)
28
- const tmp = file + '.tmp-' + Date.now()
28
+ const tmp = file + '.tmp-' + Date.now() + '-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
29
29
  fs.writeFileSync(tmp, rows.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8')
30
30
  fs.renameSync(tmp, file)
31
31
  }
@@ -155,11 +155,13 @@ export function currentView(dir, id) {
155
155
  }
156
156
 
157
157
  // 相关度 + 重要度:重要的先被想起
158
- // mark=true 时,被取回的条目会记一次"想起"(计数 +1,内容不动)
159
- export function recall(dir, query, { limit = 3, minOverlap = 1, mark = true } = {}) {
158
+ // 相关度 × 重要度:重要的先被想起
159
+ // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛
160
+ // mark=false(默认):只读;mark=true 才记一次"想起"(会重写文件,单写者场景用)
161
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false } = {}) {
160
162
  const rows = loadAll(dir)
161
163
  const q = String(query || '')
162
- const score = (r) => {
164
+ const overlap = (r) => {
163
165
  const s = (r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' '))
164
166
  let n = 0
165
167
  const big = new Set()
@@ -167,11 +169,14 @@ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = true } =
167
169
  for (let i = 0; i + 2 <= qc.length; i++) big.add(qc.slice(i, i + 2))
168
170
  const t = s.replace(/[\s\p{P}\p{S}]+/gu, '')
169
171
  for (const g of big) if (t.includes(g)) n++
170
- const w = r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1
171
- return n * w
172
+ return n
172
173
  }
173
- const picked = rows.map((r) => ({ r, s: score(r) }))
174
- .filter((x) => (q ? x.s >= minOverlap : true))
174
+ const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
175
+ const picked = rows.map((r) => {
176
+ const n = overlap(r)
177
+ return { r, n, s: n * weightOf(r) }
178
+ })
179
+ .filter((x) => (q ? x.n >= minOverlap : true))
175
180
  .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
176
181
  .slice(0, limit).map((x) => x.r)
177
182
 
@@ -1,11 +1,14 @@
1
1
  // 她自己的提示词 overlay:不碰默认段,整段追加;版本只追加,可回退
2
+ // 护栏:大小上限、控制字符清理、重复内容不写、原子写、单写者锁、篡改可检测
2
3
  import fs from 'node:fs'
3
4
  import path from 'node:path'
5
+ import crypto from 'node:crypto'
4
6
 
5
7
  const DIR = 'prompt-overlay'
6
8
  const ACTIVE = 'prompt-overlay.md'
7
9
  const VERSIONS = 'versions'
8
10
  const MAX_CHARS = 2000
11
+ const MAX_APPEND_TOTAL = 12000
9
12
 
10
13
  function base(dataDir) {
11
14
  const d = path.join(dataDir, 'plugin-data', 'biomimetic-memory', DIR)
@@ -13,30 +16,82 @@ function base(dataDir) {
13
16
  return d
14
17
  }
15
18
 
19
+ const sha1 = (s) => crypto.createHash('sha1').update(s).digest('hex').slice(0, 16)
20
+
21
+ // 清理不可见控制字符;换行和制表保留
22
+ function clean(text) {
23
+ return String(text || '')
24
+ .replace(/\r\n?/g, '\n')
25
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200b-\u200f\u2028\u2029]/g, '')
26
+ .trim()
27
+ }
28
+
29
+ function atomicWrite(file, body) {
30
+ const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8)
31
+ fs.writeFileSync(tmp, body, 'utf8')
32
+ fs.renameSync(tmp, file)
33
+ }
34
+
35
+ // 单写者锁:另一个进程正在写时等一会儿;超过 timeout 报错,不静默覆盖
36
+ function withLock(dir, fn, { timeoutMs = 2000 } = {}) {
37
+ const lock = path.join(dir, '.lock')
38
+ const start = Date.now()
39
+ for (;;) {
40
+ try {
41
+ fs.mkdirSync(lock)
42
+ break
43
+ } catch (e) {
44
+ if (e.code !== 'EEXIST') throw e
45
+ try {
46
+ const st = fs.statSync(lock)
47
+ if (Date.now() - st.mtimeMs > 10000) { fs.rmSync(lock, { recursive: true, force: true }); continue }
48
+ } catch { /* 锁刚被释放 */ }
49
+ if (Date.now() - start > timeoutMs) throw new Error('提示词文件被另一个进程锁着,稍后再试。')
50
+ const t = Date.now()
51
+ while (Date.now() - t < 25) { /* 短等待 */ }
52
+ }
53
+ }
54
+ try { return fn() } finally { try { fs.rmSync(lock, { recursive: true, force: true }) } catch { } }
55
+ }
56
+
16
57
  export function load(dataDir) {
17
58
  try {
18
- const f = path.join(base(dataDir), ACTIVE)
19
- const text = fs.readFileSync(f, 'utf8').trim()
20
- return text || ''
59
+ return clean(fs.readFileSync(path.join(base(dataDir), ACTIVE), 'utf8'))
21
60
  } catch { return '' }
22
61
  }
23
62
 
24
- export function save(dataDir, text, reason = '') {
25
- const body = String(text || '').trim()
63
+ export function save(dataDir, text, reason = '', opts = {}) {
64
+ const body = clean(text)
26
65
  if (!body) return { ok: false, error: '空的,不写。' }
27
66
  if (body.length > MAX_CHARS) return { ok: false, error: '太长了(' + body.length + '/' + MAX_CHARS + ' 字),删一些再试。' }
67
+
68
+ const current = load(dataDir)
69
+ if (current === body) return { ok: true, noop: true, reason: '和当前版本一样,没有写入。' }
70
+
28
71
  const d = base(dataDir)
29
- const baseStamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 23)
30
- let stamp = baseStamp
31
- let n = 1
32
- while (fs.existsSync(path.join(d, VERSIONS, stamp + '.md'))) {
33
- stamp = baseStamp + '-' + n
34
- n += 1
72
+ try {
73
+ return withLock(d, () => {
74
+ const baseStamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 23)
75
+ let stamp = baseStamp
76
+ let n = 1
77
+ while (fs.existsSync(path.join(d, VERSIONS, stamp + '.md'))) {
78
+ stamp = baseStamp + '-' + n
79
+ n += 1
80
+ }
81
+ atomicWrite(path.join(d, VERSIONS, stamp + '.md'), body)
82
+ atomicWrite(path.join(d, ACTIVE), body)
83
+ fs.appendFileSync(path.join(d, 'history.jsonl'), JSON.stringify({
84
+ at: new Date().toISOString(),
85
+ chars: body.length,
86
+ hash: sha1(body),
87
+ reason: String(reason || '').slice(0, 200),
88
+ snapshot: stamp
89
+ }) + '\n', 'utf8')
90
+ return { ok: true, version: stamp, chars: body.length, hash: sha1(body) }
91
+ }, opts)
92
+ } catch (e) {
93
+ return { ok: false, error: String(e && e.message ? e.message : e) }
35
94
  }
36
- fs.writeFileSync(path.join(d, VERSIONS, stamp + '.md'), body, 'utf8')
37
- fs.writeFileSync(path.join(d, ACTIVE), body, 'utf8')
38
- fs.appendFileSync(path.join(d, 'history.jsonl'), JSON.stringify({ at: new Date().toISOString(), chars: body.length, reason: String(reason || '').slice(0, 200), snapshot: stamp }) + '\n', 'utf8')
39
- return { ok: true, version: stamp, chars: body.length }
40
95
  }
41
96
 
42
97
  export function history(dataDir, limit = 10) {
@@ -47,12 +102,39 @@ export function history(dataDir, limit = 10) {
47
102
  } catch { return [] }
48
103
  }
49
104
 
50
- export function revert(dataDir, version) {
105
+ export function revert(dataDir, version, reason = '') {
51
106
  try {
52
107
  const d = base(dataDir)
53
108
  const body = fs.readFileSync(path.join(d, VERSIONS, String(version) + '.md'), 'utf8')
54
- return save(dataDir, body, '回退到 ' + version)
109
+ return save(dataDir, body, reason || ('回退到 ' + version))
55
110
  } catch { return { ok: false, error: '找不到这个版本。' } }
56
111
  }
57
112
 
58
- export const internals = { MAX_CHARS, VERSIONS, ACTIVE }
113
+ // 生效内容 = 默认段 + 她的 overlay;超总长会明确报告截断,不悄悄切
114
+ export function render(basePrompt, dataDir, { marker = '\n\n<!-- 她自己的补充 -->\n' } = {}) {
115
+ const overlay = load(dataDir)
116
+ const base = String(basePrompt || '')
117
+ if (!overlay) return { text: base, appended: false, truncated: false }
118
+ const full = base + marker + overlay
119
+ if (full.length <= MAX_APPEND_TOTAL) return { text: full, appended: true, truncated: false }
120
+ const room = MAX_APPEND_TOTAL - base.length - marker.length
121
+ return {
122
+ text: base + marker + overlay.slice(0, Math.max(0, room)),
123
+ appended: true,
124
+ truncated: true,
125
+ note: 'overlay 超过总长上限,已截断;建议她精简。'
126
+ }
127
+ }
128
+
129
+ // 篡改检测:生效文件应该和最新版本文件一致
130
+ export function verify(dataDir) {
131
+ const active = load(dataDir)
132
+ const h = history(dataDir, 1)[0]
133
+ if (!h) return { ok: active === '', note: active ? '有生效文件但没有历史版本。' : '还没有写过。' }
134
+ let versionBody = ''
135
+ try { versionBody = clean(fs.readFileSync(path.join(base(dataDir), VERSIONS, String(h.snapshot) + '.md'), 'utf8')) } catch { }
136
+ const ok = active === versionBody
137
+ return { ok, activeHash: sha1(active), versionHash: sha1(versionBody), version: h.snapshot }
138
+ }
139
+
140
+ export const internals = { MAX_CHARS, MAX_APPEND_TOTAL, VERSIONS, ACTIVE, sha1 }
package/lib/waking.js CHANGED
@@ -10,8 +10,10 @@ function readJsonl(file) {
10
10
 
11
11
  function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
12
12
 
13
+ // 只读:算出「今天该给她看什么」,不写任何文件
14
+ // 调用方确认真的把这段注入了,再调 consumeWaking 记「已展示」
13
15
  export function buildWakingBlock(dataDir, chatKey, { now = new Date() } = {}) {
14
- // 注入范围由调用方决定:这里只按「会话 + 日期」去重,不判断该不该注入
16
+ // 注入范围由调用方决定:这里只按「会话 + 日期」判断是否已经展示过
15
17
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
16
18
  const today = dayStr(now)
17
19
  const flag = path.join(dir, 'waking-flags.json')
@@ -19,8 +21,6 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date() } = {}) {
19
21
  try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
20
22
  const key = chatKey + '|' + today
21
23
  if (flags[key]) return ''
22
- flags[key] = new Date().toISOString()
23
- try { fs.writeFileSync(flag, JSON.stringify(flags), 'utf8') } catch {}
24
24
 
25
25
  const rows = readJsonl(path.join(dir, 'self-experience.jsonl')).map((r) => {
26
26
  if (r.then) return { day: r.day, text: r.then.text, unfinished: r.then.unfinished, weight: r.weight, later: r.later || [] }
@@ -45,6 +45,18 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date() } = {}) {
45
45
  return lines.join('\n')
46
46
  }
47
47
 
48
+ // 确认已展示:写入 flags,之后同一天同一会话不会再出
49
+ export function consumeWaking(dataDir, chatKey, { now = new Date() } = {}) {
50
+ const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
51
+ fs.mkdirSync(dir, { recursive: true })
52
+ const flag = path.join(dir, 'waking-flags.json')
53
+ let flags = {}
54
+ try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
55
+ flags[chatKey + '|' + dayStr(now)] = new Date().toISOString()
56
+ fs.writeFileSync(flag, JSON.stringify(flags), 'utf8')
57
+ return true
58
+ }
59
+
48
60
  export function leaveNote(dataDir, text) {
49
61
  const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
50
62
  const row = { at: new Date().toISOString(), day: dayStr(), text: String(text || '').slice(0, 300) }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.2.1",
3
+ "version": "0.4.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",