whale-memory-core 0.14.0 → 0.18.2

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.
Files changed (48) hide show
  1. package/README.md +14 -0
  2. package/bin/whale-memory-mcp.mjs +276 -0
  3. package/demo.mjs +44 -33
  4. package/index.d.ts +16 -13
  5. package/index.js +18 -15
  6. package/lib/archive.d.ts +22 -0
  7. package/lib/archive.js +171 -0
  8. package/lib/as-of.d.ts +5 -5
  9. package/lib/as-of.js +32 -32
  10. package/lib/book.d.ts +4 -4
  11. package/lib/book.js +75 -75
  12. package/lib/chapter-events.d.ts +39 -39
  13. package/lib/chapter-events.js +89 -89
  14. package/lib/detail-recall.d.ts +15 -0
  15. package/lib/detail-recall.js +174 -0
  16. package/lib/event-log.d.ts +10 -10
  17. package/lib/event-log.js +61 -61
  18. package/lib/evidence-from-experience.d.ts +8 -8
  19. package/lib/evidence-from-experience.js +62 -62
  20. package/lib/evidence-policy.js +2 -2
  21. package/lib/fact-timeline-contract.d.ts +73 -0
  22. package/lib/fact-timeline-contract.js +226 -0
  23. package/lib/fact-timeline-query.d.ts +29 -0
  24. package/lib/fact-timeline-query.js +97 -0
  25. package/lib/file-lock.js +1 -1
  26. package/lib/later-events.d.ts +21 -21
  27. package/lib/later-events.js +80 -80
  28. package/lib/link-events.d.ts +15 -15
  29. package/lib/link-events.js +33 -33
  30. package/lib/query-match.js +55 -0
  31. package/lib/recall-events.d.ts +24 -24
  32. package/lib/recall-events.js +97 -97
  33. package/lib/recap.d.ts +23 -23
  34. package/lib/recap.js +79 -79
  35. package/lib/seal-events.d.ts +25 -25
  36. package/lib/seal-events.js +82 -82
  37. package/lib/self-experience.d.ts +180 -175
  38. package/lib/self-experience.js +624 -560
  39. package/lib/self-memory.js +70 -68
  40. package/lib/self-prompt.js +8 -4
  41. package/lib/self-settings.js +2 -2
  42. package/lib/unfinished-events.d.ts +26 -26
  43. package/lib/unfinished-events.js +105 -105
  44. package/lib/unsaid.d.ts +28 -0
  45. package/lib/unsaid.js +105 -0
  46. package/lib/waking.d.ts +1 -1
  47. package/lib/waking.js +99 -92
  48. package/package.json +127 -105
@@ -1,560 +1,624 @@
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
- }
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, contentUnits, coverage, MIN_COVER } 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('The experiences file contains corrupted records; back it up and repair it before making changes.(经历文件含损坏记录,请备份并修复后再修改。)')
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} item "${f.slice(0, 10)}…" is too long (${f.length}/${LIMITS.feelingWord} chars); write a feeling as a word, not a sentence.(${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} allows at most ${LIMITS.feelings} items; got ${out.length}.(${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} is too long (${n}/${max} chars); shorten it or split it into two entries.(${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
+ // 那时还没封存的,标成 afterAsOf(后来才封存),各处过滤照常生效;点名读仍然给,并写明是后来封存的
148
+ let sealedNowMap = sealedMap
149
+ if (until !== null) { try { sealedNowMap = sealEvents.sealedByExp(dir) } catch { sealedNowMap = new Map() } }
150
+
151
+ const viewed = rows.map((r) => {
152
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
153
+ const extra = keys.flatMap((k) => laterMap.get(k) || [])
154
+ const merged = [...(r.later || []).filter((l) => before(l, until)), ...extra]
155
+ .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
156
+ const next = { ...r, later: merged }
157
+ if (until !== null) {
158
+ next.viewAsOf = new Date(until).toISOString()
159
+ // 旧格式行内的 recalls 没有时间,放不到那天的时间线上
160
+ delete next.recalls
161
+ delete next.lastRecalledAt
162
+ }
163
+ let state = null
164
+ for (const k of keys) {
165
+ const st = unfinishedMap.get(k)
166
+ if (st) state = st
167
+ }
168
+ if (state && next.then && next.then.unfinished) next.unfinishedState = state
169
+ for (const k of keys) {
170
+ const s = sealedMap.get(k)
171
+ if (s) next.sealed = s
172
+ }
173
+ if (!next.sealed && until !== null) {
174
+ for (const k of keys) {
175
+ const s = sealedNowMap.get(k)
176
+ if (s) next.sealed = { ...s, afterAsOf: true }
177
+ }
178
+ }
179
+ let count = 0
180
+ let lastAt = ''
181
+ for (const k of keys) {
182
+ const c = counts.get(k)
183
+ if (!c) continue
184
+ count += c.count
185
+ if (c.lastAt > lastAt) lastAt = c.lastAt
186
+ }
187
+ if (count) {
188
+ next.recalls = count
189
+ next.lastRecalledAt = lastAt || (until === null ? r.lastRecalledAt : '') || ''
190
+ }
191
+ return next
192
+ })
193
+
194
+ // 出处(这条是从哪几件事想到的)和反向引用(后来有哪些回想提到它):都从 then.refs 派生
195
+ // 封存了的经历不露摘要:别的回想里只说"一件你封存了的事",不借着引用把它又提起来
196
+ const pointer = (r) => r.sealed ? { id: r.id, day: r.day, sealed: true } : brief(r)
197
+ const byId = new Map()
198
+ for (const r of viewed) { byId.set(r.id, r); if (r.formerId) byId.set(r.formerId, r) }
199
+ for (const r of viewed) {
200
+ const refs = (r.then && Array.isArray(r.then.refs)) ? r.then.refs : []
201
+ if (!refs.length) continue
202
+ r.refsInfo = refs.map((id) => { const hit = byId.get(id); return hit ? pointer(hit) : { id, missing: true } })
203
+ for (const id of refs) {
204
+ const target = byId.get(id)
205
+ if (!target || target === r) continue
206
+ target.citedBy = [...(target.citedBy || []), pointer(r)]
207
+ }
208
+ }
209
+
210
+ // 事后联想(两头都看得见)与人生章节(按 day 落进她起过名字的那段日子)
211
+ let linkMap = new Map()
212
+ try { linkMap = linkEvents.linksByExp(dir, { until }) } catch { }
213
+ let chapterList = []
214
+ try { chapterList = chapterEvents.chapters(dir, { until }) } catch { }
215
+ for (const r of viewed) {
216
+ const keys = r.formerId ? [r.id, r.formerId] : [r.id]
217
+ const links = keys.flatMap((k) => linkMap.get(k) || [])
218
+ .map((l) => {
219
+ const other = byId.get(l.other)
220
+ if (!other || other === r) return null
221
+ // 另一头封存了:只给 id 和日子,连理由也不露,免得借联想又把它提起来
222
+ if (other.sealed) return { id: other.id, day: other.day, sealed: true, linkDay: l.day }
223
+ return { ...pointer(other), reason: l.reason, linkDay: l.day }
224
+ })
225
+ .filter(Boolean)
226
+ if (links.length) r.links = links
227
+ const ch = chapterEvents.chaptersOn(chapterList, r.day || '')
228
+ if (ch.length) r.chapters = ch.map((c) => ({ id: c.id, name: c.name }))
229
+ }
230
+ return viewed
231
+ }
232
+
233
+ // 事后联想:她发现两件事有关,亲手连起来,并说清为什么。两条都必须存在;同一对只连一次
234
+ export function linkExperiences(dir, { from, to, reason = '' } = {}) {
235
+ if (!String(from || '').trim() || !String(to || '').trim()) return { ok: false, error: 'Need the ids of two experiences: from and to(需要 from 与 to 两条经历的 id)' }
236
+ if (!String(reason || '').trim()) return { ok: false, error: 'Say why you are linking them (reason). If you cannot say why, do not link them yet.(说一句为什么把它们连起来(reason)。说不出来就先别连。)' }
237
+ try {
238
+ const why = tooLong('reason', String(reason).trim(), LIMITS.laterReason)
239
+ const a = resolveId(dir, String(from))
240
+ const b = resolveId(dir, String(to))
241
+ for (const [x, t] of [[from, a], [to, b]]) {
242
+ if (t.ambiguous) return { ok: false, error: 'This legacy id is shared by several old experiences: ' + x + '. Use the current id listed by `read`.(这个旧 id 有好几条旧经历共用:' + x + '。用 read 里列出的当前 id。)' }
243
+ if (!t.id) return { ok: false, error: 'Experience not found: ' + x + '. Run `read` to check the id.(找不到这条经历:' + x + '。先用 read 看一下 id。)' }
244
+ }
245
+ const res = linkEvents.link(dir, { from: a.id, to: b.id, reason: why })
246
+ return { ok: true, from: a.id, to: b.id, noop: res.noop, ...(res.row ? { at: res.row.at } : {}) }
247
+ } catch (e) {
248
+ return { ok: false, error: String(e && e.message ? e.message : e) }
249
+ }
250
+ }
251
+
252
+ // 封存 / 解封:她不想再被这件事主动提醒了,或者又愿意了
253
+ // 不删除任何东西;重复同一个动作不写第二条
254
+ export function setSealed(dir, { id, sealed = true, note = '' } = {}) {
255
+ if (!String(id || '').trim()) return { ok: false, error: 'Missing id(需要 id)' }
256
+ try {
257
+ const target = resolveId(dir, String(id))
258
+ if (target.ambiguous) return { ok: false, error: 'This legacy id is shared by several old experiences: ' + id + '. Use the current id listed by `read`.(这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id。)' }
259
+ if (!target.id) return { ok: false, error: 'Experience not found: ' + id + '. Run `read` to check the id.(找不到这条经历:' + id + '。先用 read 看一下 id。)' }
260
+ const action = sealed ? 'seal' : 'unseal'
261
+ const decided = sealEvents.decide(dir, { id: target.id, action, note: tooLong('note', note, 200) })
262
+ return { ok: true, id: target.id, sealed: Boolean(sealed), at: decided.row ? decided.row.at : '', noop: decided.noop }
263
+ } catch (e) {
264
+ return { ok: false, error: String(e && e.message ? e.message : e) }
265
+ }
266
+ }
267
+
268
+ // 挂在 0.10.0 之前的旧 id 上、但这个 id 有几条旧记录共用:事件原样保留,只报告,不替她挑
269
+ export function pendingLegacyEvents(dir) {
270
+ const { owners, explicit } = identify(dir)
271
+ let counts = new Map()
272
+ let laterMap = new Map()
273
+ try { counts = recallEvents.countByExp(dir) } catch { }
274
+ try { laterMap = laterEvents.groupByExp(dir) } catch { }
275
+ const out = []
276
+ for (const [id, candidates] of owners) {
277
+ if (candidates.length < 2 || explicit.has(id)) continue
278
+ const later = (laterMap.get(id) || []).length
279
+ const recalls = counts.get(id) ? counts.get(id).count : 0
280
+ if (later || recalls) out.push({ id, candidates, later, recalls })
281
+ }
282
+ return out
283
+ }
284
+
285
+ // 把调用方给的 id 落到一条现存经历上:认当前 id,也认唯一对应的旧 id
286
+ // 旧 id 被几条旧经历共用时不落到任何一条上,返回 ambiguous 让调用方说清楚
287
+ function resolveId(dir, id) {
288
+ const { rows, owners } = identify(dir)
289
+ const hit = rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id)
290
+ if (hit) return { id: hit.id }
291
+ return { id: '', ambiguous: (owners.get(id) || []).length > 1 }
292
+ }
293
+
294
+ // 出处:回想只能引用已经写下的经历。找不到、或旧 id 有歧义,就整条不写,并说清是哪一个
295
+ function resolveRefs(dir, refs) {
296
+ const list = (Array.isArray(refs) ? refs : String(refs || '').split(/[,,\s]+/)).map((s) => String(s || '').trim()).filter(Boolean)
297
+ if (!list.length) return []
298
+ if (list.length > LIMITS.refs) throw new Error(`refs allows at most ${LIMITS.refs} entries; got ${list.length}. Pick the most important ones.(出处最多 ${LIMITS.refs} 条,现在是 ${list.length} 条。挑最主要的几件写。)`)
299
+ const { rows, owners } = identify(dir)
300
+ const out = []
301
+ for (const x of list) {
302
+ const hit = rows.find((r) => r.id === x) || rows.find((r) => r.formerId === x)
303
+ if (!hit && (owners.get(x) || []).length > 1) throw new Error('A legacy id in refs is shared by several experiences: ' + x + '. Use the current id listed by `read`.(出处里的旧 id 有几条经历共用:' + x + '。用 read 里列出的当前 id。)')
304
+ if (!hit) throw new Error('refs points to an experience that does not exist: ' + x + '. A look-back can only cite experiences already written.(出处里有找不到的经历:' + x + '。回想只能引用已经写下的经历。)')
305
+ if (!out.includes(hit.id)) out.push(hit.id)
306
+ }
307
+ return out
308
+ }
309
+
310
+ // 写下时的"当时":她写的 + 系统能自动带的状态(情绪/时间/场合)
311
+ // refs:这条是从哪几件事想到的(回想、归纳时用)。写入时就校验,引用不存在的经历直接拒绝
312
+ export function addExperience(dir, { text, scene = '', feeling = [], thought = '', unfinished = '', quote = null, weight = 'normal', kind = '其它', state = null, source = 'own-time', refs = [] }) {
313
+ if (!String(text || '').trim()) throw new Error('text cannot be empty.(text 不能是空的。)')
314
+ const safeText = tooLong('text', text, LIMITS.text)
315
+ const safeScene = tooLong('scene', scene, LIMITS.scene)
316
+ const safeThought = tooLong('thought', thought, LIMITS.thought)
317
+ const safeUnfinished = tooLong('unfinished', unfinished, LIMITS.unfinished)
318
+ const safeKind = tooLong('kind', kind || '其它', LIMITS.kind)
319
+ // 和 revise 同一套:逗号分隔的字符串或数组都收、去重;写入时不限单个词的长度(旧宿主可能写过短句)
320
+ const feelings = feelingList(feeling, { name: 'feeling' })
321
+ const refIds = resolveRefs(dir, refs)
322
+
323
+ fs.mkdirSync(dir, { recursive: true })
324
+ const now = new Date()
325
+ const id = 'exp_' + now.getTime().toString(36) + Math.random().toString(36).slice(2, 6)
326
+ const row = {
327
+ id,
328
+ at: now.toISOString(),
329
+ day: now.toLocaleDateString('sv-SE'),
330
+ author: 'self',
331
+ source,
332
+ kind: safeKind,
333
+ weight: WEIGHTS.has(weight) ? weight : 'normal',
334
+ then: {
335
+ text: safeText,
336
+ scene: safeScene,
337
+ feeling: feelings,
338
+ thought: safeThought,
339
+ unfinished: safeUnfinished,
340
+ quote: quote && quote.text ? { text: tooLong('quote', quote.text, 500), source: tooLong('quote.source', quote.source || '', 120) } : null,
341
+ state: state && typeof state === 'object' ? { at: now.toISOString(), ...state } : { at: now.toISOString() }
342
+ },
343
+ later: [],
344
+ status: 'kept'
345
+ }
346
+ if (refIds.length) row.then.refs = refIds
347
+ const fd = fs.openSync(path.join(dir, FILE), 'a+')
348
+ try {
349
+ const size = fs.fstatSync(fd).size
350
+ const lastByte = Buffer.alloc(1)
351
+ if (size) fs.readSync(fd, lastByte, 0, 1, size - 1)
352
+ const separator = size && lastByte[0] !== 10 ? '\n' : ''
353
+ fs.writeFileSync(fd, separator + JSON.stringify(row) + '\n', 'utf8')
354
+ } finally {
355
+ fs.closeSync(fd)
356
+ }
357
+ return row
358
+ }
359
+
360
+ // 改主意 / 回头想:只追加一条 later 事件,不重写经历文件
361
+ // 先确认这条经历真的在:id 抄错时明说找不到,不留一条谁也看不见的后记
362
+ // feeling:她现在再想起这件事的感觉。当时的感觉留在 then.feeling 里不动;系统从不替她"淡化"
363
+ export function reviseExperience(dir, { id, thought, reason = '', feeling = [] }) {
364
+ if (!String(id || '').trim()) return { ok: false, error: 'Missing id(需要 id)' }
365
+ if (!String(thought || '').trim()) return { ok: false, error: 'thought cannot be empty.(thought 不能是空的。)' }
366
+ try {
367
+ const safeThought = tooLong('thought', thought, LIMITS.laterThought)
368
+ const safeReason = tooLong('reason', reason, LIMITS.laterReason)
369
+ const feelings = feelingList(feeling, { name: 'feeling', perWord: true })
370
+ const target = resolveId(dir, String(id))
371
+ if (target.ambiguous) return { ok: false, error: 'This legacy id is shared by several old experiences: ' + id + '. Use the current id listed by `read` to revise it.(这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id 来改。)' }
372
+ if (!target.id) return { ok: false, error: 'Experience not found: ' + id + '. Run `read` or `recall` to check the id.(找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。)' }
373
+ const row = laterEvents.append(dir, { id: target.id, thought: safeThought, reason: safeReason, feeling: feelings })
374
+ return { ok: true, id: row.id, at: row.at, ...(feelings.length ? { feeling: feelings } : {}) }
375
+ } catch (e) {
376
+ return { ok: false, error: String(e && e.message ? e.message : e) }
377
+ }
378
+ }
379
+
380
+ // 「这件没弄完的事」后来怎么样了:done / shelved / reopen
381
+ // 只追加一条状态事件;不改 then.unfinished,也不写成后记
382
+ // 重复同一个选择不写第二条;没关过的事 reopen 是空操作
383
+ export function setUnfinishedState(dir, { id, choice, note = '' } = {}) {
384
+ if (!String(id || '').trim()) return { ok: false, error: 'Missing id(需要 id)' }
385
+ if (!unfinishedEvents.CHOICES.has(choice)) return { ok: false, error: 'state must be done / shelved / reopen(state 只能是 done / shelved / reopen)' }
386
+ try {
387
+ const target = resolveId(dir, String(id))
388
+ if (target.ambiguous) return { ok: false, error: 'This legacy id is shared by several old experiences: ' + id + '. Use the current id listed by `read`.(这个旧 id 有好几条旧经历共用:' + id + '。用 read 里列出的当前 id。)' }
389
+ if (!target.id) return { ok: false, error: 'Experience not found: ' + id + '. Run `read` or `recall` to check the id.(找不到这条经历:' + id + '。先用 read 或 recall 看一下 id。)' }
390
+ const row = rowsById(dir, target.id)
391
+ if (!row || !row.then || !row.then.unfinished) return { ok: false, error: 'This experience has no "unfinished" part, so there is nothing to close.(这条经历没有「还没弄完」的内容,不需要结案。)' }
392
+
393
+ // 重读、判断、追加都在同一把锁里:两个进程同时提交同一选择,只有一个会写
394
+ const decided = unfinishedEvents.decide(dir, { id: target.id, choice, note: tooLong('note', note, 200) })
395
+ if (decided.noop) return { ok: true, id: target.id, at: decided.row ? decided.row.at : '', choice, noop: true }
396
+ return { ok: true, id: target.id, at: decided.row.at, choice, noop: false }
397
+ } catch (e) {
398
+ return { ok: false, error: String(e && e.message ? e.message : e) }
399
+ }
400
+ }
401
+
402
+ // 单条:loadAll 会合并事件,这里绕开全量合并,只给存在性/未完判断用
403
+ function rowsById(dir, id) {
404
+ const rows = readAll(dir).map(normalize).filter((r) => r && r.then && r.then.text)
405
+ return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
406
+ }
407
+
408
+ // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
409
+ // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
410
+ export function markRecalled(dir, id) {
411
+ if (!String(id || '').trim()) return false
412
+ try { recallEvents.append(dir, { id: String(id) }) } catch { return false }
413
+ return true
414
+ }
415
+
416
+ // asOf:看那天的这一条(那之后的后记、选择、想起都不算);那天还没写下就返回 null
417
+ export function currentView(dir, id, { asOf = null } = {}) {
418
+ const rows = loadAll(dir, { asOf })
419
+ return rows.find((r) => r.id === id) || rows.find((r) => r.formerId === id) || null
420
+ }
421
+
422
+ // 相关度 × 重要度:重要的先被想起
423
+ // 阈值比较的是「原始重叠数」,重要度只影响排序,不影响过线门槛;门槛口径见 query-match.js
424
+ // mode='strict'(默认):长查询要求 ≥60% 命中,宁可不召回也不硬凑
425
+ // mode='loose':只要求至少一个实词命中,适合"想起来就该出现在眼前"的日常召回,宿主自行承担误召
426
+ // mark=false(默认):只读;mark=true 追加一条 recall 事件(不重写经历文件)
427
+ // asOf:在那天的自己里找(只读);翻旧日子不算"想起",所以不能和 mark 一起用
428
+ // 她封存了的经历不会被召回;includeSealed=true 只给"她自己要翻"这种明确场景用
429
+ // gate:strict 下用哪套门槛。'cover'(默认,0.17 起)= 至少对上一个词 + 意思至少 70% 被接住;
430
+ // 'legacy' = 0.16 及以前的口径(长查询要 60% 的两字词对上),排序也照旧。宿主想保持旧行为时用
431
+ export function recall(dir, query, { limit = 3, minOverlap = 1, mark = false, minRatio = 0.6, mode = 'strict', asOf = null, includeSealed = false, gate = 'cover' } = {}) {
432
+ if (mark && asOf !== null && asOf !== undefined && asOf !== '') throw new Error('Looking back at an earlier day does not record a recall: mark and asOf cannot be used together.(翻回旧日子时不记「想起」:mark 和 asOf 不能一起用。)')
433
+ const rows = loadAll(dir, { asOf }).filter((r) => includeSealed || !r.sealed)
434
+ const q = String(query || '')
435
+ const parsed = queryTerms(q)
436
+ const { terms } = parsed
437
+ const required = requiredOverlap(parsed, { mode, minOverlap, minRatio })
438
+ const units = contentUnits(q)
439
+
440
+ const measure = (r) => {
441
+ const fields = []
442
+ const matched = new Set()
443
+ const take = (hits, label) => {
444
+ if (!hits.size) return
445
+ for (const g of hits) matched.add(g)
446
+ if (!fields.includes(label)) fields.push(label)
447
+ }
448
+ // 最初写下的、原文锚、后来才明白的:都参与匹配;后记逐条看,记下是哪几条让它被想起
449
+ take(matchedTerms(terms, r.then.text + ' ' + r.then.thought + ' ' + (r.then.feeling || []).join(' ')), 'then')
450
+ if (r.then.quote) take(matchedTerms(terms, (r.then.quote.text || '') + ' ' + (r.then.quote.source || '')), 'quote')
451
+ const matchedLater = []
452
+ const laterText = (l) => String(l.thought || '') + ' ' + (Array.isArray(l.feeling) ? l.feeling.join(' ') : '')
453
+ for (const l of r.later || []) {
454
+ const hits = matchedTerms(terms, laterText(l))
455
+ if (hits.size) matchedLater.push(l)
456
+ take(hits, 'later')
457
+ }
458
+
459
+ const all = normalizeText([
460
+ r.then.text, r.then.thought, (r.then.feeling || []).join(' '),
461
+ r.then.quote ? r.then.quote.text : '', r.then.quote ? r.then.quote.source : '',
462
+ (r.later || []).map(laterText).join(' ')
463
+ ].join(' '))
464
+ // 记录自身的规模:长记录天然更容易碰巧命中,排序时按 √长度 归一化
465
+ const size = Math.max(1, all.length - 1)
466
+ return { n: matched.size, size, matchedIn: fields, matchedLater, cover: coverage(units, all) }
467
+ }
468
+ const weightOf = (r) => (r.weight === 'important' ? 3 : r.weight === 'minor' ? 0.5 : 1)
469
+ const picked = rows.map((r) => {
470
+ const { n, size, matchedIn, matchedLater, cover } = measure(r)
471
+ const legacy = gate === 'legacy'
472
+ return { r: { ...r, matchedIn, matchedLater }, n, cover, s: (n / Math.sqrt(size)) * weightOf(r) * (legacy ? 1 : 0.5 + cover) }
473
+ })
474
+ // strict(0.17 起):至少对上一个词,并且查询的意思至少 MIN_COVER 在这段记忆里找得到;loose:对上 minOverlap 个词
475
+ .filter((x) => (!q ? true : mode === 'loose' || gate === 'legacy' ? x.n >= required : x.n >= minOverlap && x.cover >= MIN_COVER))
476
+ .sort((a, b) => b.s - a.s || String(b.r.at).localeCompare(String(a.r.at)))
477
+ .slice(0, limit).map((x) => x.r)
478
+
479
+ if (!mark || !picked.length) return picked
480
+
481
+ // 记完就地 +1,不回读全量;下一次读取自然会对上
482
+ const at = new Date().toISOString()
483
+ for (const r of picked) {
484
+ try { recallEvents.append(dir, { id: r.id, query: q }) } catch { /* 坏文件时不阻断召回 */ }
485
+ }
486
+ return picked.map((r) => ({ ...r, recalls: Number(r.recalls || 0) + 1, lastRecalledAt: at }))
487
+ }
488
+
489
+ const laterDay = (l) => l.day || String(l.at || '').slice(0, 10)
490
+ const sameLater = (a, b) => a === b || (a.at === b.at && a.thought === b.thought)
491
+
492
+ // 两段式的文字:zh(默认,原样不变)/ en。宿主按自己的用户选;鲸鲸的插件不传 lang,照旧是中文
493
+ const TEXT = {
494
+ zh: {
495
+ missing: (id) => '(' + id + ',找不到了)', sealedRef: '(一件你封存了的事)', ref: (x) => x.day + '「' + x.text + '」',
496
+ then: '【当时】', time: '- 时间:', scene: '- 场景:', quote: '- 我读到的原文:', src: (s) => '(' + s + ')', text: '- 我写下的话:',
497
+ refs: '- 是从这几件事想到的:', sep: ';', feelSep: '、', feeling: '- 当时的感觉:', thought: '- 当时的想法:', unfinished: '- 还没完的:',
498
+ mood: '- 记录里的情绪:', legacy: '- (这条只留下感想,当时的原文没记)',
499
+ asOfHead: (d) => '【那时(截至 ' + d + ')】', asOfNote: (d) => '- 这是截至 ' + d + ' 的样子;那之后写下的后记和选择不在这里',
500
+ nowHead: '【现在】', nowTime: '- 现在时间:', locale: 'zh-CN',
501
+ sealed: (s) => '- 这件事你' + (s.afterAsOf ? '后来' : '') + '封存了(' + s.day + '):不会再被主动想起;它还在,想解封随时可以',
502
+ recalls: (n, last) => '- 这条被你想起过 ' + n + ' 次' + (last ? ',上次是 ' + last : ''),
503
+ hit: '- 这次想起它,是因为后来写过:', latest: '- 最近一次回头想:', laterOnly: '- 后来你想过:', day: (d) => '(' + d + ')',
504
+ more: (all, rest) => '- (后来一共回头想过 ' + all + ' 次,这里没列出的 ' + rest + ' 次可以用 read 看)',
505
+ felt: '- 后来再想起的感觉:', noLater: '- 还没有文字后记',
506
+ citedBy: (n, list, more) => '- 后来有 ' + n + ' 条回想提到它:' + list + (more ? ';……' : ''),
507
+ links: '- 你后来把它和这些事连在一起:', linkReason: (r, d) => '——' + r + '(' + d + ')',
508
+ chapters: (names) => '- 你把那段日子叫做' + names.map((c) => '「' + c + '」').join('、'),
509
+ done: (prev) => (prev === 'shelved' ? '放下过,后来想通了' : '后来想通了'),
510
+ shelved: (prev) => (prev === 'done' ? '想通过一次,后来又决定先放下' : '先放下了,还没想通'),
511
+ reopen: (prev) => (prev === 'done' ? '想通过一次,后来又决定接着想' : '放下过,后来又决定接着想'),
512
+ unfinishedState: (u, p, d) => '- 当时没弄完的「' + u + '」:' + p + '(' + d + ')',
513
+ end: '以上是那天留下的全部;没留下的,我不记得。'
514
+ },
515
+ en: {
516
+ missing: (id) => '(' + id + ', can no longer be found)', sealedRef: '(something you sealed)', ref: (x) => x.day + ' "' + x.text + '"',
517
+ then: '[Then]', time: '- When: ', scene: '- Scene: ', quote: '- What I read: ', src: (s) => ' (' + s + ')', text: '- What I wrote: ',
518
+ refs: '- What made me think of it: ', sep: '; ', feelSep: ', ', feeling: '- How I felt then: ', thought: '- What I thought then: ', unfinished: '- Left unfinished: ',
519
+ mood: '- Mood on record: ', legacy: '- (Only the reflection was kept; the original text was not recorded)',
520
+ asOfHead: (d) => '[As of ' + d + ']', asOfNote: (d) => '- This is how it looked as of ' + d + '; later notes and choices are not shown',
521
+ nowHead: '[Now]', nowTime: '- Current time: ', locale: 'en-CA',
522
+ sealed: (s) => '- You ' + (s.afterAsOf ? 'later ' : '') + 'sealed this (' + s.day + '): it will not be brought up again; it still exists and can be unsealed any time',
523
+ recalls: (n, last) => '- You have recalled this ' + n + ' time' + (n === 1 ? '' : 's') + (last ? ', last on ' + last : ''),
524
+ hit: '- Recalled this time because of a later note: ', latest: '- Most recent look back: ', laterOnly: '- Later you thought: ', day: (d) => ' (' + d + ')',
525
+ more: (all, rest) => '- (You looked back ' + all + ' times in all; the other ' + rest + ' are in `read`)',
526
+ felt: '- How it felt when recalled later: ', noLater: '- No later notes yet',
527
+ citedBy: (n, list, more) => '- Later, ' + n + ' look-back' + (n === 1 ? '' : 's') + ' mentioned it: ' + list + (more ? '; …' : ''),
528
+ links: '- Later you linked it with: ', linkReason: (r, d) => ' — ' + r + ' (' + d + ')',
529
+ chapters: (names) => '- You call that time ' + names.map((c) => '"' + c + '"').join(', '),
530
+ done: (prev) => (prev === 'shelved' ? 'set aside once, then resolved' : 'resolved later'),
531
+ shelved: (prev) => (prev === 'done' ? 'resolved once, then set aside again' : 'set aside, not resolved yet'),
532
+ reopen: (prev) => (prev === 'done' ? 'resolved once, then picked up again' : 'set aside once, then picked up again'),
533
+ unfinishedState: (u, p, d) => '- The unfinished "' + u + '": ' + p + ' (' + d + ')',
534
+ end: 'That is everything left from that day; what was not written down, I do not remember.'
535
+ }
536
+ }
537
+ const textOf = (lang) => TEXT[lang === 'en' ? 'en' : 'zh']
538
+ const refLineIn = (L) => (x) => x.missing ? L.missing(x.id) : x.sealed ? L.sealedRef : L.ref(x)
539
+ const refLine = refLineIn(TEXT.zh)
540
+
541
+ // 「当时 / 现在」两段式:模板拼,不调模型;没有的字段就如实说没有
542
+ // 后记:这次是被哪条后记想起的,就把那条原样给她;再给最近的一条。各带各的日子,不截断
543
+ // 翻回那天(entry.viewAsOf)时,第二段是【那时】:只有那天之前的后记和选择
544
+ // lang:'zh'(默认)或 'en'。只换标签,她写下的内容原样不动
545
+ export function renderTwoPart(entry, { now = new Date(), lang = 'zh' } = {}) {
546
+ if (!entry) return ''
547
+ const L = textOf(lang)
548
+ const ref = refLineIn(L)
549
+ const t = entry.then
550
+ const when = new Date(entry.at || entry.day)
551
+ const hh = Number.isNaN(when.getTime()) ? '' : when.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
552
+ const lines = []
553
+ lines.push(L.then)
554
+ lines.push(L.time + (entry.day || '') + (hh ? ' ' + hh : ''))
555
+ if (t.scene) lines.push(L.scene + t.scene)
556
+ if (t.quote && t.quote.text) lines.push(L.quote + t.quote.text + (t.quote.source ? L.src(t.quote.source) : ''))
557
+ lines.push(L.text + t.text)
558
+ if (Array.isArray(entry.refsInfo) && entry.refsInfo.length) lines.push(L.refs + entry.refsInfo.map(ref).join(L.sep))
559
+ if ((t.feeling || []).length) lines.push(L.feeling + t.feeling.join(L.feelSep))
560
+ if (t.thought) lines.push(L.thought + t.thought)
561
+ if (t.unfinished) lines.push(L.unfinished + t.unfinished)
562
+ if (t.state && t.state.mood) lines.push(L.mood + t.state.mood)
563
+ if (entry.legacy && !t.quote) lines.push(L.legacy)
564
+ // 截在一天的最后一刻就只写日期;截在一天当中就写到分钟,免得让人以为整天都算进去了
565
+ let asOfDay = ''
566
+ if (entry.viewAsOf) {
567
+ const d = new Date(entry.viewAsOf)
568
+ const endOfDay = d.getHours() === 23 && d.getMinutes() === 59 && d.getSeconds() === 59 && d.getMilliseconds() === 999
569
+ asOfDay = dayOf(d.getTime()) + (endOfDay ? '' : ' ' + d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }))
570
+ }
571
+ if (asOfDay) {
572
+ lines.push('', L.asOfHead(asOfDay))
573
+ lines.push(L.asOfNote(asOfDay))
574
+ } else {
575
+ lines.push('', L.nowHead)
576
+ lines.push(L.nowTime + now.toLocaleString(L.locale, { hour12: false }))
577
+ }
578
+ if (entry.sealed) lines.push(L.sealed(entry.sealed))
579
+ lines.push(L.recalls(Number(entry.recalls || 0), entry.lastRecalledAt ? String(entry.lastRecalledAt).slice(0, 10) : ''))
580
+ const later = Array.isArray(entry.later) ? entry.later : []
581
+ if (later.length) {
582
+ const last = later[later.length - 1]
583
+ const hits = (entry.matchedLater || []).filter((l) => !sameLater(l, last))
584
+ for (const l of hits) lines.push(L.hit + String(l.thought || '') + L.day(laterDay(l)))
585
+ lines.push((hits.length ? L.latest : L.laterOnly) + String(last.thought || '') + L.day(laterDay(last)))
586
+ const shown = hits.length + 1
587
+ if (later.length > shown) lines.push(L.more(later.length, later.length - shown))
588
+ // 后来再想起时的感觉:取最近一条写了感觉的后记;她没写,就不替她说
589
+ const felt = [...later].reverse().find((l) => Array.isArray(l.feeling) && l.feeling.length)
590
+ if (felt) lines.push(L.felt + felt.feeling.join(L.feelSep) + L.day(laterDay(felt)))
591
+ } else {
592
+ lines.push(L.noLater)
593
+ }
594
+ if (Array.isArray(entry.citedBy) && entry.citedBy.length) {
595
+ const shownRefs = entry.citedBy.slice(-3)
596
+ lines.push(L.citedBy(entry.citedBy.length, shownRefs.map(ref).join(L.sep), entry.citedBy.length > shownRefs.length))
597
+ }
598
+ // 事后联想:另一头封存了的,连理由也不给(理由本身也会把那件事带回来)
599
+ if (Array.isArray(entry.links) && entry.links.length) {
600
+ lines.push(L.links + entry.links.map((l) => l.sealed ? ref(l) : ref(l) + L.linkReason(l.reason, l.linkDay)).join(L.sep))
601
+ }
602
+ if (Array.isArray(entry.chapters) && entry.chapters.length) {
603
+ lines.push(L.chapters(entry.chapters.map((c) => c.name)))
604
+ }
605
+ const st = entry.unfinishedState
606
+ if (st && t.unfinished) {
607
+ const when2 = st.day || String(st.at || '').slice(0, 10)
608
+ const history = st.history || []
609
+ // 只看最近一次决定之前的那一次,不用 includes 猜
610
+ const prev = history.length >= 2 ? history[history.length - 2] : ''
611
+ const phrase = L[st.choice] ? L[st.choice](prev) : ''
612
+ if (phrase) lines.push(L.unfinishedState(t.unfinished, phrase, when2))
613
+ }
614
+ lines.push('', L.end)
615
+ return lines.join('\n')
616
+ }
617
+
618
+ export const internals = { WEIGHTS, FILE }
619
+ // 兼容旧调用:只要一句摘要的地方仍可用
620
+ // 宿主拿用户的原话直接来召回、再自动塞进提示词:用旧口径,升级不改变自动递回的行为
621
+ // (新口径对"垫话 + 话题"更友好,但对"长句里带一个错的前提"仍可能放进来,见 docs/eval.md)
622
+ export function recallForContext(dir, query, { max = 1, gate = 'legacy' } = {}) {
623
+ 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
+ }