whale-memory-core 0.15.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 -15
  5. package/index.js +18 -17
  6. package/lib/archive.d.ts +22 -22
  7. package/lib/archive.js +171 -135
  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 -28
  45. package/lib/unsaid.js +105 -105
  46. package/lib/waking.d.ts +1 -1
  47. package/lib/waking.js +99 -92
  48. package/package.json +127 -113
package/lib/unsaid.js CHANGED
@@ -1,105 +1,105 @@
1
- // 没说出口的抽屉:打了没发的(draft)、想问没问的(question)、忍住了的(held)
2
- // unsaid-events.jsonl 只追加:留下时一行 {id, at, day, kind, text, reason, status:'open'};
3
- // 后来说出口了 / 不想要了,各追加一行 {id, at, day, status:'spoken'|'discarded'}。原文从不删除
4
- //
5
- // 这个抽屉永不自动打开:recall、醒来块、read、memory、recap、book 都不读这个文件。
6
- // 只有 listUnsaid 给她看,而且只在认得出的一对一会话里;丢掉(discarded)的,她自己也看不到了。
7
- // 为了不让原文从"原始接口"漏出去,这里不导出任何返回原始行的函数
8
- import { createLog, stamp } from './event-log.js'
9
- import { isPrivateKey } from './waking.js'
10
-
11
- export const KINDS = new Set(['draft', 'question', 'held'])
12
- const STATUSES = new Set(['open', 'spoken', 'discarded'])
13
- export const LIMITS = { text: 1000, reason: 200 }
14
-
15
- const log = createLog('unsaid-events.jsonl', {
16
- valid: (r) => Boolean(r.id && STATUSES.has(r.status) && (r.status !== 'open' || (KINDS.has(r.kind) && r.text)))
17
- })
18
- export const eventsFile = log.eventsFile
19
- export const internals = { FILE: log.FILE }
20
-
21
- // 坏行数(给 doctor 用);只给数字,不给内容
22
- export const badLines = (dir) => log.readAll(dir).bad
23
-
24
- function gate(chatKey) {
25
- if (!isPrivateKey(chatKey)) throw new Error('这个抽屉只在一对一的私聊里打开;群聊和认不出的会话一律不给。')
26
- }
27
-
28
- // 重放:每条留下的话现在是什么状态
29
- function replay(rows) {
30
- const map = new Map()
31
- for (const r of rows) {
32
- if (r.status === 'open') {
33
- if (!map.has(r.id)) map.set(r.id, { id: r.id, at: r.at, day: r.day, kind: r.kind, text: r.text, reason: r.reason || '', status: 'open', history: [] })
34
- continue
35
- }
36
- const item = map.get(r.id)
37
- if (!item) continue
38
- item.status = r.status
39
- item.history.push({ status: r.status, at: r.at, day: r.day })
40
- }
41
- return map
42
- }
43
-
44
- const fail = (e) => ({ ok: false, error: String(e && e.message ? e.message : e) })
45
- const tooLong = (name, v, max) => {
46
- const s = String(v || '')
47
- if ([...s].length > max) throw new Error(`${name} 太长(${[...s].length}/${max} 字)。`)
48
- return s
49
- }
50
-
51
- // 留下一句没说出口的话。同一句(同 kind、同原文)还开着时,重复提交是 noop
52
- export function leaveUnsaid(dir, { chatKey, kind = 'draft', text, reason = '' } = {}) {
53
- try {
54
- gate(chatKey)
55
- if (!KINDS.has(kind)) throw new Error('kind 只能是 draft(打了没发)/ question(想问没问)/ held(忍住了)。')
56
- const t = tooLong('text', String(text || '').trim(), LIMITS.text)
57
- if (!t) throw new Error('text 不能是空的。')
58
- const why = tooLong('reason', String(reason || '').trim(), LIMITS.reason)
59
- const res = log.decide(dir, (rows) => {
60
- const same = [...replay(rows).values()].find((x) => x.status === 'open' && x.kind === kind && x.text === t)
61
- if (same) return null
62
- return { id: 'unsaid_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ...stamp(), kind, text: t, reason: why, status: 'open' }
63
- })
64
- if (res.noop) {
65
- const same = [...replay(log.readAll(dir).rows).values()].find((x) => x.status === 'open' && x.kind === kind && x.text === t)
66
- return { ok: true, id: same ? same.id : '', noop: true }
67
- }
68
- return { ok: true, id: res.row.id, day: res.row.day, noop: false }
69
- } catch (e) { return fail(e) }
70
- }
71
-
72
- // 打开抽屉:默认只给还开着的;all=true 时连说出口了的也给(带上哪天说的)。丢掉的从不给
73
- export function listUnsaid(dir, { chatKey, all = false } = {}) {
74
- try {
75
- gate(chatKey)
76
- const items = [...replay(log.readAll(dir).rows).values()]
77
- .filter((x) => x.status === 'open' || (all && x.status === 'spoken'))
78
- .map((x) => {
79
- const spoken = x.history.filter((h) => h.status === 'spoken').pop()
80
- return { id: x.id, day: x.day, kind: x.kind, text: x.text, reason: x.reason, status: x.status, ...(spoken ? { spokenDay: spoken.day } : {}) }
81
- })
82
- return { ok: true, items }
83
- } catch (e) { return fail(e) }
84
- }
85
-
86
- function mark(dir, { chatKey, id }, status) {
87
- try {
88
- gate(chatKey)
89
- if (!String(id || '').trim()) throw new Error('需要 id')
90
- const res = log.decide(dir, (rows) => {
91
- const item = replay(rows).get(String(id))
92
- if (!item) throw new Error('抽屉里没有这一条:' + id)
93
- if (item.status === status) return null
94
- if (item.status === 'discarded') throw new Error('这一条已经丢掉了。')
95
- return { id: String(id), ...stamp(), status }
96
- })
97
- return { ok: true, id: String(id), status, noop: res.noop }
98
- } catch (e) { return fail(e) }
99
- }
100
-
101
- // 后来说出口了:原文还在,状态变成 spoken;重复标记不写第二条
102
- export const markUnsaidSpoken = (dir, opts = {}) => mark(dir, opts, 'spoken')
103
-
104
- // 不想要了:原文不删,但之后她自己也看不到;重复丢不写第二条
105
- export const discardUnsaid = (dir, opts = {}) => mark(dir, opts, 'discarded')
1
+ // 没说出口的抽屉:打了没发的(draft)、想问没问的(question)、忍住了的(held)
2
+ // unsaid-events.jsonl 只追加:留下时一行 {id, at, day, kind, text, reason, status:'open'};
3
+ // 后来说出口了 / 不想要了,各追加一行 {id, at, day, status:'spoken'|'discarded'}。原文从不删除
4
+ //
5
+ // 这个抽屉永不自动打开:recall、醒来块、read、memory、recap、book 都不读这个文件。
6
+ // 只有 listUnsaid 给她看,而且只在认得出的一对一会话里;丢掉(discarded)的,她自己也看不到了。
7
+ // 为了不让原文从"原始接口"漏出去,这里不导出任何返回原始行的函数
8
+ import { createLog, stamp } from './event-log.js'
9
+ import { isPrivateKey } from './waking.js'
10
+
11
+ export const KINDS = new Set(['draft', 'question', 'held'])
12
+ const STATUSES = new Set(['open', 'spoken', 'discarded'])
13
+ export const LIMITS = { text: 1000, reason: 200 }
14
+
15
+ const log = createLog('unsaid-events.jsonl', {
16
+ valid: (r) => Boolean(r.id && STATUSES.has(r.status) && (r.status !== 'open' || (KINDS.has(r.kind) && r.text)))
17
+ })
18
+ export const eventsFile = log.eventsFile
19
+ export const internals = { FILE: log.FILE }
20
+
21
+ // 坏行数(给 doctor 用);只给数字,不给内容
22
+ export const badLines = (dir) => log.readAll(dir).bad
23
+
24
+ function gate(chatKey) {
25
+ if (!isPrivateKey(chatKey)) throw new Error('This drawer only opens in a one-to-one private chat; group chats and unrecognized sessions are refused.(这个抽屉只在一对一的私聊里打开;群聊和认不出的会话一律不给。)')
26
+ }
27
+
28
+ // 重放:每条留下的话现在是什么状态
29
+ function replay(rows) {
30
+ const map = new Map()
31
+ for (const r of rows) {
32
+ if (r.status === 'open') {
33
+ if (!map.has(r.id)) map.set(r.id, { id: r.id, at: r.at, day: r.day, kind: r.kind, text: r.text, reason: r.reason || '', status: 'open', history: [] })
34
+ continue
35
+ }
36
+ const item = map.get(r.id)
37
+ if (!item) continue
38
+ item.status = r.status
39
+ item.history.push({ status: r.status, at: r.at, day: r.day })
40
+ }
41
+ return map
42
+ }
43
+
44
+ const fail = (e) => ({ ok: false, error: String(e && e.message ? e.message : e) })
45
+ const tooLong = (name, v, max) => {
46
+ const s = String(v || '')
47
+ if ([...s].length > max) throw new Error(`${name} is too long (${[...s].length}/${max} chars).(${name} 太长(${[...s].length}/${max} 字)。)`)
48
+ return s
49
+ }
50
+
51
+ // 留下一句没说出口的话。同一句(同 kind、同原文)还开着时,重复提交是 noop
52
+ export function leaveUnsaid(dir, { chatKey, kind = 'draft', text, reason = '' } = {}) {
53
+ try {
54
+ gate(chatKey)
55
+ if (!KINDS.has(kind)) throw new Error('kind must be draft (typed but not sent) / question (wanted to ask but did not) / held (held back).(kind 只能是 draft(打了没发)/ question(想问没问)/ held(忍住了)。)')
56
+ const t = tooLong('text', String(text || '').trim(), LIMITS.text)
57
+ if (!t) throw new Error('text cannot be empty.(text 不能是空的。)')
58
+ const why = tooLong('reason', String(reason || '').trim(), LIMITS.reason)
59
+ const res = log.decide(dir, (rows) => {
60
+ const same = [...replay(rows).values()].find((x) => x.status === 'open' && x.kind === kind && x.text === t)
61
+ if (same) return null
62
+ return { id: 'unsaid_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ...stamp(), kind, text: t, reason: why, status: 'open' }
63
+ })
64
+ if (res.noop) {
65
+ const same = [...replay(log.readAll(dir).rows).values()].find((x) => x.status === 'open' && x.kind === kind && x.text === t)
66
+ return { ok: true, id: same ? same.id : '', noop: true }
67
+ }
68
+ return { ok: true, id: res.row.id, day: res.row.day, noop: false }
69
+ } catch (e) { return fail(e) }
70
+ }
71
+
72
+ // 打开抽屉:默认只给还开着的;all=true 时连说出口了的也给(带上哪天说的)。丢掉的从不给
73
+ export function listUnsaid(dir, { chatKey, all = false } = {}) {
74
+ try {
75
+ gate(chatKey)
76
+ const items = [...replay(log.readAll(dir).rows).values()]
77
+ .filter((x) => x.status === 'open' || (all && x.status === 'spoken'))
78
+ .map((x) => {
79
+ const spoken = x.history.filter((h) => h.status === 'spoken').pop()
80
+ return { id: x.id, day: x.day, kind: x.kind, text: x.text, reason: x.reason, status: x.status, ...(spoken ? { spokenDay: spoken.day } : {}) }
81
+ })
82
+ return { ok: true, items }
83
+ } catch (e) { return fail(e) }
84
+ }
85
+
86
+ function mark(dir, { chatKey, id }, status) {
87
+ try {
88
+ gate(chatKey)
89
+ if (!String(id || '').trim()) throw new Error('Missing id(需要 id)')
90
+ const res = log.decide(dir, (rows) => {
91
+ const item = replay(rows).get(String(id))
92
+ if (!item) throw new Error('No such item in the drawer: ' + id + '(抽屉里没有这一条:' + id + ')')
93
+ if (item.status === status) return null
94
+ if (item.status === 'discarded') throw new Error('This item has already been discarded.(这一条已经丢掉了。)')
95
+ return { id: String(id), ...stamp(), status }
96
+ })
97
+ return { ok: true, id: String(id), status, noop: res.noop }
98
+ } catch (e) { return fail(e) }
99
+ }
100
+
101
+ // 后来说出口了:原文还在,状态变成 spoken;重复标记不写第二条
102
+ export const markUnsaidSpoken = (dir, opts = {}) => mark(dir, opts, 'spoken')
103
+
104
+ // 不想要了:原文不删,但之后她自己也看不到;重复丢不写第二条
105
+ export const discardUnsaid = (dir, opts = {}) => mark(dir, opts, 'discarded')
package/lib/waking.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export function buildWakingBlock(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean }): string
1
+ export function buildWakingBlock(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean; lang?: 'zh' | 'en' }): string
2
2
  export function consumeWaking(dataDir: string, chatKey: string, opts?: { now?: Date; allowGroup?: boolean }): boolean
3
3
  export function leaveNote(dataDir: string, text: string): { at: string; day: string; text: string }
4
4
  export function isPrivateKey(chatKey: string): boolean
package/lib/waking.js CHANGED
@@ -1,93 +1,100 @@
1
- // 醒来块:每天第一次被唤醒时,给她一条自己的时间线
2
- import fs from 'node:fs'
3
- import path from 'node:path'
4
- import * as exp from './self-experience.js'
5
-
6
- function readJsonl(file) {
7
- try {
8
- return fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
9
- } catch { return [] }
10
- }
11
-
12
- function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
13
-
14
- // 只认得出一对一的会话键(private_* / private:* / local_* / local:*);认不出的一律当成可能有别人在,宁可不给
15
- const PRIVATE_KEY = /^(private|local)[:_]/i
16
- function mayShow(key, allowGroup) {
17
- return Boolean(key) && (allowGroup || PRIVATE_KEY.test(key))
18
- }
19
-
20
- // 给宿主用的同一个判断:注入记忆前先问它,别自己写"不是群就行"
21
- export function isPrivateKey(chatKey) {
22
- return mayShow(String(chatKey || '').trim(), false)
23
- }
24
-
25
- // 只读:算出「今天该给她看什么」,不写任何文件
26
- // 调用方确认真的把这段注入了,再调 consumeWaking 记「已展示」
27
- // 安全默认:没有 chatKey、或不是认得出的一对一会话(未显式 allowGroup)→ 返回空
28
- // 醒来块里可能有昨天私下的话,默认不该流到群里
29
- export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
30
- const key = String(chatKey || '').trim()
31
- if (!mayShow(key, allowGroup)) return ''
32
-
33
- const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
34
- const today = dayStr(now)
35
- const flag = path.join(dir, 'waking-flags.json')
36
- let flags = {}
37
- try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
38
- const dedupeKey = key + '|' + today
39
- if (flags[dedupeKey]) return ''
40
-
41
- // 用合并后的视图:明确想通/暂放的不再进入未完列表;旧库没有状态事件,行为不变
42
- // 她封存了的经历不出现在醒来块里,昨天的、没弄完的都一样
43
- let loaded = []
44
- try { loaded = exp.loadAll(dir) } catch { }
45
- const rows = loaded.filter((r) => !r.sealed).map((r) => ({
46
- day: r.day,
47
- text: r.then.text,
48
- unfinished: r.then.unfinished,
49
- weight: r.weight,
50
- later: r.later || [],
51
- state: r.unfinishedState || null
52
- })).filter((r) => r.text)
53
- const y = new Date(now.getTime() - 86400000).toLocaleDateString('sv-SE')
54
- const yRows = rows.filter((r) => r.day === y)
55
- const notes = readJsonl(path.join(dir, 'notes-to-tomorrow.jsonl'))
56
- const lastNote = [...notes].reverse().find((n) => n.day === y)
57
-
58
- const lines = ['【醒来】今天是 ' + today + '。']
59
- if (yRows.length) {
60
- lines.push('昨天你自己的时候:')
61
- for (const r of yRows.slice(-3)) lines.push('- ' + String(r.text).slice(0, 60))
62
- } else {
63
- lines.push('昨天你没有留下自己的记录。')
64
- }
65
- if (lastNote && lastNote.text) lines.push('昨天睡前你给今天留了一句:' + String(lastNote.text).slice(0, 120))
66
- const unfinished = rows.filter((r) => r.unfinished && !(r.state && (r.state.choice === 'done' || r.state.choice === 'shelved'))).slice(-2)
67
- for (const r of unfinished) lines.push('- 你还没弄完:' + String(r.unfinished).slice(0, 50))
68
- lines.push('(这些是记录,不是别人告诉你的。要不要接着想,你自己定。)')
69
- return lines.join('\n')
70
- }
71
-
72
- // 确认已展示:写入 flags,之后同一天同一会话不会再出
73
- export function consumeWaking(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
74
- const key = String(chatKey || '').trim()
75
- if (!mayShow(key, allowGroup)) return false
76
-
77
- const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
78
- fs.mkdirSync(dir, { recursive: true })
79
- const flag = path.join(dir, 'waking-flags.json')
80
- let flags = {}
81
- try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
82
- flags[key + '|' + dayStr(now)] = new Date().toISOString()
83
- fs.writeFileSync(flag, JSON.stringify(flags), 'utf8')
84
- return true
85
- }
86
-
87
- export function leaveNote(dataDir, text) {
88
- const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
89
- fs.mkdirSync(dir, { recursive: true })
90
- const row = { at: new Date().toISOString(), day: dayStr(), text: String(text || '').slice(0, 300) }
91
- fs.appendFileSync(path.join(dir, 'notes-to-tomorrow.jsonl'), JSON.stringify(row) + '\n', 'utf8')
92
- return row
1
+ // 醒来块:每天第一次被唤醒时,给她一条自己的时间线
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import * as exp from './self-experience.js'
5
+
6
+ function readJsonl(file) {
7
+ try {
8
+ return fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l) } catch { return null } }).filter(Boolean)
9
+ } catch { return [] }
10
+ }
11
+
12
+ function dayStr(d = new Date()) { return d.toLocaleDateString('sv-SE') }
13
+
14
+ // 只认得出一对一的会话键(private_* / private:* / local_* / local:*);认不出的一律当成可能有别人在,宁可不给
15
+ const PRIVATE_KEY = /^(private|local)[:_]/i
16
+ function mayShow(key, allowGroup) {
17
+ return Boolean(key) && (allowGroup || PRIVATE_KEY.test(key))
18
+ }
19
+
20
+ // 给宿主用的同一个判断:注入记忆前先问它,别自己写"不是群就行"
21
+ export function isPrivateKey(chatKey) {
22
+ return mayShow(String(chatKey || '').trim(), false)
23
+ }
24
+
25
+ // 只读:算出「今天该给她看什么」,不写任何文件
26
+ // 调用方确认真的把这段注入了,再调 consumeWaking 记「已展示」
27
+ // 安全默认:没有 chatKey、或不是认得出的一对一会话(未显式 allowGroup)→ 返回空
28
+ // 醒来块里可能有昨天私下的话,默认不该流到群里
29
+ // 醒来块的文字:zh(默认,原样不变)/ en
30
+ const WAKE = {
31
+ zh: { head: (d) => '【醒来】今天是 ' + d + '。', yesterday: '昨天你自己的时候:', none: '昨天你没有留下自己的记录。', note: '昨天睡前你给今天留了一句:', unfinished: '- 你还没弄完:', tail: '(这些是记录,不是别人告诉你的。要不要接着想,你自己定。)' },
32
+ en: { head: (d) => '[Waking up] Today is ' + d + '.', yesterday: 'Yesterday, in your own time:', none: 'You left no record of your own yesterday.', note: 'Before sleeping you left a line for today: ', unfinished: '- Still unfinished: ', tail: '(These are your own records, not something someone told you. Whether to keep thinking about them is up to you.)' }
33
+ }
34
+
35
+ export function buildWakingBlock(dataDir, chatKey, { now = new Date(), allowGroup = false, lang = 'zh' } = {}) {
36
+ const W = WAKE[lang === 'en' ? 'en' : 'zh']
37
+ const key = String(chatKey || '').trim()
38
+ if (!mayShow(key, allowGroup)) return ''
39
+
40
+ const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
41
+ const today = dayStr(now)
42
+ const flag = path.join(dir, 'waking-flags.json')
43
+ let flags = {}
44
+ try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
45
+ const dedupeKey = key + '|' + today
46
+ if (flags[dedupeKey]) return ''
47
+
48
+ // 用合并后的视图:明确想通/暂放的不再进入未完列表;旧库没有状态事件,行为不变
49
+ // 她封存了的经历不出现在醒来块里,昨天的、没弄完的都一样
50
+ let loaded = []
51
+ try { loaded = exp.loadAll(dir) } catch { }
52
+ const rows = loaded.filter((r) => !r.sealed).map((r) => ({
53
+ day: r.day,
54
+ text: r.then.text,
55
+ unfinished: r.then.unfinished,
56
+ weight: r.weight,
57
+ later: r.later || [],
58
+ state: r.unfinishedState || null
59
+ })).filter((r) => r.text)
60
+ const y = new Date(now.getTime() - 86400000).toLocaleDateString('sv-SE')
61
+ const yRows = rows.filter((r) => r.day === y)
62
+ const notes = readJsonl(path.join(dir, 'notes-to-tomorrow.jsonl'))
63
+ const lastNote = [...notes].reverse().find((n) => n.day === y)
64
+
65
+ const lines = [W.head(today)]
66
+ if (yRows.length) {
67
+ lines.push(W.yesterday)
68
+ for (const r of yRows.slice(-3)) lines.push('- ' + String(r.text).slice(0, 60))
69
+ } else {
70
+ lines.push(W.none)
71
+ }
72
+ if (lastNote && lastNote.text) lines.push(W.note + String(lastNote.text).slice(0, 120))
73
+ const unfinished = rows.filter((r) => r.unfinished && !(r.state && (r.state.choice === 'done' || r.state.choice === 'shelved'))).slice(-2)
74
+ for (const r of unfinished) lines.push(W.unfinished + String(r.unfinished).slice(0, 50))
75
+ lines.push(W.tail)
76
+ return lines.join('\n')
77
+ }
78
+
79
+ // 确认已展示:写入 flags,之后同一天同一会话不会再出
80
+ export function consumeWaking(dataDir, chatKey, { now = new Date(), allowGroup = false } = {}) {
81
+ const key = String(chatKey || '').trim()
82
+ if (!mayShow(key, allowGroup)) return false
83
+
84
+ const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
85
+ fs.mkdirSync(dir, { recursive: true })
86
+ const flag = path.join(dir, 'waking-flags.json')
87
+ let flags = {}
88
+ try { flags = JSON.parse(fs.readFileSync(flag, 'utf8')) } catch {}
89
+ flags[key + '|' + dayStr(now)] = new Date().toISOString()
90
+ fs.writeFileSync(flag, JSON.stringify(flags), 'utf8')
91
+ return true
92
+ }
93
+
94
+ export function leaveNote(dataDir, text) {
95
+ const dir = path.join(dataDir, 'plugin-data', 'biomimetic-memory')
96
+ fs.mkdirSync(dir, { recursive: true })
97
+ const row = { at: new Date().toISOString(), day: dayStr(), text: String(text || '').slice(0, 300) }
98
+ fs.appendFileSync(path.join(dir, 'notes-to-tomorrow.jsonl'), JSON.stringify(row) + '\n', 'utf8')
99
+ return row
93
100
  }