whale-memory-core 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -6,4 +6,5 @@ export * as waking from './lib/waking.js'
6
6
  export * as selfPrompt from './lib/self-prompt.js'
7
7
  export * as selfSettings from './lib/self-settings.js'
8
8
  export * as evidencePolicy from './lib/evidence-policy.js'
9
- export * as evidenceFromExperience from './lib/evidence-from-experience.js'
9
+ export * as evidenceFromExperience from './lib/evidence-from-experience.js'
10
+ export * as unfinishedEvents from './lib/unfinished-events.js'
@@ -33,6 +33,16 @@ export interface Experience {
33
33
  recalls?: number
34
34
  lastRecalledAt?: string
35
35
  matchedIn?: Array<'then' | 'quote' | 'later'>
36
+ /** 没弄完的事后来怎么样了:done=想通,shelved=先放下,reopen=又接着想 */
37
+ unfinishedState?: {
38
+ id: string
39
+ at: string
40
+ day: string
41
+ choice: 'done' | 'shelved' | 'reopen'
42
+ note: string
43
+ /** 完整的选择历史,按追加顺序 */
44
+ history: Array<'done' | 'shelved' | 'reopen'>
45
+ }
36
46
  /** recall 返回:是哪几条后记让这条被想起 */
37
47
  matchedLater?: LaterEntry[]
38
48
  /** 0.10.0 之前的旧 id(只在唯一对应时出现);用它也能 revise / currentView */
@@ -90,6 +100,11 @@ export interface PendingLegacyEvents {
90
100
 
91
101
  export function pendingLegacyEvents(dir: string): PendingLegacyEvents[]
92
102
 
103
+ export function setUnfinishedState(
104
+ dir: string,
105
+ opts: { id: string; choice: 'done' | 'shelved' | 'reopen'; note?: string }
106
+ ): { ok: boolean; id?: string; at?: string; choice?: string; noop?: boolean; error?: string }
107
+
93
108
  export interface RecallContextItem {
94
109
  id: string
95
110
  day: string
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  import crypto from 'node:crypto'
5
5
  import * as recallEvents from './recall-events.js'
6
6
  import * as laterEvents from './later-events.js'
7
+ import * as unfinishedEvents from './unfinished-events.js'
7
8
  import { queryTerms, requiredOverlap, matchedTerms, normalizeText } from './query-match.js'
8
9
 
9
10
  const FILE = 'self-experience.jsonl'
@@ -109,12 +110,22 @@ export function loadAll(dir) {
109
110
  let laterMap = new Map()
110
111
  try { laterMap = laterEvents.groupByExp(dir) } catch { }
111
112
 
113
+ // 没弄完的事后来怎么样了:想通 / 暂放 / 再接着想
114
+ let unfinishedMap = new Map()
115
+ try { unfinishedMap = unfinishedEvents.latestByExp(dir) } catch { }
116
+
112
117
  return rows.map((r) => {
113
118
  const keys = r.formerId ? [r.id, r.formerId] : [r.id]
114
119
  const extra = keys.flatMap((k) => laterMap.get(k) || [])
115
120
  const merged = [...(r.later || []), ...extra]
116
121
  .sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
117
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
118
129
  let count = 0
119
130
  let lastAt = ''
120
131
  for (const k of keys) {
@@ -222,6 +233,36 @@ export function reviseExperience(dir, { id, thought, reason = '' }) {
222
233
  }
223
234
  }
224
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
+
225
266
  // 想起时记一笔:往 recall-events.jsonl 追加一条事件,不动经历正文
226
267
  // 不做存在性检查:孤儿事件在 loadAll 合并时自然被忽略
227
268
  export function markRecalled(dir, id) {
@@ -328,6 +369,19 @@ export function renderTwoPart(entry, { now = new Date() } = {}) {
328
369
  } else {
329
370
  lines.push('- 之后你还没回头想过')
330
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
+ }
331
385
  lines.push('', '以上是那天留下的全部;没留下的,我不记得。')
332
386
  return lines.join('\n')
333
387
  }
@@ -0,0 +1,26 @@
1
+ export type UnfinishedChoice = 'done' | 'shelved' | 'reopen'
2
+
3
+ export const CHOICES: Set<UnfinishedChoice>
4
+
5
+ export interface UnfinishedEvent {
6
+ id: string
7
+ at: string
8
+ day: string
9
+ choice: UnfinishedChoice
10
+ note: string
11
+ }
12
+
13
+ export interface UnfinishedLatest {
14
+ id: string
15
+ at: string
16
+ day: string
17
+ choice: UnfinishedChoice | ''
18
+ note: string
19
+ history: UnfinishedChoice[]
20
+ }
21
+
22
+ export function eventsFile(memDir: string): string
23
+ export function append(memDir: string, opts: { id: string; choice: UnfinishedChoice; note?: string }, lockOpts?: Record<string, unknown>): UnfinishedEvent
24
+ export function readAll(memDir: string): { rows: UnfinishedEvent[]; bad: number }
25
+ export function latestByExp(memDir: string): Map<string, UnfinishedLatest>
26
+ export function countByExp(memDir: string): Map<string, number>
@@ -0,0 +1,82 @@
1
+ // 「这件没弄完的事」后来怎么样了:想通 / 先放下 / 再接着想
2
+ // 一行一个 { id, at, day, choice, note? },只追加;不改 then.unfinished,也不冒充后记
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { withFileLock } from './file-lock.js'
6
+
7
+ const FILE = 'unfinished-events.jsonl'
8
+ export const CHOICES = new Set(['done', 'shelved', 'reopen'])
9
+
10
+ export function eventsFile(memDir) {
11
+ return path.join(memDir, FILE)
12
+ }
13
+
14
+ export function append(memDir, { id, choice, note = '' } = {}, opts = {}) {
15
+ if (!String(id || '').trim()) throw new Error('id 不能为空')
16
+ if (!CHOICES.has(choice)) throw new Error('choice 只能是 done / shelved / reopen')
17
+ const now = new Date()
18
+ const row = {
19
+ id: String(id),
20
+ at: now.toISOString(),
21
+ day: now.toLocaleDateString('sv-SE'),
22
+ choice,
23
+ note: String(note || '').slice(0, 200)
24
+ }
25
+
26
+ fs.mkdirSync(memDir, { recursive: true })
27
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
28
+ const file = eventsFile(memDir)
29
+ let prefix = ''
30
+ try {
31
+ const st = fs.statSync(file)
32
+ if (st.size) {
33
+ const fd = fs.openSync(file, 'r')
34
+ const buf = Buffer.alloc(1)
35
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
36
+ fs.closeSync(fd)
37
+ if (buf[0] !== 10) prefix = '\n'
38
+ }
39
+ } catch { }
40
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
41
+ return row
42
+ }, opts)
43
+ }
44
+
45
+ export function readAll(memDir) {
46
+ let raw = ''
47
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
48
+ const rows = []
49
+ let bad = 0
50
+ for (const line of raw.split('\n')) {
51
+ if (!line.trim()) continue
52
+ try {
53
+ const r = JSON.parse(line)
54
+ if (r && r.id && CHOICES.has(r.choice)) rows.push(r)
55
+ else bad += 1
56
+ } catch { bad += 1 }
57
+ }
58
+ return { rows, bad }
59
+ }
60
+
61
+ // 每个经历 id 的最新状态,附带完整的选择历史(渲染"中间放下过"要用)
62
+ export function latestByExp(memDir) {
63
+ const { rows } = readAll(memDir)
64
+ const map = new Map()
65
+ for (const r of rows) {
66
+ const cur = map.get(r.id) || { id: r.id, at: '', day: '', choice: '', note: '', history: [] }
67
+ cur.at = r.at
68
+ cur.day = r.day
69
+ cur.choice = r.choice
70
+ cur.note = r.note || ''
71
+ cur.history.push(r.choice)
72
+ map.set(r.id, cur)
73
+ }
74
+ return map
75
+ }
76
+
77
+ export function countByExp(memDir) {
78
+ const { rows } = readAll(memDir)
79
+ const map = new Map()
80
+ for (const r of rows) map.set(r.id, (map.get(r.id) || 0) + 1)
81
+ return map
82
+ }
package/lib/waking.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export function buildWakingBlock(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean }): string
2
2
  export function consumeWaking(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean }): boolean
3
- export function leaveNote(dataDir: string, text: string): { at: string; day: string; text: string }
3
+ export function leaveNote(dataDir: string, text: string): { at: string; day: string; text: string }
4
+ export function isPrivateKey(chatKey: string): boolean
package/lib/waking.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // 醒来块:每天第一次被唤醒时,给她一条自己的时间线
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
+ import * as exp from './self-experience.js'
4
5
 
5
6
  function readJsonl(file) {
6
7
  try {
@@ -16,6 +17,11 @@ function mayShow(key, allowGroup) {
16
17
  return Boolean(key) && (allowGroup || PRIVATE_KEY.test(key))
17
18
  }
18
19
 
20
+ // 给宿主用的同一个判断:注入记忆前先问它,别自己写"不是群就行"
21
+ export function isPrivateKey(chatKey) {
22
+ return mayShow(String(chatKey || '').trim(), false)
23
+ }
24
+
19
25
  // 只读:算出「今天该给她看什么」,不写任何文件
20
26
  // 调用方确认真的把这段注入了,再调 consumeWaking 记「已展示」
21
27
  // 安全默认:没有 chatKey、或不是认得出的一对一会话(未显式 allowGroup)→ 返回空
@@ -32,10 +38,17 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGrou
32
38
  const dedupeKey = key + '|' + today
33
39
  if (flags[dedupeKey]) return ''
34
40
 
35
- const rows = readJsonl(path.join(dir, 'self-experience.jsonl')).map((r) => {
36
- if (r.then) return { day: r.day, text: r.then.text, unfinished: r.then.unfinished, weight: r.weight, later: r.later || [] }
37
- return { day: r.day, text: r.text, unfinished: '', weight: r.weight || 'normal', later: [] }
38
- }).filter((r) => r.text)
41
+ // 用合并后的视图:明确想通/暂放的不再进入未完列表;旧库没有状态事件,行为不变
42
+ let loaded = []
43
+ try { loaded = exp.loadAll(dir) } catch { }
44
+ const rows = loaded.map((r) => ({
45
+ day: r.day,
46
+ text: r.then.text,
47
+ unfinished: r.then.unfinished,
48
+ weight: r.weight,
49
+ later: r.later || [],
50
+ state: r.unfinishedState || null
51
+ })).filter((r) => r.text)
39
52
  const y = new Date(now.getTime() - 86400000).toLocaleDateString('sv-SE')
40
53
  const yRows = rows.filter((r) => r.day === y)
41
54
  const notes = readJsonl(path.join(dir, 'notes-to-tomorrow.jsonl'))
@@ -49,7 +62,7 @@ export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGrou
49
62
  lines.push('昨天你没有留下自己的记录。')
50
63
  }
51
64
  if (lastNote && lastNote.text) lines.push('昨天睡前你给今天留了一句:' + String(lastNote.text).slice(0, 120))
52
- const unfinished = rows.filter((r) => r.unfinished).slice(-2)
65
+ const unfinished = rows.filter((r) => r.unfinished && !(r.state && (r.state.choice === 'done' || r.state.choice === 'shelved'))).slice(-2)
53
66
  for (const r of unfinished) lines.push('- 你还没弄完:' + String(r.unfinished).slice(0, 50))
54
67
  lines.push('(这些是记录,不是别人告诉你的。要不要接着想,你自己定。)')
55
68
  return lines.join('\n')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -49,6 +49,10 @@
49
49
  "./evidence-from-experience": {
50
50
  "types": "./lib/evidence-from-experience.d.ts",
51
51
  "default": "./lib/evidence-from-experience.js"
52
+ },
53
+ "./unfinished-events": {
54
+ "types": "./lib/unfinished-events.d.ts",
55
+ "default": "./lib/unfinished-events.js"
52
56
  }
53
57
  },
54
58
  "files": [