whale-memory-core 0.20.0 → 0.21.1
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 +3 -3
- package/bin/whale-memory-mcp.mjs +29 -5
- package/index.d.ts +7 -0
- package/index.js +2 -0
- package/lib/archive.d.ts +19 -0
- package/lib/archive.js +267 -14
- package/lib/book.js +34 -3
- package/lib/changed.d.ts +4 -0
- package/lib/changed.js +76 -0
- package/lib/conversation-privacy.js +43 -15
- package/lib/fact-store.js +56 -15
- package/lib/file-lock.d.ts +4 -1
- package/lib/file-lock.js +151 -13
- package/lib/injection.d.ts +5 -0
- package/lib/injection.js +82 -0
- package/lib/query-match.js +67 -18
- package/lib/scope-key.d.ts +4 -0
- package/lib/scope-key.js +34 -0
- package/lib/seal-events.d.ts +2 -2
- package/lib/seal-events.js +26 -5
- package/lib/self-experience.d.ts +4 -1
- package/lib/self-experience.js +138 -52
- package/lib/self-prompt.js +22 -5
- package/lib/unfinished-events.d.ts +2 -0
- package/lib/waking.js +6 -3
- package/package.json +9 -1
package/lib/scope-key.js
CHANGED
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* - 人设级查询 = 人设级记录 + 同会话的会话级记录
|
|
7
7
|
* - 会话级查询 = 只认会话级记录(不反向并入人设记录,避免把某人的记忆串给所有人)
|
|
8
8
|
*
|
|
9
|
+
* 另外,这里也放"这个会话是不是一对一的私聊"这一条判断:
|
|
10
|
+
* 醒来块、注入、未说出口抽屉、跨窗口可见性都问同一个实现,别让每个出口各写一份正则。
|
|
11
|
+
*
|
|
9
12
|
* 纯函数,宿主无关。
|
|
10
13
|
*/
|
|
11
14
|
|
|
@@ -21,6 +24,37 @@ export function isPersonaScoped(chatKey) {
|
|
|
21
24
|
return PERSONA_SUFFIX.test(String(chatKey || '').trim());
|
|
22
25
|
}
|
|
23
26
|
|
|
27
|
+
// 一对一会话的写法:private_10001 / private:10001 / local_owner / local:owner。
|
|
28
|
+
// 分隔符后面必须有东西:光一个 `private:` 认不出是谁,不给。
|
|
29
|
+
const PRIVATE_PREFIX = /^(?:private|local)[:_](.+)$/i;
|
|
30
|
+
|
|
31
|
+
// 群 / 公共场景的标记。前后都要是边界(键首、分隔符、数字、结尾),
|
|
32
|
+
// 所以 `private_groupie_42` 这种账号名不算群;`group_1`、`group:1`、`qq:group:1`、
|
|
33
|
+
// `private:group_123`、`local_group_1` 都算。中文"群"当整体标记看。
|
|
34
|
+
const GROUP_MARK = /(?:^|[:_\-#.@])(?:groupchat|groupdm|group|guild|channel|chatroom|conference)(?=$|[:_\-#.@0-9])/i;
|
|
35
|
+
const GROUP_CJK = /群/;
|
|
36
|
+
|
|
37
|
+
/** 这个键是不是群 / 公共场景(group_1、qq:group:1、private:group_123、群聊……)。 */
|
|
38
|
+
export function isGroupScope(chatKey) {
|
|
39
|
+
const base = baseChatKey(chatKey);
|
|
40
|
+
if (!base) return false;
|
|
41
|
+
return GROUP_MARK.test(base) || GROUP_CJK.test(base);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 这个键是不是认得出来的一对一私聊。
|
|
46
|
+
*
|
|
47
|
+
* 只认 `private_` / `private:` / `local_` / `local:` 开头;带群标记的(`private:group_123`、
|
|
48
|
+
* `local_group_1`……)和认不出来的写法(`group_1`、`qq:group:1`、空键)一律 false。
|
|
49
|
+
* 这是"宁可不给"的方向:醒来块、注入、抽屉都靠它,错放行一次就是把私话带进群里。
|
|
50
|
+
*/
|
|
51
|
+
export function isPrivateScope(chatKey) {
|
|
52
|
+
const base = baseChatKey(chatKey);
|
|
53
|
+
if (!base) return false;
|
|
54
|
+
if (!PRIVATE_PREFIX.test(base)) return false;
|
|
55
|
+
return !isGroupScope(base);
|
|
56
|
+
}
|
|
57
|
+
|
|
24
58
|
/**
|
|
25
59
|
* 一次查询应该覆盖哪些键。
|
|
26
60
|
* @param {string} chatKey 当前会话键
|
package/lib/seal-events.d.ts
CHANGED
|
@@ -20,6 +20,6 @@ export function eventsFile(memDir: string): string
|
|
|
20
20
|
/** 同一把锁里重读 → 判断 → 追加;已是这个状态就 noop,不写第二条 */
|
|
21
21
|
export function decide(memDir: string, opts: { id: string; action: SealAction; note?: string }, lockOpts?: Record<string, unknown>): { row: SealEvent | null; noop: boolean }
|
|
22
22
|
export function readAll(memDir: string): { rows: SealEvent[]; bad: number }
|
|
23
|
-
/** 现在(或截至 until
|
|
24
|
-
export function sealedByExp(memDir: string, opts?: { until?: number | null }): Map<string, SealedInfo>
|
|
23
|
+
/** 现在(或截至 until)仍封存着的经历;strict 时坏行会抛 SEAL_EVENTS_CORRUPT */
|
|
24
|
+
export function sealedByExp(memDir: string, opts?: { until?: number | null; strict?: boolean }): Map<string, SealedInfo>
|
|
25
25
|
export const internals: { FILE: string }
|
package/lib/seal-events.js
CHANGED
|
@@ -42,17 +42,30 @@ export function decide(memDir, { id, action, note = '' } = {}, opts = {}) {
|
|
|
42
42
|
if (!ACTIONS.has(action)) throw new Error('action must be seal / unseal(action 只能是 seal / unseal)')
|
|
43
43
|
fs.mkdirSync(memDir, { recursive: true })
|
|
44
44
|
return withFileLock(eventsFile(memDir) + '.lock', () => {
|
|
45
|
-
const
|
|
45
|
+
const all = readAll(memDir)
|
|
46
|
+
const rows = all.rows.filter((r) => r.id === String(id))
|
|
46
47
|
const last = rows[rows.length - 1] || null
|
|
47
48
|
const sealedNow = Boolean(last && last.action === 'seal')
|
|
48
|
-
|
|
49
|
+
// 有坏行时状态不确定:不做"重复操作"的合并,直接按她的请求追加,
|
|
50
|
+
// 让最后一次显式动作成为真正生效的那条。
|
|
51
|
+
if (!all.bad && ((action === 'seal' && sealedNow) || (action === 'unseal' && !sealedNow))) return { row: last, noop: true }
|
|
49
52
|
return { row: appendUnlocked(memDir, makeRow({ id, action, note })), noop: false }
|
|
50
53
|
}, opts)
|
|
51
54
|
}
|
|
52
55
|
|
|
53
56
|
export function readAll(memDir) {
|
|
54
57
|
let raw = ''
|
|
55
|
-
try {
|
|
58
|
+
try {
|
|
59
|
+
raw = fs.readFileSync(eventsFile(memDir), 'utf8')
|
|
60
|
+
} catch (error) {
|
|
61
|
+
// 只有"还没有这个文件"能当空;权限、磁盘、路径是目录这类错误必须抛出去。
|
|
62
|
+
// 否则正文可读、封存日志读不出来时,召回/醒来/书会当成"她什么都没封存"。
|
|
63
|
+
if (error?.code === 'ENOENT') return { rows: [], bad: 0 }
|
|
64
|
+
const wrapped = new Error('封存日志读不出来:' + String(error?.message || error))
|
|
65
|
+
wrapped.code = 'SEAL_EVENTS_UNREADABLE'
|
|
66
|
+
wrapped.cause = error
|
|
67
|
+
throw wrapped
|
|
68
|
+
}
|
|
56
69
|
const rows = []
|
|
57
70
|
let bad = 0
|
|
58
71
|
for (const line of raw.split('\n')) {
|
|
@@ -67,8 +80,16 @@ export function readAll(memDir) {
|
|
|
67
80
|
}
|
|
68
81
|
|
|
69
82
|
// 每个经历 id 现在是否封存着:只收最后一次是 seal 的;until 用于翻回那天(那时还没封存就不算)
|
|
70
|
-
|
|
71
|
-
|
|
83
|
+
// strict:展示路径用。日志里有坏行时"某条经历唯一一次封存"可能正好坏掉,
|
|
84
|
+
// 这时不能默认可见——把"状态未知"抛给调用方(fail closed)。
|
|
85
|
+
export function sealedByExp(memDir, { until = null, strict = false } = {}) {
|
|
86
|
+
const { rows, bad } = readAll(memDir)
|
|
87
|
+
if (strict && bad > 0) {
|
|
88
|
+
const error = new Error('封存日志有 ' + bad + ' 行无法解析,封存状态不确定')
|
|
89
|
+
error.code = 'SEAL_EVENTS_CORRUPT'
|
|
90
|
+
error.bad = bad
|
|
91
|
+
throw error
|
|
92
|
+
}
|
|
72
93
|
const last = new Map()
|
|
73
94
|
for (const r of rows) {
|
|
74
95
|
if (!before(r, until)) continue
|
package/lib/self-experience.d.ts
CHANGED
|
@@ -83,7 +83,10 @@ export interface Experience {
|
|
|
83
83
|
|
|
84
84
|
export const LIMITS: Record<string, number>
|
|
85
85
|
|
|
86
|
-
export function loadAll(dir: string, opts?: { asOf?: AsOf }): Experience[]
|
|
86
|
+
export function loadAll(dir: string, opts?: { asOf?: AsOf; allowSealCorrupt?: boolean }): Experience[]
|
|
87
|
+
|
|
88
|
+
/** 经历文件里解析不了的行数:展示路径遇到坏行会 fail closed,这个用于诊断和"先备份再修复" */
|
|
89
|
+
export function badLines(dir: string): number
|
|
87
90
|
|
|
88
91
|
export function addExperience(dir: string, opts: {
|
|
89
92
|
text: string
|
package/lib/self-experience.js
CHANGED
|
@@ -14,22 +14,72 @@ import { parseAsOf, before, dayOf } from './as-of.js'
|
|
|
14
14
|
const FILE = 'self-experience.jsonl'
|
|
15
15
|
const WEIGHTS = new Set(['important', 'normal', 'minor'])
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
// 坏行不再静默跳过:返回解析失败的行数,展示路径(strict)遇到坏行直接拒绝。
|
|
18
|
+
// 写入路径用非 strict:追加一条新记录不会碰坏行,坏行原样留在文件里等人工修复。
|
|
19
|
+
function readAll(dir, { strict = false } = {}) {
|
|
18
20
|
let raw
|
|
19
21
|
try {
|
|
20
22
|
raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
|
|
21
23
|
} catch (error) {
|
|
22
|
-
if (error.code === 'ENOENT') return []
|
|
23
|
-
|
|
24
|
+
if (error.code === 'ENOENT') return { rows: [], bad: 0 }
|
|
25
|
+
// 只有"还没有这个文件"能当空;权限、是目录、坏盘必须报出来,不能当成 0 条
|
|
26
|
+
throw experienceUnreadable(error)
|
|
24
27
|
}
|
|
25
28
|
const rows = []
|
|
29
|
+
let bad = 0
|
|
26
30
|
for (const line of raw.split('\n').filter(line => line.trim())) {
|
|
27
31
|
try { rows.push(JSON.parse(line)) }
|
|
28
|
-
catch {
|
|
29
|
-
|
|
30
|
-
|
|
32
|
+
catch { bad += 1 }
|
|
33
|
+
}
|
|
34
|
+
if (strict && bad > 0) throw experienceCorrupt(bad)
|
|
35
|
+
return { rows, bad }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function experienceCorrupt(bad) {
|
|
39
|
+
const error = new Error('经历文件有 ' + bad + ' 行无法解析:这里少了她写下的记录,不能当成空的照常展示(先备份再修复)。')
|
|
40
|
+
error.code = 'EXPERIENCE_CORRUPT'
|
|
41
|
+
error.bad = bad
|
|
42
|
+
return error
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function experienceUnreadable(cause) {
|
|
46
|
+
const error = new Error('经历文件读不出来(' + FILE + '):' + String(cause && cause.message ? cause.message : cause))
|
|
47
|
+
error.code = 'EXPERIENCE_UNREADABLE'
|
|
48
|
+
error.cause = cause
|
|
49
|
+
return error
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 坏行计数(体检 / 工具用):解析失败的行数。读文件本身失败仍然抛,不当成"0 行坏行"
|
|
53
|
+
export function badLines(dir) {
|
|
54
|
+
return readAll(dir).bad
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 事件文件:只有"还没有这个文件"能当空。读不出来(权限、是目录、坏盘)必须报出来,
|
|
58
|
+
// 否则正文可读、事件读不了时,这里会当成"她没想起过、也没后记、没结过案",替她编一段空白。
|
|
59
|
+
function eventsUnreadable(file, cause) {
|
|
60
|
+
const error = new Error('事件日志读不出来(' + path.basename(file) + '):' + String(cause && cause.message ? cause.message : cause))
|
|
61
|
+
error.code = 'EVENTS_UNREADABLE'
|
|
62
|
+
error.cause = cause
|
|
63
|
+
return error
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function readEvents(dir, eventsFile, read, onError = null) {
|
|
67
|
+
const file = eventsFile(dir)
|
|
68
|
+
try {
|
|
69
|
+
const st = fs.statSync(file)
|
|
70
|
+
if (!st.isFile()) throw Object.assign(new Error('not a regular file'), { code: 'EISDIR' })
|
|
71
|
+
const fd = fs.openSync(file, 'r')
|
|
72
|
+
fs.closeSync(fd)
|
|
73
|
+
} catch (error) {
|
|
74
|
+
// 还没有这组事件:当空是如实的
|
|
75
|
+
if (error.code === 'ENOENT') return read()
|
|
76
|
+
if (onError) return onError(file, error)
|
|
77
|
+
throw eventsUnreadable(file, error)
|
|
78
|
+
}
|
|
79
|
+
try { return read() } catch (error) {
|
|
80
|
+
if (onError) return onError(file, error)
|
|
81
|
+
throw eventsUnreadable(file, error)
|
|
31
82
|
}
|
|
32
|
-
return rows
|
|
33
83
|
}
|
|
34
84
|
|
|
35
85
|
// 字段上限:写的时候超了就报错,不静默截断
|
|
@@ -100,18 +150,32 @@ function normalize(r) {
|
|
|
100
150
|
|
|
101
151
|
// 读出经历并认领旧 id:一个旧 id 只对应一条旧记录、也没有别的记录显式用着它,才认领;
|
|
102
152
|
// 否则谁也不给(事件原样留在文件里),由 pendingLegacyEvents 报告
|
|
103
|
-
|
|
104
|
-
|
|
153
|
+
// strict:展示路径用,坏行直接抛(见 readAll)
|
|
154
|
+
function identify(dir, { strict = false } = {}) {
|
|
155
|
+
const raw = readAll(dir, { strict })
|
|
156
|
+
const rows = raw.rows.map(normalize).filter((r) => r && r.then && r.then.text)
|
|
105
157
|
const explicit = new Set(rows.filter((r) => !r.formerId).map((r) => r.id))
|
|
106
158
|
const owners = new Map()
|
|
107
159
|
for (const r of rows) {
|
|
108
|
-
if (r.formerId)
|
|
160
|
+
if (!r.formerId) continue
|
|
161
|
+
// push 而不是 [...旧数组, id]:四万条同一分钟的旧记录共用一个旧 id 时,后者是 O(n²)
|
|
162
|
+
const list = owners.get(r.formerId)
|
|
163
|
+
if (list) list.push(r.id)
|
|
164
|
+
else owners.set(r.formerId, [r.id])
|
|
165
|
+
}
|
|
166
|
+
// 同一个 id 在文件里出现两次(导入合并、手改都可能):只认最先写下的那条,
|
|
167
|
+
// 后面的标 duplicateOf,事件不再往它身上回填——否则一次「想起」会挂在两条上
|
|
168
|
+
const canonical = new Map()
|
|
169
|
+
for (const r of rows) {
|
|
170
|
+
const first = canonical.get(r.id)
|
|
171
|
+
if (first) { r.duplicateOf = first.id; continue }
|
|
172
|
+
canonical.set(r.id, r)
|
|
109
173
|
}
|
|
110
174
|
for (const r of rows) {
|
|
111
175
|
if (r.formerId && (owners.get(r.formerId).length !== 1 || explicit.has(r.formerId))) r.formerId = ''
|
|
112
176
|
if (!r.formerId) delete r.formerId
|
|
113
177
|
}
|
|
114
|
-
return { rows, owners, explicit }
|
|
178
|
+
return { rows, owners, explicit, bad: raw.bad }
|
|
115
179
|
}
|
|
116
180
|
|
|
117
181
|
// 出处的一句话摘要:只用来指路,全文用 read / currentView 看
|
|
@@ -122,35 +186,46 @@ const brief = (r) => {
|
|
|
122
186
|
|
|
123
187
|
// asOf:翻回那天的自己。只保留那一刻之前(含)写下的经历、后记、想起和选择;
|
|
124
188
|
// 那之后发生的一律看不见。不传 asOf 就是现在的样子
|
|
125
|
-
|
|
189
|
+
//
|
|
190
|
+
// 坏行(self-experience.jsonl 里有解析不了的行)默认 fail closed:返回的部分经历会
|
|
191
|
+
// 把"少了一条"装成"就这些",召回/书/体检都会当真。要按字节备份、恢复演练、计数这种
|
|
192
|
+
// 不展示内容的工具,传 allowCorrupt(导出/恢复那条路走 allowSealCorrupt,含义相同)。
|
|
193
|
+
export function loadAll(dir, { asOf = null, allowSealCorrupt = false, allowCorrupt = false } = {}) {
|
|
126
194
|
const until = parseAsOf(asOf)
|
|
127
|
-
const
|
|
195
|
+
const rawMode = Boolean(allowSealCorrupt || allowCorrupt)
|
|
196
|
+
const { rows: all } = identify(dir, { strict: !rawMode })
|
|
128
197
|
const rows = until === null ? all : all.filter((r) => before(r, until))
|
|
129
198
|
if (!rows.length) return rows
|
|
130
199
|
|
|
131
|
-
//
|
|
132
|
-
|
|
133
|
-
|
|
200
|
+
// 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段。
|
|
201
|
+
// 读不出来必须报出来(readEvents):否则会当成"她从没想起过"。
|
|
202
|
+
// rawMode(按字节备份/恢复/计数)不看事件内容,读不出来也不该拦住备份。
|
|
203
|
+
const onEventError = rawMode ? () => new Map() : null
|
|
204
|
+
const counts = readEvents(dir, recallEvents.eventsFile, () => recallEvents.countByExp(dir, { until }), onEventError)
|
|
134
205
|
|
|
135
206
|
// 改主意:旧 later 数组 + later-events 事件,按时间合并
|
|
136
|
-
|
|
137
|
-
try { laterMap = laterEvents.groupByExp(dir, { until }) } catch { }
|
|
207
|
+
const laterMap = readEvents(dir, laterEvents.eventsFile, () => laterEvents.groupByExp(dir, { until }), onEventError)
|
|
138
208
|
|
|
139
209
|
// 没弄完的事后来怎么样了:想通 / 暂放 / 再接着想
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
|
|
210
|
+
const unfinishedMap = readEvents(dir, unfinishedEvents.eventsFile, () => unfinishedEvents.latestByExp(dir, { until }), onEventError)
|
|
211
|
+
|
|
212
|
+
// 她选择封存的:不再被主动想起,但还在。
|
|
213
|
+
// 读不出来就抛出去,不能当成"什么都没封存"——否则正文可读、日志读不了时,
|
|
214
|
+
// 召回/醒来/书会把本该藏起来的经历重新拿出来。
|
|
215
|
+
// strict:坏行也算"状态未知",展示路径必须 fail closed。
|
|
216
|
+
// allowSealCorrupt:只给"按字节备份/恢复/计数"这种不展示内容的工具用;
|
|
217
|
+
// 它们要能保住损坏现场,但不能把结果当"可见"用。
|
|
218
|
+
const sealedMap = sealEvents.sealedByExp(dir, { until, strict: !allowSealCorrupt })
|
|
146
219
|
// 翻回那天时,她**现在**封存着的也不翻出来:封存说的是她现在不想被提起,而翻回那天正是在提起旧事。
|
|
147
220
|
// 那时还没封存的,标成 afterAsOf(后来才封存),各处过滤照常生效;点名读仍然给,并写明是后来封存的
|
|
148
221
|
let sealedNowMap = sealedMap
|
|
149
|
-
if (until !== null)
|
|
222
|
+
if (until !== null) sealedNowMap = sealEvents.sealedByExp(dir, { strict: !allowSealCorrupt })
|
|
150
223
|
|
|
151
224
|
const viewed = rows.map((r) => {
|
|
152
225
|
const keys = r.formerId ? [r.id, r.formerId] : [r.id]
|
|
153
|
-
|
|
226
|
+
// 同一个 id 出现两次时,事件只回填到最先写下的那条(duplicateOf):一次想起不该挂两条
|
|
227
|
+
const duplicate = Boolean(r.duplicateOf)
|
|
228
|
+
const extra = duplicate ? [] : keys.flatMap((k) => laterMap.get(k) || [])
|
|
154
229
|
const merged = [...(r.later || []).filter((l) => before(l, until)), ...extra]
|
|
155
230
|
.sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
|
|
156
231
|
const next = { ...r, later: merged }
|
|
@@ -161,9 +236,11 @@ export function loadAll(dir, { asOf = null } = {}) {
|
|
|
161
236
|
delete next.lastRecalledAt
|
|
162
237
|
}
|
|
163
238
|
let state = null
|
|
164
|
-
|
|
165
|
-
const
|
|
166
|
-
|
|
239
|
+
if (!duplicate) {
|
|
240
|
+
for (const k of keys) {
|
|
241
|
+
const st = unfinishedMap.get(k)
|
|
242
|
+
if (st) state = st
|
|
243
|
+
}
|
|
167
244
|
}
|
|
168
245
|
if (state && next.then && next.then.unfinished) next.unfinishedState = state
|
|
169
246
|
for (const k of keys) {
|
|
@@ -178,11 +255,13 @@ export function loadAll(dir, { asOf = null } = {}) {
|
|
|
178
255
|
}
|
|
179
256
|
let count = 0
|
|
180
257
|
let lastAt = ''
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
258
|
+
if (!duplicate) {
|
|
259
|
+
for (const k of keys) {
|
|
260
|
+
const c = counts.get(k)
|
|
261
|
+
if (!c) continue
|
|
262
|
+
count += c.count
|
|
263
|
+
if (c.lastAt > lastAt) lastAt = c.lastAt
|
|
264
|
+
}
|
|
186
265
|
}
|
|
187
266
|
if (count) {
|
|
188
267
|
next.recalls = count
|
|
@@ -195,7 +274,12 @@ export function loadAll(dir, { asOf = null } = {}) {
|
|
|
195
274
|
// 封存了的经历不露摘要:别的回想里只说"一件你封存了的事",不借着引用把它又提起来
|
|
196
275
|
const pointer = (r) => r.sealed ? { id: r.id, day: r.day, sealed: true } : brief(r)
|
|
197
276
|
const byId = new Map()
|
|
198
|
-
|
|
277
|
+
// 重复 id 不覆盖先写下的那条:指路一律指向它
|
|
278
|
+
for (const r of viewed) {
|
|
279
|
+
if (r.duplicateOf) continue
|
|
280
|
+
byId.set(r.id, r)
|
|
281
|
+
if (r.formerId) byId.set(r.formerId, r)
|
|
282
|
+
}
|
|
199
283
|
for (const r of viewed) {
|
|
200
284
|
const refs = (r.then && Array.isArray(r.then.refs)) ? r.then.refs : []
|
|
201
285
|
if (!refs.length) continue
|
|
@@ -208,13 +292,11 @@ export function loadAll(dir, { asOf = null } = {}) {
|
|
|
208
292
|
}
|
|
209
293
|
|
|
210
294
|
// 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
let chapterList = []
|
|
214
|
-
try { chapterList = chapterEvents.chapters(dir, { until }) } catch { }
|
|
295
|
+
const linkMap = readEvents(dir, linkEvents.eventsFile, () => linkEvents.linksByExp(dir, { until }), onEventError)
|
|
296
|
+
const chapterList = readEvents(dir, chapterEvents.eventsFile, () => chapterEvents.chapters(dir, { until }), rawMode ? () => [] : null)
|
|
215
297
|
for (const r of viewed) {
|
|
216
298
|
const keys = r.formerId ? [r.id, r.formerId] : [r.id]
|
|
217
|
-
const links = keys.flatMap((k) => linkMap.get(k) || [])
|
|
299
|
+
const links = !r.duplicateOf && keys.flatMap((k) => linkMap.get(k) || [])
|
|
218
300
|
.map((l) => {
|
|
219
301
|
const other = byId.get(l.other)
|
|
220
302
|
if (!other || other === r) return null
|
|
@@ -401,7 +483,7 @@ export function setUnfinishedState(dir, { id, choice, note = '' } = {}) {
|
|
|
401
483
|
|
|
402
484
|
// 单条:loadAll 会合并事件,这里绕开全量合并,只给存在性/未完判断用
|
|
403
485
|
function rowsById(dir, id) {
|
|
404
|
-
const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
|
|
486
|
+
const rows = readAll(dir).rows.map(normalize).filter((r) => r && r.then && r.then.text)
|
|
405
487
|
return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
|
|
406
488
|
}
|
|
407
489
|
|
|
@@ -421,8 +503,9 @@ export function currentView(dir, id, { asOf = null } = {}) {
|
|
|
421
503
|
|
|
422
504
|
// 相关度 × 重要度:重要的先被想起
|
|
423
505
|
// 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛;门槛口径见 query-match.js
|
|
424
|
-
// mode='strict'
|
|
425
|
-
// mode='loose'
|
|
506
|
+
// mode='strict'(默认):至少对上一个词,并且查询的意思至少 70% 被接住,宁可不召回也不硬凑
|
|
507
|
+
// mode='loose':比 strict 松,但最低比例还在(长查询仍要够一定比例的词命中),
|
|
508
|
+
// 适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
|
|
426
509
|
// mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
|
|
427
510
|
// asOf:在那天的自己里找(只读);翻旧日子不算"想起",所以不能和 mark 一起用
|
|
428
511
|
// 她封存了的经历不会被召回;includeSealed=true 只给"她自己要翻"这种明确场景用
|
|
@@ -456,14 +539,15 @@ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, mi
|
|
|
456
539
|
take(hits, 'later')
|
|
457
540
|
}
|
|
458
541
|
|
|
459
|
-
|
|
542
|
+
// 记录自身的规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
|
|
543
|
+
// cover 用原文拼起来的这段算(不要先归一化:拉丁词要按整词比,抹掉空格就成了一整个词)
|
|
544
|
+
const fieldsText = [
|
|
460
545
|
r.then.text, r.then.thought, (r.then.feeling || []).join(' '),
|
|
461
546
|
r.then.quote ? r.then.quote.text : '', r.then.quote ? r.then.quote.source : '',
|
|
462
547
|
(r.later || []).map(laterText).join(' ')
|
|
463
|
-
].join(' ')
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
return { n: matched.size, size, matchedIn: fields, matchedLater, cover: coverage(units, all) }
|
|
548
|
+
].join(' ')
|
|
549
|
+
const size = Math.max(1, normalizeText(fieldsText).length - 1)
|
|
550
|
+
return { n: matched.size, size, matchedIn: fields, matchedLater, cover: coverage(units, fieldsText) }
|
|
467
551
|
}
|
|
468
552
|
const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
|
|
469
553
|
const picked = rows.map((r) => {
|
|
@@ -471,7 +555,8 @@ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, mi
|
|
|
471
555
|
const legacy = gate === 'legacy'
|
|
472
556
|
return { r: { ...r, matchedIn, matchedLater }, n, cover, s: (n / Math.sqrt(size)) * weightOf(r) * (legacy ? 1 : 0.5 + cover) }
|
|
473
557
|
})
|
|
474
|
-
// strict(0.17 起):至少对上一个词,并且查询的意思至少 MIN_COVER 在这段记忆里找得到;
|
|
558
|
+
// strict(0.17 起):至少对上一个词,并且查询的意思至少 MIN_COVER 在这段记忆里找得到;
|
|
559
|
+
// loose:要够 minOverlap 个词,并且长查询还要够最低比例(requiredOverlap 里算)
|
|
475
560
|
.filter((x) => (!q ? true : mode === 'loose' || gate === 'legacy' ? x.n >= required : x.n >= minOverlap && x.cover >= MIN_COVER))
|
|
476
561
|
.sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
|
|
477
562
|
.slice(0, limit).map((x) => x.r)
|
|
@@ -617,8 +702,9 @@ export function renderTwoPart(entry, { now = new Date(), lang = 'zh' } = {}) {
|
|
|
617
702
|
|
|
618
703
|
export const internals = { WEIGHTS, FILE }
|
|
619
704
|
// 兼容旧调用:只要一句摘要的地方仍可用
|
|
620
|
-
//
|
|
621
|
-
//
|
|
622
|
-
|
|
705
|
+
// 宿主拿用户的原话直接来召回、再自动塞进提示词:默认走 strict 的新口径(cover)。
|
|
706
|
+
// 旧口径(legacy)在同批用例上编造率 27.8%(见 docs/eval.md),自动递回不能默认用它;
|
|
707
|
+
// 确实要保持 0.16 行为的宿主显式传 gate: 'legacy'。
|
|
708
|
+
export function recallForContext(dir, query, { max = 1, gate = 'cover' } = {}) {
|
|
623
709
|
return recall(dir, query, { limit: max, gate }).map((r) => ({ id: r.id, day: r.day, text: r.then.text, thought: r.then.thought, weight: r.weight, raw: r }))
|
|
624
710
|
}
|
package/lib/self-prompt.js
CHANGED
|
@@ -85,10 +85,15 @@ export function revert(dataDir, version, reason = '') {
|
|
|
85
85
|
try {
|
|
86
86
|
const key = String(version)
|
|
87
87
|
// 只接受 history.jsonl 里真实出现过的快照名:不把调用方给的字符串直接拼进路径
|
|
88
|
-
const known = history(dataDir, 100000).
|
|
88
|
+
const known = history(dataDir, 100000).find((h) => String(h.snapshot) === key)
|
|
89
89
|
if (!known) return { ok: false, error: 'Version not found.(找不到这个版本。)' }
|
|
90
90
|
const d = base(dataDir)
|
|
91
91
|
const body = fs.readFileSync(path.join(d, VERSIONS, key + '.md'), 'utf8')
|
|
92
|
+
// 快照被改过就不回退:history 里记着写下那一刻的 hash,对不上说明文件已经不是当初那份。
|
|
93
|
+
// 只比内容的话,改过的快照会被 revert 原样写回去,等于把篡改洗成新版本。
|
|
94
|
+
if (known.hash && sha1(clean(body)) !== known.hash) {
|
|
95
|
+
return { ok: false, error: 'Snapshot does not match the hash recorded in history; it may have been changed. Refusing to revert.(快照和 history 里记的 hash 对不上,可能被改过;拒绝回退。)' }
|
|
96
|
+
}
|
|
92
97
|
return save(dataDir, body, reason || ('回退到 ' + version))
|
|
93
98
|
} catch { return { ok: false, error: 'Version not found.(找不到这个版本。)' } }
|
|
94
99
|
}
|
|
@@ -109,15 +114,27 @@ export function render(basePrompt, dataDir, { marker = '\n\n<!-- 她自己的补
|
|
|
109
114
|
}
|
|
110
115
|
}
|
|
111
116
|
|
|
112
|
-
//
|
|
117
|
+
// 篡改检测:生效文件和最新快照要一致,而且要跟 history 里记的 hash 对得上。
|
|
118
|
+
// 只比「生效文件 vs 快照内容」不够:把两处改成同一份伪造内容就能蒙混过去;
|
|
119
|
+
// hash 是写入那一刻的指纹,改过快照/生效文件都会对不上。
|
|
113
120
|
export function verify(dataDir) {
|
|
114
121
|
const active = load(dataDir)
|
|
115
122
|
const h = history(dataDir, 1)[0]
|
|
116
123
|
if (!h) return { ok: active === '', note: active ? '有生效文件但没有历史版本。' : '还没有写过。' }
|
|
124
|
+
let found = true
|
|
117
125
|
let versionBody = ''
|
|
118
|
-
try { versionBody = clean(fs.readFileSync(path.join(base(dataDir), VERSIONS, String(h.snapshot) + '.md'), 'utf8')) } catch { }
|
|
119
|
-
const
|
|
120
|
-
|
|
126
|
+
try { versionBody = clean(fs.readFileSync(path.join(base(dataDir), VERSIONS, String(h.snapshot) + '.md'), 'utf8')) } catch { found = false }
|
|
127
|
+
const activeHash = sha1(active)
|
|
128
|
+
const versionHash = sha1(versionBody)
|
|
129
|
+
const recordedHash = typeof h.hash === 'string' ? h.hash : ''
|
|
130
|
+
const contentOk = found && active === versionBody
|
|
131
|
+
// 没有 hash 的老记录(0.21 之前)只能退回内容比对,并在 note 里说清楚
|
|
132
|
+
const ok = recordedHash ? found && activeHash === recordedHash && versionHash === recordedHash : contentOk
|
|
133
|
+
let note
|
|
134
|
+
if (!found) note = '最新版本文件不见了。'
|
|
135
|
+
else if (recordedHash && !ok) note = '快照或生效文件和 history 里记的 hash 对不上:被改过。'
|
|
136
|
+
else if (!recordedHash) note = '这条历史没有记 hash,只能比对内容。'
|
|
137
|
+
return { ok, activeHash, versionHash, version: h.snapshot, ...(note ? { note } : {}) }
|
|
121
138
|
}
|
|
122
139
|
|
|
123
140
|
export const internals = { MAX_CHARS, MAX_APPEND_TOTAL, VERSIONS, ACTIVE, sha1 }
|
|
@@ -21,6 +21,8 @@ export interface UnfinishedLatest {
|
|
|
21
21
|
|
|
22
22
|
export function eventsFile(memDir: string): string
|
|
23
23
|
export function append(memDir: string, opts: { id: string; choice: UnfinishedChoice; note?: string }, lockOpts?: Record<string, unknown>): UnfinishedEvent
|
|
24
|
+
/** 记一次选择(重复同一个选择是 noop;没关过的事 reopen 也是 noop) */
|
|
25
|
+
export function decide(memDir: string, opts: { id: string; choice: UnfinishedChoice; note?: string }, lockOpts?: Record<string, unknown>): { row: UnfinishedEvent | null; noop: boolean }
|
|
24
26
|
export function readAll(memDir: string): { rows: UnfinishedEvent[]; bad: number }
|
|
25
27
|
/** until:按这一刻(毫秒时间戳)之前(含)的选择重放 */
|
|
26
28
|
export function latestByExp(memDir: string, opts?: { until?: number | null }): Map<string, UnfinishedLatest>
|
package/lib/waking.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
import * as exp from './self-experience.js'
|
|
5
|
+
import { isPrivateScope } from './scope-key.js'
|
|
5
6
|
|
|
6
7
|
function readJsonl(file) {
|
|
7
8
|
try {
|
|
@@ -12,9 +13,10 @@ function readJsonl(file) {
|
|
|
12
13
|
function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
|
|
13
14
|
|
|
14
15
|
// 只认得出一对一的会话键(private_* / private:* / local_* / local:*);认不出的一律当成可能有别人在,宁可不给
|
|
15
|
-
|
|
16
|
+
// 判断本身在 scope-key.js:带群标记的写法(private:group_123、local_group_1……)也不算私聊,
|
|
17
|
+
// 醒来块、注入、未说出口抽屉问的是同一个实现。
|
|
16
18
|
function mayShow(key, allowGroup) {
|
|
17
|
-
return Boolean(key) && (allowGroup ||
|
|
19
|
+
return Boolean(key) && (allowGroup || isPrivateScope(key))
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
// 给宿主用的同一个判断:注入记忆前先问它,别自己写"不是群就行"
|
|
@@ -48,7 +50,8 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGrou
|
|
|
48
50
|
// 用合并后的视图:明确想通/暂放的不再进入未完列表;旧库没有状态事件,行为不变
|
|
49
51
|
// 她封存了的经历不出现在醒来块里,昨天的、没弄完的都一样
|
|
50
52
|
let loaded = []
|
|
51
|
-
|
|
53
|
+
// 封存状态读不出来时宁可不展示:醒来块是自动放进去的,不能把该藏的经历带出来。
|
|
54
|
+
try { loaded = exp.loadAll(dir) } catch { return '' }
|
|
52
55
|
const rows = loaded.filter((r) => !r.sealed).map((r) => ({
|
|
53
56
|
day: r.day,
|
|
54
57
|
text: r.then.text,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "whale-memory-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.1",
|
|
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",
|
|
@@ -120,6 +120,14 @@
|
|
|
120
120
|
"./fact-judge": {
|
|
121
121
|
"types": "./lib/fact-judge.d.ts",
|
|
122
122
|
"default": "./lib/fact-judge.js"
|
|
123
|
+
},
|
|
124
|
+
"./changed": {
|
|
125
|
+
"types": "./lib/changed.d.ts",
|
|
126
|
+
"default": "./lib/changed.js"
|
|
127
|
+
},
|
|
128
|
+
"./injection": {
|
|
129
|
+
"types": "./lib/injection.d.ts",
|
|
130
|
+
"default": "./lib/injection.js"
|
|
123
131
|
}
|
|
124
132
|
},
|
|
125
133
|
"files": [
|