whale-memory-core 0.11.1 → 0.14.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.
@@ -1,393 +1,560 @@
1
- // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import crypto from 'node:crypto'
5
- import * as recallEvents from './recall-events.js'
6
- import * as laterEvents from './later-events.js'
7
- import * as unfinishedEvents from './unfinished-events.js'
8
- import { queryTerms, requiredOverlap, matchedTerms, normalizeText } from './query-match.js'
9
-
10
- const FILE = 'self-experience.jsonl'
11
- const WEIGHTS = new Set(['important', 'normal', 'minor'])
12
-
13
- function readAll(dir, { rewriting = false } = {}) {
14
- let raw
15
- try {
16
- raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
17
- } catch (error) {
18
- if (error.code === 'ENOENT') return []
19
- throw error
20
- }
21
- const rows = []
22
- for (const line of raw.split('\n').filter(line => line.trim())) {
23
- try { rows.push(JSON.parse(line)) }
24
- catch {
25
- if (rewriting) throw new Error('经历文件含损坏记录,请备份并修复后再修改。')
26
- }
27
- }
28
- return rows
29
- }
30
-
31
- // 字段上限:写的时候超了就报错,不静默截断
32
- export const LIMITS = { text: 2000, scene: 500, thought: 1000, unfinished: 300, feelings: 8, kind: 20, laterThought: 1000, laterReason: 200 }
33
-
34
- function tooLong(name, value, max) {
35
- const n = String(value || '').length
36
- if (n > max) throw new Error(`${name} 太长(${n}/${max} 字),删一些或拆成两条再写。`)
37
- return String(value || '')
38
- }
39
-
40
- // 旧格式没有 id:用「时间 + 正文指纹」生成,避免同一分钟的多条记录撞成同一个身份
41
- // 只用记录里的内容生成,每次读取都得到同一个 id;没有 at 的旧记录用 noat 代替时间
42
- function legacyId(r) {
43
- const stamp = r.at ? String(r.at).replace(/\D/g, '').slice(0, 14) : 'noat'
44
- const body = String(r.text || '') + '\u0000' + String(r.thought || '') + '\u0000' + String(r.at || '')
45
- const fp = crypto.createHash('sha1').update(body).digest('hex').slice(0, 8)
46
- return 'exp_legacy_' + stamp + '_' + fp
47
- }
48
-
49
- // 0.10.0 之前的旧 id:只到分钟、不带指纹。那时写下的后记和想起事件挂在这个 id 上
50
- // 没有 at 的记录当时用的是 Date.now(),每次都不同,那些事件已无从对上
51
- function preV010Id(r) {
52
- return r.at ? 'exp_legacy_' + String(r.at).replace(/\D/g, '').slice(0, 12) : ''
53
- }
54
-
55
- function normalize(r) {
56
- if (!r) return null
57
- if (r.then && typeof r.then === 'object') {
58
- return { ...r, weight: WEIGHTS.has(r.weight) ? r.weight : 'normal', later: Array.isArray(r.later) ? r.later : [] }
59
- }
60
- // 旧格式:text/thought 在顶层
61
- return {
62
- id: r.id || legacyId(r),
63
- formerId: r.id ? '' : preV010Id(r),
64
- at: r.at || '',
65
- day: r.day || String(r.at || '').slice(0, 10),
66
- author: 'self',
67
- source: r.source || 'own-time',
68
- kind: r.kind || '其它',
69
- weight: WEIGHTS.has(r.weight) ? r.weight : 'normal',
70
- then: {
71
- text: String(r.text || ''),
72
- scene: '',
73
- feeling: [],
74
- thought: String(r.thought || ''),
75
- unfinished: '',
76
- quote: null,
77
- state: null
78
- },
79
- later: Array.isArray(r.later) ? r.later : [],
80
- status: r.status || 'kept',
81
- legacy: true
82
- }
83
- }
84
-
85
- // 读出经历并认领旧 id:一个旧 id 只对应一条旧记录、也没有别的记录显式用着它,才认领;
86
- // 否则谁也不给(事件原样留在文件里),由 pendingLegacyEvents 报告
87
- function identify(dir) {
88
- const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
89
- const explicit = new Set(rows.filter((r) => !r.formerId).map((r) => r.id))
90
- const owners = new Map()
91
- for (const r of rows) {
92
- if (r.formerId) owners.set(r.formerId, [...(owners.get(r.formerId) || []), r.id])
93
- }
94
- for (const r of rows) {
95
- if (r.formerId && (owners.get(r.formerId).length !== 1 || explicit.has(r.formerId))) r.formerId = ''
96
- if (!r.formerId) delete r.formerId
97
- }
98
- return { rows, owners, explicit }
99
- }
100
-
101
- export function loadAll(dir) {
102
- const { rows } = identify(dir)
103
- if (!rows.length) return rows
104
-
105
- // 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段
106
- let counts = new Map()
107
- try { counts = recallEvents.countByExp(dir) } catch { /* 事件文件坏了也不影响读经历 */ }
108
-
109
- // 改主意:旧 later 数组 + later-events 事件,按时间合并
110
- let laterMap = new Map()
111
- try { laterMap = laterEvents.groupByExp(dir) } catch { }
112
-
113
- // 没弄完的事后来怎么样了:想通 / 暂放 / 再接着想
114
- let unfinishedMap = new Map()
115
- try { unfinishedMap = unfinishedEvents.latestByExp(dir) } catch { }
116
-
117
- return rows.map((r) => {
118
- const keys = r.formerId ? [r.id, r.formerId] : [r.id]
119
- const extra = keys.flatMap((k) => laterMap.get(k) || [])
120
- const merged = [...(r.later || []), ...extra]
121
- .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
122
- const next = { ...r, later: merged }
123
- let state = null
124
- for (const k of keys) {
125
- const st = unfinishedMap.get(k)
126
- if (st) state = st
127
- }
128
- if (state && next.then && next.then.unfinished) next.unfinishedState = state
129
- let count = 0
130
- let lastAt = ''
131
- for (const k of keys) {
132
- const c = counts.get(k)
133
- if (!c) continue
134
- count += c.count
135
- if (c.lastAt > lastAt) lastAt = c.lastAt
136
- }
137
- if (count) {
138
- next.recalls = count
139
- next.lastRecalledAt = lastAt || r.lastRecalledAt || ''
140
- }
141
- return next
142
- })
143
- }
144
-
145
- // 挂在 0.10.0 之前的旧 id 上、但这个 id 有几条旧记录共用:事件原样保留,只报告,不替她挑
146
- export function pendingLegacyEvents(dir) {
147
- const { owners, explicit } = identify(dir)
148
- let counts = new Map()
149
- let laterMap = new Map()
150
- try { counts = recallEvents.countByExp(dir) } catch { }
151
- try { laterMap = laterEvents.groupByExp(dir) } catch { }
152
- const out = []
153
- for (const [id, candidates] of owners) {
154
- if (candidates.length < 2 || explicit.has(id)) continue
155
- const later = (laterMap.get(id) || []).length
156
- const recalls = counts.get(id) ? counts.get(id).count : 0
157
- if (later || recalls) out.push({ id, candidates, later, recalls })
158
- }
159
- return out
160
- }
161
-
162
- // 把调用方给的 id 落到一条现存经历上:认当前 id,也认唯一对应的旧 id
163
- // 旧 id 被几条旧经历共用时不落到任何一条上,返回 ambiguous 让调用方说清楚
164
- function resolveId(dir, id) {
165
- const { rows, owners } = identify(dir)
166
- const hit = rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id)
167
- if (hit) return { id: hit.id }
168
- return { id: '', ambiguous: (owners.get(id) || []).length > 1 }
169
- }
170
-
171
- // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
172
- export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time' }) {
173
- if (!String(text || '').trim()) throw new Error('text 不能是空的。')
174
- const safeText = tooLong('text', text, LIMITS.text)
175
- const safeScene = tooLong('scene', scene, LIMITS.scene)
176
- const safeThought = tooLong('thought', thought, LIMITS.thought)
177
- const safeUnfinished = tooLong('unfinished', unfinished, LIMITS.unfinished)
178
- const safeKind = tooLong('kind', kind || '其它', LIMITS.kind)
179
- const feelings = (Array.isArray(feeling) ? feeling : [feeling]).map((f) => String(f || '').trim()).filter(Boolean)
180
- if (feelings.length > LIMITS.feelings) throw new Error(`feeling 最多 ${LIMITS.feelings} 个,现在是 ${feelings.length} 个。`)
181
-
182
- fs.mkdirSync(dir, { recursive: true })
183
- const now = new Date()
184
- const id = 'exp_' + now.getTime().toString(36) + Math.random().toString(36).slice(2, 6)
185
- const row = {
186
- id,
187
- at: now.toISOString(),
188
- day: now.toLocaleDateString('sv-SE'),
189
- author: 'self',
190
- source,
191
- kind: safeKind,
192
- weight: WEIGHTS.has(weight) ? weight : 'normal',
193
- then: {
194
- text: safeText,
195
- scene: safeScene,
196
- feeling: feelings,
197
- thought: safeThought,
198
- unfinished: safeUnfinished,
199
- quote: quote && quote.text ? { text: tooLong('quote', quote.text, 500), source: tooLong('quote.source', quote.source || '', 120) } : null,
200
- state: state && typeof state === 'object' ? { at: now.toISOString(), ...state } : { at: now.toISOString() }
201
- },
202
- later: [],
203
- status: 'kept'
204
- }
205
- const fd = fs.openSync(path.join(dir, FILE), 'a+')
206
- try {
207
- const size = fs.fstatSync(fd).size
208
- const lastByte = Buffer.alloc(1)
209
- if (size) fs.readSync(fd, lastByte, 0, 1, size - 1)
210
- const separator = size && lastByte[0] !== 10 ? '\n' : ''
211
- fs.writeFileSync(fd, separator + JSON.stringify(row) + '\n', 'utf8')
212
- } finally {
213
- fs.closeSync(fd)
214
- }
215
- return row
216
- }
217
-
218
- // 改主意 / 回头想:只追加一条 later 事件,不重写经历文件
219
- // 先确认这条经历真的在:id 抄错时明说找不到,不留一条谁也看不见的后记
220
- export function reviseExperience(dir, { id, thought, reason = '' }) {
221
- if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
222
- if (!String(thought || '').trim()) return { ok: false, error: 'thought 不能是空的。' }
223
- try {
224
- const safeThought = tooLong('thought', thought, LIMITS.laterThought)
225
- const safeReason = tooLong('reason', reason, LIMITS.laterReason)
226
- const target = resolveId(dir, String(id))
227
- if (target.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id 来改。' }
228
- if (!target.id) return { ok: false, error: '找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。' }
229
- const row = laterEvents.append(dir, { id: target.id, thought: safeThought, reason: safeReason })
230
- return { ok: true, id: row.id, at: row.at }
231
- } catch (e) {
232
- return { ok: false, error: String(e && e.message ? e.message : e) }
233
- }
234
- }
235
-
236
- // 「这件没弄完的事」后来怎么样了:done / shelved / reopen
237
- // 只追加一条状态事件;不改 then.unfinished,也不写成后记
238
- // 重复同一个选择不写第二条;没关过的事 reopen 是空操作
239
- export function setUnfinishedState(dir, { id, choice, note = '' } = {}) {
240
- if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
241
- if (!unfinishedEvents.CHOICES.has(choice)) return { ok: false, error: 'state 只能是 done / shelved / reopen' }
242
- try {
243
- const target = resolveId(dir, String(id))
244
- if (target.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id。' }
245
- if (!target.id) return { ok: false, error: '找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。' }
246
- const row = rowsById(dir, target.id)
247
- if (!row || !row.then || !row.then.unfinished) return { ok: false, error: '这条经历没有「还没弄完」的内容,不需要结案。' }
248
-
249
- const latest = unfinishedEvents.latestByExp(dir).get(target.id)
250
- if (latest && latest.choice === choice) return { ok: true, id: target.id, at: latest.at, noop: true }
251
- if (choice === 'reopen' && !latest) return { ok: true, id: target.id, at: '', noop: true }
252
-
253
- const event = unfinishedEvents.append(dir, { id: target.id, choice, note: tooLong('note', note, 200) })
254
- return { ok: true, id: target.id, at: event.at, choice, noop: false }
255
- } catch (e) {
256
- return { ok: false, error: String(e && e.message ? e.message : e) }
257
- }
258
- }
259
-
260
- // 单条:loadAll 会合并事件,这里绕开全量合并,只给存在性/未完判断用
261
- function rowsById(dir, id) {
262
- const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
263
- return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
264
- }
265
-
266
- // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
267
- // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
268
- export function markRecalled(dir, id) {
269
- if (!String(id || '').trim()) return false
270
- try { recallEvents.append(dir, { id: String(id) }) } catch { return false }
271
- return true
272
- }
273
-
274
- export function currentView(dir, id) {
275
- const rows = loadAll(dir)
276
- return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
277
- }
278
-
279
- // 相关度 × 重要度:重要的先被想起
280
- // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛;门槛口径见 query-match.js
281
- // mode='strict'(默认):长查询要求 ≥60% 命中,宁可不召回也不硬凑
282
- // mode='loose':只要求至少一个实词命中,适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
283
- // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
284
- export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict' } = {}) {
285
- const rows = loadAll(dir)
286
- const q = String(query || '')
287
- const parsed = queryTerms(q)
288
- const { terms } = parsed
289
- const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
290
-
291
- const measure = (r) => {
292
- const fields = []
293
- const matched = new Set()
294
- const take = (hits, label) => {
295
- if (!hits.size) return
296
- for (const g of hits) matched.add(g)
297
- if (!fields.includes(label)) fields.push(label)
298
- }
299
- // 最初写下的、原文锚、后来才明白的:都参与匹配;后记逐条看,记下是哪几条让它被想起
300
- take(matchedTerms(terms, r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' ')), 'then')
301
- if (r.then.quote) take(matchedTerms(terms, (r.then.quote.text || '') + ' ' + (r.then.quote.source || '')), 'quote')
302
- const matchedLater = []
303
- for (const l of r.later || []) {
304
- const hits = matchedTerms(terms, l.thought)
305
- if (hits.size) matchedLater.push(l)
306
- take(hits, 'later')
307
- }
308
-
309
- const all = normalizeText([
310
- r.then.text, r.then.thought, (r.then.feeling || []).join(' '),
311
- r.then.quote ? r.then.quote.text : '', r.then.quote ? r.then.quote.source : '',
312
- (r.later || []).map((l) => l.thought).join(' ')
313
- ].join(' '))
314
- // 记录自身的规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
315
- const size = Math.max(1, all.length - 1)
316
- return { n: matched.size, size, matchedIn: fields, matchedLater }
317
- }
318
- const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
319
- const picked = rows.map((r) => {
320
- const { n, size, matchedIn, matchedLater } = measure(r)
321
- return { r: { ...r, matchedIn, matchedLater }, n, s: (n / Math.sqrt(size)) * weightOf(r) }
322
- })
323
- .filter((x) => (q ? x.n >= required : true))
324
- .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
325
- .slice(0, limit).map((x) => x.r)
326
-
327
- if (!mark || !picked.length) return picked
328
-
329
- // 记完就地 +1,不回读全量;下一次读取自然会对上
330
- const at = new Date().toISOString()
331
- for (const r of picked) {
332
- try { recallEvents.append(dir, { id: r.id, query: q }) } catch { /* 坏文件时不阻断召回 */ }
333
- }
334
- return picked.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
335
- }
336
-
337
- const laterDay = (l) => l.day || String(l.at || '').slice(0, 10)
338
- const sameLater = (a, b) => a === b || (a.at === b.at && a.thought === b.thought)
339
-
340
- // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
341
- // 后记:这次是被哪条后记想起的,就把那条原样给她;再给最近的一条。各带各的日子,不截断
342
- export function renderTwoPart(entry, { now = new Date() } = {}) {
343
- if (!entry) return ''
344
- const t = entry.then
345
- const when = new Date(entry.at || entry.day)
346
- const hh = Number.isNaN(when.getTime()) ? '' : when.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
347
- const lines = []
348
- lines.push('【当时】')
349
- lines.push('- 时间:' + (entry.day || '') + (hh ? ' ' + hh : ''))
350
- if (t.scene) lines.push('- 场景:' + t.scene)
351
- if (t.quote && t.quote.text) lines.push('- 我读到的原文:' + t.quote.text + (t.quote.source ? '(' + t.quote.source + ')' : ''))
352
- lines.push('- 我写下的话:' + t.text)
353
- if ((t.feeling || []).length) lines.push('- 当时的感觉:' + t.feeling.join('、'))
354
- if (t.thought) lines.push('- 当时的想法:' + t.thought)
355
- if (t.unfinished) lines.push('- 还没完的:' + t.unfinished)
356
- if (t.state && t.state.mood) lines.push('- 记录里的情绪:' + t.state.mood)
357
- if (entry.legacy && !t.quote) lines.push('- (这条只留下感想,当时的原文没记)')
358
- lines.push('', '【现在】')
359
- lines.push('- 现在时间:' + now.toLocaleString('zh-CN', { hour12: false }))
360
- lines.push('- 这条被你想起过 ' + Number(entry.recalls || 0) + ' 次' + (entry.lastRecalledAt ? ',上次是 ' + String(entry.lastRecalledAt).slice(0, 10) : ''))
361
- const later = Array.isArray(entry.later) ? entry.later : []
362
- if (later.length) {
363
- const last = later[later.length - 1]
364
- const hits = (entry.matchedLater || []).filter((l) => !sameLater(l, last))
365
- for (const l of hits) lines.push('- 这次想起它,是因为后来写过:' + String(l.thought || '') + '(' + laterDay(l) + ')')
366
- lines.push((hits.length ? '- 最近一次回头想:' : '- 后来你想过:') + String(last.thought || '') + '(' + laterDay(last) + ')')
367
- const shown = hits.length + 1
368
- if (later.length > shown) lines.push('- (后来一共回头想过 ' + later.length + ' 次,这里没列出的 ' + (later.length - shown) + ' 次可以用 read 看)')
369
- } else {
370
- lines.push('- 之后你还没回头想过')
371
- }
372
- const st = entry.unfinishedState
373
- if (st && t.unfinished) {
374
- const when2 = st.day || String(st.at || '').slice(0, 10)
375
- if (st.choice === 'done') {
376
- lines.push('- 这件没弄完的事已经想通了:' + t.unfinished + '(' + when2 + ')')
377
- } else if (st.choice === 'shelved') {
378
- lines.push('- 这件没弄完的事先放下了,还没有想通:' + t.unfinished + '(' + when2 + ')')
379
- } else if (st.choice === 'reopen') {
380
- const history = st.history || []
381
- if (history.includes('shelved')) lines.push('- 这件事中间放下过,后来又决定接着想:' + t.unfinished + '(' + when2 + ')')
382
- else if (history.includes('done')) lines.push('- 这件事本来觉得想通了,后来又决定接着想:' + t.unfinished + '(' + when2 + ')')
383
- }
384
- }
385
- lines.push('', '以上是那天留下的全部;没留下的,我不记得。')
386
- return lines.join('\n')
387
- }
388
-
389
- export const internals = { WEIGHTS, FILE }
390
- // 兼容旧调用:只要一句摘要的地方仍可用
391
- export function recallForContext(dir, query, { max = 1 } = {}) {
392
- 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 }))
393
- }
1
+ // 她自己的经历 v2:写下时拍下"当时",回想分「当时 / 现在」两段;重要的写细,次要的简写
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+ import * as recallEvents from './recall-events.js'
6
+ import * as laterEvents from './later-events.js'
7
+ import * as unfinishedEvents from './unfinished-events.js'
8
+ import * as sealEvents from './seal-events.js'
9
+ import * as linkEvents from './link-events.js'
10
+ import * as chapterEvents from './chapter-events.js'
11
+ import { queryTerms, requiredOverlap, matchedTerms, normalizeText } from './query-match.js'
12
+ import { parseAsOf, before, dayOf } from './as-of.js'
13
+
14
+ const FILE = 'self-experience.jsonl'
15
+ const WEIGHTS = new Set(['important', 'normal', 'minor'])
16
+
17
+ function readAll(dir, { rewriting = false } = {}) {
18
+ let raw
19
+ try {
20
+ raw = fs.readFileSync(path.join(dir, FILE), 'utf8')
21
+ } catch (error) {
22
+ if (error.code === 'ENOENT') return []
23
+ throw error
24
+ }
25
+ const rows = []
26
+ for (const line of raw.split('\n').filter(line => line.trim())) {
27
+ try { rows.push(JSON.parse(line)) }
28
+ catch {
29
+ if (rewriting) throw new Error('经历文件含损坏记录,请备份并修复后再修改。')
30
+ }
31
+ }
32
+ return rows
33
+ }
34
+
35
+ // 字段上限:写的时候超了就报错,不静默截断
36
+ export const LIMITS = { text: 2000, scene: 500, thought: 1000, unfinished: 300, feelings: 8, feelingWord: 20, kind: 20, laterThought: 1000, laterReason: 200, refs: 8 }
37
+
38
+ // 感觉词:逗号分隔的字符串或数组都收;去空白、去重;超了就报错,不静默丢
39
+ function feelingList(feeling, { name = 'feeling', perWord = false } = {}) {
40
+ const raw = Array.isArray(feeling) ? feeling : String(feeling || '').split(/[,,、]/)
41
+ const out = []
42
+ for (const f of raw.map((x) => String(x || '').trim()).filter(Boolean)) {
43
+ if (perWord && f.length > LIMITS.feelingWord) throw new Error(`${name} 里的「${f.slice(0, 10)}…」太长(${f.length}/${LIMITS.feelingWord} 字),感觉写成词就好。`)
44
+ if (!out.includes(f)) out.push(f)
45
+ }
46
+ if (out.length > LIMITS.feelings) throw new Error(`${name} 最多 ${LIMITS.feelings} 个,现在是 ${out.length} 个。`)
47
+ return out
48
+ }
49
+
50
+ function tooLong(name, value, max) {
51
+ const n = String(value || '').length
52
+ if (n > max) throw new Error(`${name} 太长(${n}/${max} 字),删一些或拆成两条再写。`)
53
+ return String(value || '')
54
+ }
55
+
56
+ // 旧格式没有 id:用「时间 + 正文指纹」生成,避免同一分钟的多条记录撞成同一个身份
57
+ // 只用记录里的内容生成,每次读取都得到同一个 id;没有 at 的旧记录用 noat 代替时间
58
+ function legacyId(r) {
59
+ const stamp = r.at ? String(r.at).replace(/\D/g, '').slice(0, 14) : 'noat'
60
+ const body = String(r.text || '') + '\u0000' + String(r.thought || '') + '\u0000' + String(r.at || '')
61
+ const fp = crypto.createHash('sha1').update(body).digest('hex').slice(0, 8)
62
+ return 'exp_legacy_' + stamp + '_' + fp
63
+ }
64
+
65
+ // 0.10.0 之前的旧 id:只到分钟、不带指纹。那时写下的后记和想起事件挂在这个 id 上
66
+ // 没有 at 的记录当时用的是 Date.now(),每次都不同,那些事件已无从对上
67
+ function preV010Id(r) {
68
+ return r.at ? 'exp_legacy_' + String(r.at).replace(/\D/g, '').slice(0, 12) : ''
69
+ }
70
+
71
+ function normalize(r) {
72
+ if (!r) return null
73
+ if (r.then && typeof r.then === 'object') {
74
+ return { ...r, weight: WEIGHTS.has(r.weight) ? r.weight : 'normal', later: Array.isArray(r.later) ? r.later : [] }
75
+ }
76
+ // 旧格式:text/thought 在顶层
77
+ return {
78
+ id: r.id || legacyId(r),
79
+ formerId: r.id ? '' : preV010Id(r),
80
+ at: r.at || '',
81
+ day: r.day || String(r.at || '').slice(0, 10),
82
+ author: 'self',
83
+ source: r.source || 'own-time',
84
+ kind: r.kind || '其它',
85
+ weight: WEIGHTS.has(r.weight) ? r.weight : 'normal',
86
+ then: {
87
+ text: String(r.text || ''),
88
+ scene: '',
89
+ feeling: [],
90
+ thought: String(r.thought || ''),
91
+ unfinished: '',
92
+ quote: null,
93
+ state: null
94
+ },
95
+ later: Array.isArray(r.later) ? r.later : [],
96
+ status: r.status || 'kept',
97
+ legacy: true
98
+ }
99
+ }
100
+
101
+ // 读出经历并认领旧 id:一个旧 id 只对应一条旧记录、也没有别的记录显式用着它,才认领;
102
+ // 否则谁也不给(事件原样留在文件里),由 pendingLegacyEvents 报告
103
+ function identify(dir) {
104
+ const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
105
+ const explicit = new Set(rows.filter((r) => !r.formerId).map((r) => r.id))
106
+ const owners = new Map()
107
+ for (const r of rows) {
108
+ if (r.formerId) owners.set(r.formerId, [...(owners.get(r.formerId) || []), r.id])
109
+ }
110
+ for (const r of rows) {
111
+ if (r.formerId && (owners.get(r.formerId).length !== 1 || explicit.has(r.formerId))) r.formerId = ''
112
+ if (!r.formerId) delete r.formerId
113
+ }
114
+ return { rows, owners, explicit }
115
+ }
116
+
117
+ // 出处的一句话摘要:只用来指路,全文用 read / currentView 看
118
+ const brief = (r) => {
119
+ const s = String((r.then && r.then.text) || '')
120
+ return { id: r.id, day: r.day, text: [...s].length > 24 ? [...s].slice(0, 24).join('') + '…' : s }
121
+ }
122
+
123
+ // asOf:翻回那天的自己。只保留那一刻之前(含)写下的经历、后记、想起和选择;
124
+ // 那之后发生的一律看不见。不传 asOf 就是现在的样子
125
+ export function loadAll(dir, { asOf = null } = {}) {
126
+ const until = parseAsOf(asOf)
127
+ const { rows: all } = identify(dir)
128
+ const rows = until === null ? all : all.filter((r) => before(r, until))
129
+ if (!rows.length) return rows
130
+
131
+ // 想起次数:有事件文件就以事件为准;没有事件时才退回旧字段
132
+ let counts = new Map()
133
+ try { counts = recallEvents.countByExp(dir, { until }) } catch { /* 事件文件坏了也不影响读经历 */ }
134
+
135
+ // 改主意:旧 later 数组 + later-events 事件,按时间合并
136
+ let laterMap = new Map()
137
+ try { laterMap = laterEvents.groupByExp(dir, { until }) } catch { }
138
+
139
+ // 没弄完的事后来怎么样了:想通 / 暂放 / 再接着想
140
+ let unfinishedMap = new Map()
141
+ try { unfinishedMap = unfinishedEvents.latestByExp(dir, { until }) } catch { }
142
+
143
+ // 她选择封存的:不再被主动想起,但还在
144
+ let sealedMap = new Map()
145
+ try { sealedMap = sealEvents.sealedByExp(dir, { until }) } catch { }
146
+
147
+ const viewed = rows.map((r) => {
148
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
149
+ const extra = keys.flatMap((k) => laterMap.get(k) || [])
150
+ const merged = [...(r.later || []).filter((l) => before(l, until)), ...extra]
151
+ .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
152
+ const next = { ...r, later: merged }
153
+ if (until !== null) {
154
+ next.viewAsOf = new Date(until).toISOString()
155
+ // 旧格式行内的 recalls 没有时间,放不到那天的时间线上
156
+ delete next.recalls
157
+ delete next.lastRecalledAt
158
+ }
159
+ let state = null
160
+ for (const k of keys) {
161
+ const st = unfinishedMap.get(k)
162
+ if (st) state = st
163
+ }
164
+ if (state && next.then && next.then.unfinished) next.unfinishedState = state
165
+ for (const k of keys) {
166
+ const s = sealedMap.get(k)
167
+ if (s) next.sealed = s
168
+ }
169
+ let count = 0
170
+ let lastAt = ''
171
+ for (const k of keys) {
172
+ const c = counts.get(k)
173
+ if (!c) continue
174
+ count += c.count
175
+ if (c.lastAt > lastAt) lastAt = c.lastAt
176
+ }
177
+ if (count) {
178
+ next.recalls = count
179
+ next.lastRecalledAt = lastAt || (until === null ? r.lastRecalledAt : '') || ''
180
+ }
181
+ return next
182
+ })
183
+
184
+ // 出处(这条是从哪几件事想到的)和反向引用(后来有哪些回想提到它):都从 then.refs 派生
185
+ // 封存了的经历不露摘要:别的回想里只说"一件你封存了的事",不借着引用把它又提起来
186
+ const pointer = (r) => r.sealed ? { id: r.id, day: r.day, sealed: true } : brief(r)
187
+ const byId = new Map()
188
+ for (const r of viewed) { byId.set(r.id, r); if (r.formerId) byId.set(r.formerId, r) }
189
+ for (const r of viewed) {
190
+ const refs = (r.then && Array.isArray(r.then.refs)) ? r.then.refs : []
191
+ if (!refs.length) continue
192
+ r.refsInfo = refs.map((id) => { const hit = byId.get(id); return hit ? pointer(hit) : { id, missing: true } })
193
+ for (const id of refs) {
194
+ const target = byId.get(id)
195
+ if (!target || target === r) continue
196
+ target.citedBy = [...(target.citedBy || []), pointer(r)]
197
+ }
198
+ }
199
+
200
+ // 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
201
+ let linkMap = new Map()
202
+ try { linkMap = linkEvents.linksByExp(dir, { until }) } catch { }
203
+ let chapterList = []
204
+ try { chapterList = chapterEvents.chapters(dir, { until }) } catch { }
205
+ for (const r of viewed) {
206
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
207
+ const links = keys.flatMap((k) => linkMap.get(k) || [])
208
+ .map((l) => {
209
+ const other = byId.get(l.other)
210
+ if (!other || other === r) return null
211
+ // 另一头封存了:只给 id 和日子,连理由也不露,免得借联想又把它提起来
212
+ if (other.sealed) return { id: other.id, day: other.day, sealed: true, linkDay: l.day }
213
+ return { ...pointer(other), reason: l.reason, linkDay: l.day }
214
+ })
215
+ .filter(Boolean)
216
+ if (links.length) r.links = links
217
+ const ch = chapterEvents.chaptersOn(chapterList, r.day || '')
218
+ if (ch.length) r.chapters = ch.map((c) => ({ id: c.id, name: c.name }))
219
+ }
220
+ return viewed
221
+ }
222
+
223
+ // 事后联想:她发现两件事有关,亲手连起来,并说清为什么。两条都必须存在;同一对只连一次
224
+ export function linkExperiences(dir, { from, to, reason = '' } = {}) {
225
+ if (!String(from || '').trim() || !String(to || '').trim()) return { ok: false, error: '需要 from 与 to 两条经历的 id' }
226
+ if (!String(reason || '').trim()) return { ok: false, error: '说一句为什么把它们连起来(reason)。说不出来就先别连。' }
227
+ try {
228
+ const why = tooLong('reason', String(reason).trim(), LIMITS.laterReason)
229
+ const a = resolveId(dir, String(from))
230
+ const b = resolveId(dir, String(to))
231
+ for (const [x, t] of [[from, a], [to, b]]) {
232
+ if (t.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + x + '。用 read 里列出的当前 id。' }
233
+ if (!t.id) return { ok: false, error: '找不到这条经历:' + x + '。先用 read 看一下 id。' }
234
+ }
235
+ const res = linkEvents.link(dir, { from: a.id, to: b.id, reason: why })
236
+ return { ok: true, from: a.id, to: b.id, noop: res.noop, ...(res.row ? { at: res.row.at } : {}) }
237
+ } catch (e) {
238
+ return { ok: false, error: String(e && e.message ? e.message : e) }
239
+ }
240
+ }
241
+
242
+ // 封存 / 解封:她不想再被这件事主动提醒了,或者又愿意了
243
+ // 不删除任何东西;重复同一个动作不写第二条
244
+ export function setSealed(dir, { id, sealed = true, note = '' } = {}) {
245
+ if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
246
+ try {
247
+ const target = resolveId(dir, String(id))
248
+ if (target.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id。' }
249
+ if (!target.id) return { ok: false, error: '找不到这条经历:' + id + '。先用 read 看一下 id。' }
250
+ const action = sealed ? 'seal' : 'unseal'
251
+ const decided = sealEvents.decide(dir, { id: target.id, action, note: tooLong('note', note, 200) })
252
+ return { ok: true, id: target.id, sealed: Boolean(sealed), at: decided.row ? decided.row.at : '', noop: decided.noop }
253
+ } catch (e) {
254
+ return { ok: false, error: String(e && e.message ? e.message : e) }
255
+ }
256
+ }
257
+
258
+ // 挂在 0.10.0 之前的旧 id 上、但这个 id 有几条旧记录共用:事件原样保留,只报告,不替她挑
259
+ export function pendingLegacyEvents(dir) {
260
+ const { owners, explicit } = identify(dir)
261
+ let counts = new Map()
262
+ let laterMap = new Map()
263
+ try { counts = recallEvents.countByExp(dir) } catch { }
264
+ try { laterMap = laterEvents.groupByExp(dir) } catch { }
265
+ const out = []
266
+ for (const [id, candidates] of owners) {
267
+ if (candidates.length < 2 || explicit.has(id)) continue
268
+ const later = (laterMap.get(id) || []).length
269
+ const recalls = counts.get(id) ? counts.get(id).count : 0
270
+ if (later || recalls) out.push({ id, candidates, later, recalls })
271
+ }
272
+ return out
273
+ }
274
+
275
+ // 把调用方给的 id 落到一条现存经历上:认当前 id,也认唯一对应的旧 id
276
+ // 旧 id 被几条旧经历共用时不落到任何一条上,返回 ambiguous 让调用方说清楚
277
+ function resolveId(dir, id) {
278
+ const { rows, owners } = identify(dir)
279
+ const hit = rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id)
280
+ if (hit) return { id: hit.id }
281
+ return { id: '', ambiguous: (owners.get(id) || []).length > 1 }
282
+ }
283
+
284
+ // 出处:回想只能引用已经写下的经历。找不到、或旧 id 有歧义,就整条不写,并说清是哪一个
285
+ function resolveRefs(dir, refs) {
286
+ const list = (Array.isArray(refs) ? refs : String(refs || '').split(/[,,\s]+/)).map((s) => String(s || '').trim()).filter(Boolean)
287
+ if (!list.length) return []
288
+ if (list.length > LIMITS.refs) throw new Error(`出处最多 ${LIMITS.refs} 条,现在是 ${list.length} 条。挑最主要的几件写。`)
289
+ const { rows, owners } = identify(dir)
290
+ const out = []
291
+ for (const x of list) {
292
+ const hit = rows.find((r) => r.id === x) || rows.find((r) => r.formerId === x)
293
+ if (!hit && (owners.get(x) || []).length > 1) throw new Error('出处里的旧 id 有几条经历共用:' + x + '。用 read 里列出的当前 id。')
294
+ if (!hit) throw new Error('出处里有找不到的经历:' + x + '。回想只能引用已经写下的经历。')
295
+ if (!out.includes(hit.id)) out.push(hit.id)
296
+ }
297
+ return out
298
+ }
299
+
300
+ // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
301
+ // refs:这条是从哪几件事想到的(回想、归纳时用)。写入时就校验,引用不存在的经历直接拒绝
302
+ export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time', refs = [] }) {
303
+ if (!String(text || '').trim()) throw new Error('text 不能是空的。')
304
+ const safeText = tooLong('text', text, LIMITS.text)
305
+ const safeScene = tooLong('scene', scene, LIMITS.scene)
306
+ const safeThought = tooLong('thought', thought, LIMITS.thought)
307
+ const safeUnfinished = tooLong('unfinished', unfinished, LIMITS.unfinished)
308
+ const safeKind = tooLong('kind', kind || '其它', LIMITS.kind)
309
+ const feelings = (Array.isArray(feeling) ? feeling : [feeling]).map((f) => String(f || '').trim()).filter(Boolean)
310
+ if (feelings.length > LIMITS.feelings) throw new Error(`feeling 最多 ${LIMITS.feelings} 个,现在是 ${feelings.length} 个。`)
311
+ const refIds = resolveRefs(dir, refs)
312
+
313
+ fs.mkdirSync(dir, { recursive: true })
314
+ const now = new Date()
315
+ const id = 'exp_' + now.getTime().toString(36) + Math.random().toString(36).slice(2, 6)
316
+ const row = {
317
+ id,
318
+ at: now.toISOString(),
319
+ day: now.toLocaleDateString('sv-SE'),
320
+ author: 'self',
321
+ source,
322
+ kind: safeKind,
323
+ weight: WEIGHTS.has(weight) ? weight : 'normal',
324
+ then: {
325
+ text: safeText,
326
+ scene: safeScene,
327
+ feeling: feelings,
328
+ thought: safeThought,
329
+ unfinished: safeUnfinished,
330
+ quote: quote && quote.text ? { text: tooLong('quote', quote.text, 500), source: tooLong('quote.source', quote.source || '', 120) } : null,
331
+ state: state && typeof state === 'object' ? { at: now.toISOString(), ...state } : { at: now.toISOString() }
332
+ },
333
+ later: [],
334
+ status: 'kept'
335
+ }
336
+ if (refIds.length) row.then.refs = refIds
337
+ const fd = fs.openSync(path.join(dir, FILE), 'a+')
338
+ try {
339
+ const size = fs.fstatSync(fd).size
340
+ const lastByte = Buffer.alloc(1)
341
+ if (size) fs.readSync(fd, lastByte, 0, 1, size - 1)
342
+ const separator = size && lastByte[0] !== 10 ? '\n' : ''
343
+ fs.writeFileSync(fd, separator + JSON.stringify(row) + '\n', 'utf8')
344
+ } finally {
345
+ fs.closeSync(fd)
346
+ }
347
+ return row
348
+ }
349
+
350
+ // 改主意 / 回头想:只追加一条 later 事件,不重写经历文件
351
+ // 先确认这条经历真的在:id 抄错时明说找不到,不留一条谁也看不见的后记
352
+ // feeling:她现在再想起这件事的感觉。当时的感觉留在 then.feeling 里不动;系统从不替她"淡化"
353
+ export function reviseExperience(dir, { id, thought, reason = '', feeling = [] }) {
354
+ if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
355
+ if (!String(thought || '').trim()) return { ok: false, error: 'thought 不能是空的。' }
356
+ try {
357
+ const safeThought = tooLong('thought', thought, LIMITS.laterThought)
358
+ const safeReason = tooLong('reason', reason, LIMITS.laterReason)
359
+ const feelings = feelingList(feeling, { name: 'feeling', perWord: true })
360
+ const target = resolveId(dir, String(id))
361
+ if (target.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id 来改。' }
362
+ if (!target.id) return { ok: false, error: '找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。' }
363
+ const row = laterEvents.append(dir, { id: target.id, thought: safeThought, reason: safeReason, feeling: feelings })
364
+ return { ok: true, id: row.id, at: row.at, ...(feelings.length ? { feeling: feelings } : {}) }
365
+ } catch (e) {
366
+ return { ok: false, error: String(e && e.message ? e.message : e) }
367
+ }
368
+ }
369
+
370
+ // 「这件没弄完的事」后来怎么样了:done / shelved / reopen
371
+ // 只追加一条状态事件;不改 then.unfinished,也不写成后记
372
+ // 重复同一个选择不写第二条;没关过的事 reopen 是空操作
373
+ export function setUnfinishedState(dir, { id, choice, note = '' } = {}) {
374
+ if (!String(id || '').trim()) return { ok: false, error: '需要 id' }
375
+ if (!unfinishedEvents.CHOICES.has(choice)) return { ok: false, error: 'state 只能是 done / shelved / reopen' }
376
+ try {
377
+ const target = resolveId(dir, String(id))
378
+ if (target.ambiguous) return { ok: false, error: '这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id。' }
379
+ if (!target.id) return { ok: false, error: '找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。' }
380
+ const row = rowsById(dir, target.id)
381
+ if (!row || !row.then || !row.then.unfinished) return { ok: false, error: '这条经历没有「还没弄完」的内容,不需要结案。' }
382
+
383
+ // 重读、判断、追加都在同一把锁里:两个进程同时提交同一选择,只有一个会写
384
+ const decided = unfinishedEvents.decide(dir, { id: target.id, choice, note: tooLong('note', note, 200) })
385
+ if (decided.noop) return { ok: true, id: target.id, at: decided.row ? decided.row.at : '', choice, noop: true }
386
+ return { ok: true, id: target.id, at: decided.row.at, choice, noop: false }
387
+ } catch (e) {
388
+ return { ok: false, error: String(e && e.message ? e.message : e) }
389
+ }
390
+ }
391
+
392
+ // 单条:loadAll 会合并事件,这里绕开全量合并,只给存在性/未完判断用
393
+ function rowsById(dir, id) {
394
+ const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
395
+ return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
396
+ }
397
+
398
+ // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
399
+ // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
400
+ export function markRecalled(dir, id) {
401
+ if (!String(id || '').trim()) return false
402
+ try { recallEvents.append(dir, { id: String(id) }) } catch { return false }
403
+ return true
404
+ }
405
+
406
+ // asOf:看那天的这一条(那之后的后记、选择、想起都不算);那天还没写下就返回 null
407
+ export function currentView(dir, id, { asOf = null } = {}) {
408
+ const rows = loadAll(dir, { asOf })
409
+ return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
410
+ }
411
+
412
+ // 相关度 × 重要度:重要的先被想起
413
+ // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛;门槛口径见 query-match.js
414
+ // mode='strict'(默认):长查询要求 ≥60% 命中,宁可不召回也不硬凑
415
+ // mode='loose':只要求至少一个实词命中,适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
416
+ // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
417
+ // asOf:在那天的自己里找(只读);翻旧日子不算"想起",所以不能和 mark 一起用
418
+ // 她封存了的经历不会被召回;includeSealed=true 只给"她自己要翻"这种明确场景用
419
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict', asOf = null, includeSealed = false } = {}) {
420
+ if (mark && asOf !== null && asOf !== undefined && asOf !== '') throw new Error('翻回旧日子时不记「想起」:mark 和 asOf 不能一起用。')
421
+ const rows = loadAll(dir, { asOf }).filter((r) => includeSealed || !r.sealed)
422
+ const q = String(query || '')
423
+ const parsed = queryTerms(q)
424
+ const { terms } = parsed
425
+ const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
426
+
427
+ const measure = (r) => {
428
+ const fields = []
429
+ const matched = new Set()
430
+ const take = (hits, label) => {
431
+ if (!hits.size) return
432
+ for (const g of hits) matched.add(g)
433
+ if (!fields.includes(label)) fields.push(label)
434
+ }
435
+ // 最初写下的、原文锚、后来才明白的:都参与匹配;后记逐条看,记下是哪几条让它被想起
436
+ take(matchedTerms(terms, r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' ')), 'then')
437
+ if (r.then.quote) take(matchedTerms(terms, (r.then.quote.text || '') + ' ' + (r.then.quote.source || '')), 'quote')
438
+ const matchedLater = []
439
+ const laterText = (l) => String(l.thought || '') + ' ' + (Array.isArray(l.feeling) ? l.feeling.join(' ') : '')
440
+ for (const l of r.later || []) {
441
+ const hits = matchedTerms(terms, laterText(l))
442
+ if (hits.size) matchedLater.push(l)
443
+ take(hits, 'later')
444
+ }
445
+
446
+ const all = normalizeText([
447
+ r.then.text, r.then.thought, (r.then.feeling || []).join(' '),
448
+ r.then.quote ? r.then.quote.text : '', r.then.quote ? r.then.quote.source : '',
449
+ (r.later || []).map(laterText).join(' ')
450
+ ].join(' '))
451
+ // 记录自身的规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
452
+ const size = Math.max(1, all.length - 1)
453
+ return { n: matched.size, size, matchedIn: fields, matchedLater }
454
+ }
455
+ const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
456
+ const picked = rows.map((r) => {
457
+ const { n, size, matchedIn, matchedLater } = measure(r)
458
+ return { r: { ...r, matchedIn, matchedLater }, n, s: (n / Math.sqrt(size)) * weightOf(r) }
459
+ })
460
+ .filter((x) => (q ? x.n >= required : true))
461
+ .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
462
+ .slice(0, limit).map((x) => x.r)
463
+
464
+ if (!mark || !picked.length) return picked
465
+
466
+ // 记完就地 +1,不回读全量;下一次读取自然会对上
467
+ const at = new Date().toISOString()
468
+ for (const r of picked) {
469
+ try { recallEvents.append(dir, { id: r.id, query: q }) } catch { /* 坏文件时不阻断召回 */ }
470
+ }
471
+ return picked.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
472
+ }
473
+
474
+ const laterDay = (l) => l.day || String(l.at || '').slice(0, 10)
475
+ const sameLater = (a, b) => a === b || (a.at === b.at && a.thought === b.thought)
476
+
477
+ const refLine = (x) => x.missing ? '(' + x.id + ',找不到了)' : x.sealed ? '(一件你封存了的事)' : x.day + '「' + x.text + '」'
478
+
479
+ // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
480
+ // 后记:这次是被哪条后记想起的,就把那条原样给她;再给最近的一条。各带各的日子,不截断
481
+ // 翻回那天(entry.viewAsOf)时,第二段是【那时】:只有那天之前的后记和选择
482
+ export function renderTwoPart(entry, { now = new Date() } = {}) {
483
+ if (!entry) return ''
484
+ const t = entry.then
485
+ const when = new Date(entry.at || entry.day)
486
+ const hh = Number.isNaN(when.getTime()) ? '' : when.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
487
+ const lines = []
488
+ lines.push('【当时】')
489
+ lines.push('- 时间:' + (entry.day || '') + (hh ? ' ' + hh : ''))
490
+ if (t.scene) lines.push('- 场景:' + t.scene)
491
+ if (t.quote && t.quote.text) lines.push('- 我读到的原文:' + t.quote.text + (t.quote.source ? '(' + t.quote.source + ')' : ''))
492
+ lines.push('- 我写下的话:' + t.text)
493
+ if (Array.isArray(entry.refsInfo) && entry.refsInfo.length) lines.push('- 是从这几件事想到的:' + entry.refsInfo.map(refLine).join(';'))
494
+ if ((t.feeling || []).length) lines.push('- 当时的感觉:' + t.feeling.join('、'))
495
+ if (t.thought) lines.push('- 当时的想法:' + t.thought)
496
+ if (t.unfinished) lines.push('- 还没完的:' + t.unfinished)
497
+ if (t.state && t.state.mood) lines.push('- 记录里的情绪:' + t.state.mood)
498
+ if (entry.legacy && !t.quote) lines.push('- (这条只留下感想,当时的原文没记)')
499
+ // 截在一天的最后一刻就只写日期;截在一天当中就写到分钟,免得让人以为整天都算进去了
500
+ let asOfDay = ''
501
+ if (entry.viewAsOf) {
502
+ const d = new Date(entry.viewAsOf)
503
+ const endOfDay = d.getHours() === 23 && d.getMinutes() === 59 && d.getSeconds() === 59 && d.getMilliseconds() === 999
504
+ asOfDay = dayOf(d.getTime()) + (endOfDay ? '' : ' ' + d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }))
505
+ }
506
+ if (asOfDay) {
507
+ lines.push('', '【那时(截至 ' + asOfDay + ')】')
508
+ lines.push('- 这是截至 ' + asOfDay + ' 的样子;那之后写下的后记和选择不在这里')
509
+ } else {
510
+ lines.push('', '【现在】')
511
+ lines.push('- 现在时间:' + now.toLocaleString('zh-CN', { hour12: false }))
512
+ }
513
+ if (entry.sealed) lines.push('- 这件事你封存了(' + entry.sealed.day + '):不会再被主动想起;它还在,想解封随时可以')
514
+ lines.push('- 这条被你想起过 ' + Number(entry.recalls || 0) + ' 次' + (entry.lastRecalledAt ? ',上次是 ' + String(entry.lastRecalledAt).slice(0, 10) : ''))
515
+ const later = Array.isArray(entry.later) ? entry.later : []
516
+ if (later.length) {
517
+ const last = later[later.length - 1]
518
+ const hits = (entry.matchedLater || []).filter((l) => !sameLater(l, last))
519
+ for (const l of hits) lines.push('- 这次想起它,是因为后来写过:' + String(l.thought || '') + '(' + laterDay(l) + ')')
520
+ lines.push((hits.length ? '- 最近一次回头想:' : '- 后来你想过:') + String(last.thought || '') + '(' + laterDay(last) + ')')
521
+ const shown = hits.length + 1
522
+ if (later.length > shown) lines.push('- (后来一共回头想过 ' + later.length + ' 次,这里没列出的 ' + (later.length - shown) + ' 次可以用 read 看)')
523
+ // 后来再想起时的感觉:取最近一条写了感觉的后记;她没写,就不替她说
524
+ const felt = [...later].reverse().find((l) => Array.isArray(l.feeling) && l.feeling.length)
525
+ if (felt) lines.push('- 后来再想起的感觉:' + felt.feeling.join('、') + '(' + laterDay(felt) + ')')
526
+ } else {
527
+ lines.push('- 还没有文字后记')
528
+ }
529
+ if (Array.isArray(entry.citedBy) && entry.citedBy.length) {
530
+ const shownRefs = entry.citedBy.slice(-3)
531
+ lines.push('- 后来有 ' + entry.citedBy.length + ' 条回想提到它:' + shownRefs.map(refLine).join(';') + (entry.citedBy.length > shownRefs.length ? ';……' : ''))
532
+ }
533
+ // 事后联想:另一头封存了的,连理由也不给(理由本身也会把那件事带回来)
534
+ if (Array.isArray(entry.links) && entry.links.length) {
535
+ lines.push('- 你后来把它和这些事连在一起:' + entry.links.map((l) => l.sealed ? refLine(l) : refLine(l) + '——' + l.reason + '(' + l.linkDay + ')').join(';'))
536
+ }
537
+ if (Array.isArray(entry.chapters) && entry.chapters.length) {
538
+ lines.push('- 你把那段日子叫做' + entry.chapters.map((c) => '「' + c.name + '」').join('、'))
539
+ }
540
+ const st = entry.unfinishedState
541
+ if (st && t.unfinished) {
542
+ const when2 = st.day || String(st.at || '').slice(0, 10)
543
+ const history = st.history || []
544
+ // 只看最近一次决定之前的那一次,不用 includes 猜
545
+ const prev = history.length >= 2 ? history[history.length - 2] : ''
546
+ let phrase = ''
547
+ if (st.choice === 'done') phrase = prev === 'shelved' ? '放下过,后来想通了' : '后来想通了'
548
+ else if (st.choice === 'shelved') phrase = prev === 'done' ? '想通过一次,后来又决定先放下' : '先放下了,还没想通'
549
+ else if (st.choice === 'reopen') phrase = prev === 'done' ? '想通过一次,后来又决定接着想' : '放下过,后来又决定接着想'
550
+ if (phrase) lines.push('- 当时没弄完的「' + t.unfinished + '」:' + phrase + '(' + when2 + ')')
551
+ }
552
+ lines.push('', '以上是那天留下的全部;没留下的,我不记得。')
553
+ return lines.join('\n')
554
+ }
555
+
556
+ export const internals = { WEIGHTS, FILE }
557
+ // 兼容旧调用:只要一句摘要的地方仍可用
558
+ export function recallForContext(dir, query, { max = 1 } = {}) {
559
+ 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 }))
560
+ }