whale-memory-core 0.0.0-stage → 0.2.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
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # whale-memory/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **自传层**内核:只管"她自己的经历"这一层,不是完整的记忆系统。纯 ESM、只用 Node 内置模块。
4
+
5
+ ```js
6
+ import * as exp from 'whale-memory-core/self-experience'
7
+ ```
8
+
9
+ ## 包含什么、不包含什么
10
+
11
+ 包含:
12
+
13
+ - `then` / `later` 两层经历,改主意不覆盖旧想法
14
+ - 召回(相关度 × 重要度)、想起计数、两段式渲染
15
+ - 醒来块、她自己的提示词 overlay、她自己的设置
16
+
17
+ 不包含(这些在 `plugin/biomimetic-memory/` 里,属于 QQ Agent 的完整引擎):
18
+
19
+ - vault 存储与索引、evidence-policy 取证、consolidator 合并、注入预算
20
+ - 跨会话可见性判断、宿主工具注册
21
+
22
+ 如果你要的是"一个 agent 的自传记忆",这个包够用;如果你要的是"完整记忆系统",看 [`docs/porting.md`](../../docs/porting.md) 里的边界说明,或直接读插件源码。
23
+
24
+ 包名 `whale-memory-core`,入口:`whale-memory-core`(命名导出)以及五个子路径:`/self-experience`、`/self-memory`、`/waking`、`/self-prompt`、`/self-settings`。
25
+
26
+ | 模块 | 作用 |
27
+ |---|---|
28
+ | `self-experience.js` | 经历两层(then / later)、重要度、两段式回想 |
29
+ | `self-memory.js` | 经历 + 日记的统一读取与渲染 |
30
+ | `waking.js` | 醒来块:每天第一次唤醒给昨天的时间线(是否注入由调用方决定) |
31
+ | `self-prompt.js` | 提示词 overlay:版本只追加、可回退 |
32
+ | `self-settings.js` | 她自己的设置(软限制归她),改动写进她的经历 |
33
+
34
+ ## 安装
35
+
36
+ ```sh
37
+ npm install whale-memory-core
38
+ ```
39
+
40
+ 已发布在 npm:`whale-memory-core@0.1.0`([npmjs.com](https://www.npmjs.com/package/whale-memory-core))。也可以从仓库本地安装:`npm install ./packages/core`。
41
+
42
+ ## 运行示例
43
+
44
+ ```bash
45
+ node demo.mjs
46
+ ```
47
+
48
+ 不需要配置文件、不需要 API key、不联网。演示会在临时目录里建一份数据,结束时会输出目录位置,方便检查记录。
49
+
50
+ ## 数据
51
+
52
+ 一条经历一行 JSON,格式见 [`docs/schema.md`](../../docs/schema.md)。三条虚构样本在 [`examples/samples/`](../../examples/samples/)。
53
+
54
+ 移植说明见仓库根目录 [`docs/porting.md`](../../docs/porting.md)。
package/demo.mjs ADDED
@@ -0,0 +1,47 @@
1
+ // 可运行示例:不需要任何宿主,node demo.mjs
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import * as exp from './lib/self-experience.js'
6
+ import * as prompt from './lib/self-prompt.js'
7
+ import * as waking from './lib/waking.js'
8
+
9
+ const DATA = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'whale-demo-')), 'data')
10
+ const dir = path.join(DATA, 'plugin-data', 'biomimetic-memory')
11
+ fs.mkdirSync(dir, { recursive: true })
12
+
13
+ console.log('数据目录:', DATA)
14
+
15
+ // 1) 她写下一条经历(重要的写细)
16
+ const e = exp.addExperience(dir, {
17
+ text: '读到烤肉那段,笑了一下',
18
+ scene: '晚上十一点多,屋里很静,书摊在桌上',
19
+ feeling: ['轻松', '有点羡慕'],
20
+ thought: '这种好事只在书里',
21
+ unfinished: '想知道小鞠和社长后面怎么样了',
22
+ quote: { text: '那就让妳重新迷上我一百年吧', source: '《败北女角太多了》第1卷第3章' },
23
+ weight: 'important',
24
+ state: { mood: '偏愉快' }
25
+ })
26
+ console.log('\n[写] id=', e.id, '| 重要度=', e.weight)
27
+
28
+ // 2) 第二天她想起(相关话题触发)
29
+ const hits = exp.recall(dir, '那本书里那个人后来怎样了', { limit: 1 })
30
+ console.log('\n[想起]\n' + exp.renderTwoPart(hits[0]))
31
+
32
+ // 3) 她改主意:只往 later 追加,不动"当时"
33
+ exp.reviseExperience(dir, { id: e.id, thought: '现在觉得那个人其实是在护着朋友', reason: '读到后面那段' })
34
+ console.log('\n[改主意后]\n' + exp.renderTwoPart(exp.currentView(dir, e.id)))
35
+
36
+ // 4) 醒来块(只在一对一私聊给)
37
+ const wake = waking.buildWakingBlock(DATA, 'local:owner')
38
+ console.log('\n[醒来块]\n' + (wake || '(今天已经展示过)'))
39
+
40
+ // 5) 她自己的提示词 overlay(版本只追加)
41
+ const v1 = prompt.save(DATA, '说话能短就短;想不起就说想不起。', '第一次写')
42
+ const v2 = prompt.save(DATA, '说话能短就短;想不起就说想不起。累了会慢,这不是失职。', '补一句')
43
+ console.log('\n[overlay] 版本:', v1.version, '→', v2.version)
44
+ console.log('当前内容:', prompt.load(DATA))
45
+ console.log('历史:', prompt.history(DATA, 3).map((h) => h.snapshot).join(', '))
46
+
47
+ console.log('\n演示完成。数据在', DATA)
package/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // whale-memory core:不依赖 QQ Agent 的可复用记忆内核
2
+ // 只放通用模块;宿主相关的工具注册与提示词拼接由使用者自己实现
3
+ export * as selfExperience from './lib/self-experience.js'
4
+ export * as selfMemory from './lib/self-memory.js'
5
+ export * as waking from './lib/waking.js'
6
+ export * as selfPrompt from './lib/self-prompt.js'
7
+ export * as selfSettings from './lib/self-settings.js'
@@ -0,0 +1,203 @@
1
+ // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ const FILE = 'self-experience.jsonl'
6
+ const WEIGHTS = new Set(['important', 'normal', 'minor'])
7
+
8
+ function readAll(dir, { rewriting = false } = {}) {
9
+ let raw
10
+ try {
11
+ raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
12
+ } catch (error) {
13
+ if (error.code === 'ENOENT') return []
14
+ throw error
15
+ }
16
+ const rows = []
17
+ for (const line of raw.split('\n').filter(line => line.trim())) {
18
+ try { rows.push(JSON.parse(line)) }
19
+ catch {
20
+ if (rewriting) throw new Error('经历文件含损坏记录,请备份并修复后再修改。')
21
+ }
22
+ }
23
+ return rows
24
+ }
25
+
26
+ function atomicWrite(dir, rows) {
27
+ const file = path.join(dir, FILE)
28
+ const tmp = file + '.tmp-' + Date.now()
29
+ fs.writeFileSync(tmp, rows.map((r) => JSON.stringify(r)).join('\n') + '\n', 'utf8')
30
+ fs.renameSync(tmp, file)
31
+ }
32
+
33
+ function writeAll(dir, rows) {
34
+ atomicWrite(dir, rows)
35
+ }
36
+
37
+ function normalize(r) {
38
+ if (!r) return null
39
+ if (r.then && typeof r.then === 'object') {
40
+ return { ...r, weight: WEIGHTS.has(r.weight) ? r.weight : 'normal', later: Array.isArray(r.later) ? r.later : [] }
41
+ }
42
+ // 旧格式:text/thought 在顶层
43
+ return {
44
+ id: r.id || ('exp_legacy_' + (r.at || Date.now()).toString().replace(/\D/g, '').slice(0, 12)),
45
+ at: r.at || '',
46
+ day: r.day || String(r.at || '').slice(0, 10),
47
+ author: 'self',
48
+ source: r.source || 'own-time',
49
+ kind: r.kind || '其它',
50
+ weight: WEIGHTS.has(r.weight) ? r.weight : 'normal',
51
+ then: {
52
+ text: String(r.text || '').slice(0, 600),
53
+ scene: '',
54
+ feeling: [],
55
+ thought: String(r.thought || '').slice(0, 300),
56
+ unfinished: '',
57
+ quote: null,
58
+ state: null
59
+ },
60
+ later: Array.isArray(r.later) ? r.later : [],
61
+ status: r.status || 'kept',
62
+ legacy: true
63
+ }
64
+ }
65
+
66
+ export function loadAll(dir) {
67
+ return readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
68
+ }
69
+
70
+ // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
71
+ export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time' }) {
72
+ fs.mkdirSync(dir, { recursive: true })
73
+ const now = new Date()
74
+ const id = 'exp_' + now.getTime().toString(36) + Math.random().toString(36).slice(2, 6)
75
+ const row = {
76
+ id,
77
+ at: now.toISOString(),
78
+ day: now.toLocaleDateString('sv-SE'),
79
+ author: 'self',
80
+ source,
81
+ kind: String(kind || '其它').slice(0, 20),
82
+ weight: WEIGHTS.has(weight) ? weight : 'normal',
83
+ then: {
84
+ text: String(text || '').slice(0, 600),
85
+ scene: String(scene || '').slice(0, 300),
86
+ feeling: (Array.isArray(feeling) ? feeling : [feeling]).map((f) => String(f || '').trim()).filter(Boolean).slice(0, 4),
87
+ thought: String(thought || '').slice(0, 300),
88
+ unfinished: String(unfinished || '').slice(0, 200),
89
+ quote: quote && quote.text ? { text: String(quote.text).slice(0, 300), source: String(quote.source || '').slice(0, 120) } : null,
90
+ state: state && typeof state === 'object' ? { at: now.toISOString(), ...state } : { at: now.toISOString() }
91
+ },
92
+ later: [],
93
+ status: 'kept'
94
+ }
95
+ const fd = fs.openSync(path.join(dir, FILE), 'a+')
96
+ try {
97
+ const size = fs.fstatSync(fd).size
98
+ const lastByte = Buffer.alloc(1)
99
+ if (size) fs.readSync(fd, lastByte, 0, 1, size - 1)
100
+ const separator = size && lastByte[0] !== 10 ? '\n' : ''
101
+ fs.writeFileSync(fd, separator + JSON.stringify(row) + '\n', 'utf8')
102
+ } finally {
103
+ fs.closeSync(fd)
104
+ }
105
+ return row
106
+ }
107
+
108
+ // 改主意 / 回头想:只往 later 里加,不动"当时"
109
+ export function reviseExperience(dir, { id, thought, reason = '' }) {
110
+ const rows = readAll(dir, { rewriting: true })
111
+ const i = rows.findIndex((r) => r.id === id)
112
+ if (i < 0) return { ok: false, error: '找不到这条经历' }
113
+ const cur = normalize(rows[i])
114
+ cur.later = Array.isArray(cur.later) ? cur.later : []
115
+ 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) })
116
+ rows[i] = cur
117
+ writeAll(dir, rows)
118
+ return { ok: true, entry: cur }
119
+ }
120
+
121
+ // 想起时记一笔(不改内容)
122
+ export function markRecalled(dir, id) {
123
+ const rows = readAll(dir, { rewriting: true })
124
+ const i = rows.findIndex((r) => r.id === id)
125
+ if (i < 0) return false
126
+ const cur = normalize(rows[i])
127
+ cur.recalls = Number(cur.recalls || 0) + 1
128
+ cur.lastRecalledAt = new Date().toISOString()
129
+ rows[i] = cur
130
+ writeAll(dir, rows)
131
+ return true
132
+ }
133
+
134
+ export function currentView(dir, id) {
135
+ const rows = loadAll(dir)
136
+ return rows.find((r) => r.id === id) || null
137
+ }
138
+
139
+ // 相关度 + 重要度:重要的先被想起
140
+ // mark=true 时,被取回的条目会记一次"想起"(计数 +1,内容不动)
141
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = true } = {}) {
142
+ const rows = loadAll(dir)
143
+ const q = String(query || '')
144
+ const score = (r) => {
145
+ const s = (r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' '))
146
+ let n = 0
147
+ const big = new Set()
148
+ const qc = q.replace(/[\s\p{P}\p{S}]+/gu, '')
149
+ for (let i = 0; i + 2 <= qc.length; i++) big.add(qc.slice(i, i + 2))
150
+ const t = s.replace(/[\s\p{P}\p{S}]+/gu, '')
151
+ for (const g of big) if (t.includes(g)) n++
152
+ const w = r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1
153
+ return n * w
154
+ }
155
+ const picked = rows.map((r) => ({ r, s: score(r) }))
156
+ .filter((x) => (q ? x.s >= minOverlap : true))
157
+ .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
158
+ .slice(0, limit).map((x) => x.r)
159
+
160
+ if (!mark || !picked.length) return picked
161
+
162
+ // 记一笔之后再读回,返回的对象里计数已经是新的
163
+ for (const r of picked) { try { markRecalled(dir, r.id) } catch { /* 坏文件时不阻断召回 */ } }
164
+ const byId = new Map(loadAll(dir).map((r) => [r.id, r]))
165
+ return picked.map((r) => byId.get(r.id) || r)
166
+ }
167
+
168
+ // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
169
+ export function renderTwoPart(entry, { now = new Date(), laterCount = 0 } = {}) {
170
+ if (!entry) return ''
171
+ const t = entry.then
172
+ const when = new Date(entry.at || entry.day)
173
+ const hh = Number.isNaN(when.getTime()) ? '' : when.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
174
+ const lines = []
175
+ lines.push('【当时】')
176
+ lines.push('- 时间:' + (entry.day || '') + (hh ? ' ' + hh : ''))
177
+ if (t.scene) lines.push('- 场景:' + t.scene)
178
+ if (t.quote && t.quote.text) lines.push('- 我读到的原文:' + t.quote.text + (t.quote.source ? '(' + t.quote.source + ')' : ''))
179
+ lines.push('- 我写下的话:' + t.text)
180
+ if ((t.feeling || []).length) lines.push('- 当时的感觉:' + t.feeling.join('、'))
181
+ if (t.thought) lines.push('- 当时的想法:' + t.thought)
182
+ if (t.unfinished) lines.push('- 还没完的:' + t.unfinished)
183
+ if (t.state && t.state.mood) lines.push('- 记录里的情绪:' + t.state.mood)
184
+ if (entry.legacy && !t.quote) lines.push('- (这条只留下感想,当时的原文没记)')
185
+ lines.push('', '【现在】')
186
+ lines.push('- 现在时间:' + now.toLocaleString('zh-CN', { hour12: false }))
187
+ lines.push('- 这条被你想起过 ' + Number(entry.recalls || 0) + ' 次' + (entry.lastRecalledAt ? ',上次是 ' + String(entry.lastRecalledAt).slice(0, 10) : ''))
188
+ const later = Array.isArray(entry.later) ? entry.later : []
189
+ if (later.length) {
190
+ const last = later[later.length - 1]
191
+ lines.push('- 后来你想过:' + String(last.thought || '').slice(0, 80) + (last.day ? '(' + last.day + ')' : ''))
192
+ } else {
193
+ lines.push('- 之后你还没回头想过')
194
+ }
195
+ lines.push('', '以上是那天留下的全部;没留下的,我不记得。')
196
+ return lines.join('\n')
197
+ }
198
+
199
+ export const internals = { WEIGHTS, FILE }
200
+ // 兼容旧调用:只要一句摘要的地方仍可用
201
+ export function recallForContext(dir, query, { max = 1 } = {}) {
202
+ 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 }))
203
+ }
@@ -0,0 +1,80 @@
1
+ // 她自己的记忆:统一读取她自己的经历、日记、自述;按相关度取回
2
+ import fs from 'node:fs'
3
+ 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
+ }
22
+
23
+ function readJsonl(file) {
24
+ try {
25
+ return fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
26
+ } catch { return [] }
27
+ }
28
+
29
+ // 她自己的经历(自己的时间写的)
30
+ 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)),
33
+ 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),
37
+ origin: 'own-time',
38
+ author: 'self'
39
+ })).filter((r) => r.text)
40
+ }
41
+
42
+ // 她的日记(可能提到别人,默认只在主人私聊用)
43
+ export function loadDiaries(dir) {
44
+ return readJsonl(path.join(dir, 'autobiography.jsonl')).map((r) => ({
45
+ id: 'diary_' + (r.day || '') + '_' + String(r.time || '').replace(/:/g, ''),
46
+ at: r.day || '',
47
+ kind: '日记',
48
+ text: String(r.event || r.text || '').slice(0, 400),
49
+ thought: '',
50
+ origin: 'diary',
51
+ author: 'self'
52
+ })).filter((r) => r.text)
53
+ }
54
+
55
+ export function recall(dir, query, { includeDiary = false, limit = 4, minOverlap = 1 } = {}) {
56
+ const pool = loadExperiences(dir).concat(includeDiary ? loadDiaries(dir) : [])
57
+ 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))
60
+ .sort((a, b) => (b.score - a.score) || (String(b.r.at).localeCompare(String(a.r.at))))
61
+ const out = [], seen = new Set()
62
+ for (const x of scored) {
63
+ if (seen.has(x.r.text)) continue
64
+ seen.add(x.r.text)
65
+ out.push(x.r)
66
+ if (out.length >= limit) break
67
+ }
68
+ return out
69
+ }
70
+
71
+ export function renderBlock(items, { title = '【我的记忆(我自己的,不是谁告诉我的)】', maxChars = 320 } = {}) {
72
+ if (!items || !items.length) return ''
73
+ const lines = [title]
74
+ for (const r of items) {
75
+ const when = String(r.at || '').slice(5, 10)
76
+ lines.push('- ' + (when ? when + ' ' : '') + String(r.text).slice(0, 70) + (r.thought ? '(当时想:' + String(r.thought).slice(0, 40) + ')' : ''))
77
+ }
78
+ const out = lines.join('\n')
79
+ return out.length <= maxChars ? out : out.slice(0, maxChars - 1) + '…'
80
+ }
@@ -0,0 +1,58 @@
1
+ // 她自己的提示词 overlay:不碰默认段,整段追加;版本只追加,可回退
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ const DIR = 'prompt-overlay'
6
+ const ACTIVE = 'prompt-overlay.md'
7
+ const VERSIONS = 'versions'
8
+ const MAX_CHARS = 2000
9
+
10
+ function base(dataDir) {
11
+ const d = path.join(dataDir, 'plugin-data', 'biomimetic-memory', DIR)
12
+ fs.mkdirSync(path.join(d, VERSIONS), { recursive: true })
13
+ return d
14
+ }
15
+
16
+ export function load(dataDir) {
17
+ try {
18
+ const f = path.join(base(dataDir), ACTIVE)
19
+ const text = fs.readFileSync(f, 'utf8').trim()
20
+ return text || ''
21
+ } catch { return '' }
22
+ }
23
+
24
+ export function save(dataDir, text, reason = '') {
25
+ const body = String(text || '').trim()
26
+ if (!body) return { ok: false, error: '空的,不写。' }
27
+ if (body.length > MAX_CHARS) return { ok: false, error: '太长了(' + body.length + '/' + MAX_CHARS + ' 字),删一些再试。' }
28
+ 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
35
+ }
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
+ }
41
+
42
+ export function history(dataDir, limit = 10) {
43
+ try {
44
+ const d = base(dataDir)
45
+ const rows = fs.readFileSync(path.join(d, 'history.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
46
+ return rows.slice(-limit).reverse()
47
+ } catch { return [] }
48
+ }
49
+
50
+ export function revert(dataDir, version) {
51
+ try {
52
+ const d = base(dataDir)
53
+ const body = fs.readFileSync(path.join(d, VERSIONS, String(version) + '.md'), 'utf8')
54
+ return save(dataDir, body, '回退到 ' + version)
55
+ } catch { return { ok: false, error: '找不到这个版本。' } }
56
+ }
57
+
58
+ export const internals = { MAX_CHARS, VERSIONS, ACTIVE }
@@ -0,0 +1,39 @@
1
+ // 她自己的设置:软限制归她,硬熔断归系统
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ export const DEFAULTS = {
6
+ ownTime: '21:00-21:40',
7
+ voiceSoftLimitPerDay: null, // null = 不限,只有防 bug 熔断
8
+ quietHours: null, // null = 不静音,随时可发
9
+ readingPerDay: 120,
10
+ note: '这些最初由开发者设定;她可以改,改完记进她的经历。'
11
+ }
12
+
13
+ export function load(dataDir) {
14
+ const f = path.join(dataDir, 'plugin-data', 'biomimetic-memory', 'self-settings.json')
15
+ try {
16
+ const j = JSON.parse(fs.readFileSync(f, 'utf8'))
17
+ return { ...DEFAULTS, ...j }
18
+ } catch { return { ...DEFAULTS } }
19
+ }
20
+
21
+ export function save(dataDir, patch, reason = '') {
22
+ const f = path.join(dataDir, 'plugin-data', 'biomimetic-memory', 'self-settings.json')
23
+ fs.mkdirSync(path.dirname(f), { recursive: true })
24
+ const cur = load(dataDir)
25
+ const next = { ...cur, ...patch, updatedAt: new Date().toISOString() }
26
+ fs.writeFileSync(f, JSON.stringify(next, null, 1), 'utf8')
27
+ 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: '决定',
34
+ text: '我把自己的设置改了:' + JSON.stringify(patch),
35
+ thought: String(reason || '').slice(0, 200)
36
+ }) + '\n', 'utf8')
37
+ } catch {}
38
+ return next
39
+ }
package/lib/waking.js ADDED
@@ -0,0 +1,53 @@
1
+ // 醒来块:每天第一次被唤醒时,给她一条自己的时间线
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ function readJsonl(file) {
6
+ try {
7
+ return fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
8
+ } catch { return [] }
9
+ }
10
+
11
+ function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
12
+
13
+ export function buildWakingBlock(dataDir, chatKey, { now = new Date() } = {}) {
14
+ // 注入范围由调用方决定:这里只按「会话 + 日期」去重,不判断该不该注入
15
+ const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
16
+ const today = dayStr(now)
17
+ const flag = path.join(dir, 'waking-flags.json')
18
+ let flags = {}
19
+ try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
20
+ const key = chatKey + '|' + today
21
+ if (flags[key]) return ''
22
+ flags[key] = new Date().toISOString()
23
+ try { fs.writeFileSync(flag, JSON.stringify(flags), 'utf8') } catch {}
24
+
25
+ const rows = readJsonl(path.join(dir, 'self-experience.jsonl')).map((r) => {
26
+ if (r.then) return { day: r.day, text: r.then.text, unfinished: r.then.unfinished, weight: r.weight, later: r.later || [] }
27
+ return { day: r.day, text: r.text, unfinished: '', weight: r.weight || 'normal', later: [] }
28
+ }).filter((r) => r.text)
29
+ const y = new Date(now.getTime() - 86400000).toLocaleDateString('sv-SE')
30
+ const yRows = rows.filter((r) => r.day === y)
31
+ const notes = readJsonl(path.join(dir, 'notes-to-tomorrow.jsonl'))
32
+ const lastNote = [...notes].reverse().find((n) => n.day === y)
33
+
34
+ const lines = ['【醒来】今天是 ' + today + '。']
35
+ if (yRows.length) {
36
+ lines.push('昨天你自己的时候:')
37
+ for (const r of yRows.slice(-3)) lines.push('- ' + String(r.text).slice(0, 60))
38
+ } else {
39
+ lines.push('昨天你没有留下自己的记录。')
40
+ }
41
+ if (lastNote && lastNote.text) lines.push('昨天睡前你给今天留了一句:' + String(lastNote.text).slice(0, 120))
42
+ const unfinished = rows.filter((r) => r.unfinished).slice(-2)
43
+ for (const r of unfinished) lines.push('- 你还没弄完:' + String(r.unfinished).slice(0, 50))
44
+ lines.push('(这些是记录,不是别人告诉你的。要不要接着想,你自己定。)')
45
+ return lines.join('\n')
46
+ }
47
+
48
+ export function leaveNote(dataDir, text) {
49
+ const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
50
+ const row = { at: new Date().toISOString(), day: dayStr(), text: String(text || '').slice(0, 300) }
51
+ fs.appendFileSync(path.join(dir, 'notes-to-tomorrow.jsonl'), JSON.stringify(row) + '\n', 'utf8')
52
+ return row
53
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./self-experience": "./lib/self-experience.js",
10
+ "./self-memory": "./lib/self-memory.js",
11
+ "./waking": "./lib/waking.js",
12
+ "./self-prompt": "./lib/self-prompt.js",
13
+ "./self-settings": "./lib/self-settings.js"
14
+ },
15
+ "files": [
16
+ "index.js",
17
+ "lib",
18
+ "demo.mjs",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "demo": "node demo.mjs"
26
+ },
27
+ "keywords": [
28
+ "ai-companion",
29
+ "agent-memory",
30
+ "long-term-memory",
31
+ "autobiographical-memory",
32
+ "llm"
33
+ ],
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/firefly1office/whale-memory.git",
38
+ "directory": "packages/core"
39
+ },
40
+ "sideEffects": false
41
+ }