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,81 +1,81 @@
1
- // 改主意是事件:只追加,不改 then,也不重写经历文件
2
- // 一行一个 { id, at, day, thought, reason?, feeling? }
3
- // feeling 是她「后来再想起时」的感觉;当时的感觉在 then.feeling 里,永远不动
4
- import fs from 'node:fs'
5
- import path from 'node:path'
6
- import { withFileLock } from './file-lock.js'
7
- import { before } from './as-of.js'
8
-
9
- const FILE = 'later-events.jsonl'
10
-
11
- export function eventsFile(memDir) {
12
- return path.join(memDir, FILE)
13
- }
14
-
15
- export function append(memDir, { id, thought, reason = '', feeling = [] } = {}, opts = {}) {
16
- if (!String(id || '').trim()) throw new Error('id 不能为空')
17
- if (!String(thought || '').trim()) throw new Error('thought 不能为空')
18
- const now = new Date()
19
- const row = {
20
- id: String(id),
21
- at: now.toISOString(),
22
- day: now.toLocaleDateString('sv-SE'),
23
- thought: String(thought),
24
- reason: String(reason || '')
25
- }
26
- if (Array.isArray(feeling) && feeling.length) row.feeling = feeling.map(String)
27
-
28
- fs.mkdirSync(memDir, { recursive: true })
29
- return withFileLock(eventsFile(memDir) + '.lock', () => {
30
- const file = eventsFile(memDir)
31
- let prefix = ''
32
- try {
33
- const st = fs.statSync(file)
34
- if (st.size) {
35
- const fd = fs.openSync(file, 'r')
36
- const buf = Buffer.alloc(1)
37
- fs.readSync(fd, buf, 0, 1, st.size - 1)
38
- fs.closeSync(fd)
39
- if (buf[0] !== 10) prefix = '\n'
40
- }
41
- } catch { }
42
- fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
43
- return row
44
- }, opts)
45
- }
46
-
47
- export function readAll(memDir) {
48
- let raw = ''
49
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
50
- const rows = []
51
- let bad = 0
52
- for (const line of raw.split('\n')) {
53
- if (!line.trim()) continue
54
- try {
55
- const r = JSON.parse(line)
56
- if (r && r.id && r.thought) rows.push(r)
57
- else bad += 1
58
- } catch { bad += 1 }
59
- }
60
- return { rows, bad }
61
- }
62
-
63
- // until:只要这一刻之前(含)写下的后记,「翻回那天的自己」用
64
- export function groupByExp(memDir, { until = null } = {}) {
65
- const { rows } = readAll(memDir)
66
- const map = new Map()
67
- for (const r of rows) {
68
- if (!before(r, until)) continue
69
- const list = map.get(r.id) || []
70
- list.push(r)
71
- map.set(r.id, list)
72
- }
73
- return map
74
- }
75
-
76
- export function list(memDir, { id = '', limit = 20 } = {}) {
77
- const { rows } = readAll(memDir)
78
- return rows.filter((r) => !id || r.id === id).slice(-limit).reverse()
79
- }
80
-
1
+ // 改主意是事件:只追加,不改 then,也不重写经历文件
2
+ // 一行一个 { id, at, day, thought, reason?, feeling? }
3
+ // feeling 是她「后来再想起时」的感觉;当时的感觉在 then.feeling 里,永远不动
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
7
+ import { before } from './as-of.js'
8
+
9
+ const FILE = 'later-events.jsonl'
10
+
11
+ export function eventsFile(memDir) {
12
+ return path.join(memDir, FILE)
13
+ }
14
+
15
+ export function append(memDir, { id, thought, reason = '', feeling = [] } = {}, opts = {}) {
16
+ if (!String(id || '').trim()) throw new Error('id cannot be empty(id 不能为空)')
17
+ if (!String(thought || '').trim()) throw new Error('thought cannot be empty(thought 不能为空)')
18
+ const now = new Date()
19
+ const row = {
20
+ id: String(id),
21
+ at: now.toISOString(),
22
+ day: now.toLocaleDateString('sv-SE'),
23
+ thought: String(thought),
24
+ reason: String(reason || '')
25
+ }
26
+ if (Array.isArray(feeling) && feeling.length) row.feeling = feeling.map(String)
27
+
28
+ fs.mkdirSync(memDir, { recursive: true })
29
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
30
+ const file = eventsFile(memDir)
31
+ let prefix = ''
32
+ try {
33
+ const st = fs.statSync(file)
34
+ if (st.size) {
35
+ const fd = fs.openSync(file, 'r')
36
+ const buf = Buffer.alloc(1)
37
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
38
+ fs.closeSync(fd)
39
+ if (buf[0] !== 10) prefix = '\n'
40
+ }
41
+ } catch { }
42
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
43
+ return row
44
+ }, opts)
45
+ }
46
+
47
+ export function readAll(memDir) {
48
+ let raw = ''
49
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
50
+ const rows = []
51
+ let bad = 0
52
+ for (const line of raw.split('\n')) {
53
+ if (!line.trim()) continue
54
+ try {
55
+ const r = JSON.parse(line)
56
+ if (r && r.id && r.thought) rows.push(r)
57
+ else bad += 1
58
+ } catch { bad += 1 }
59
+ }
60
+ return { rows, bad }
61
+ }
62
+
63
+ // until:只要这一刻之前(含)写下的后记,「翻回那天的自己」用
64
+ export function groupByExp(memDir, { until = null } = {}) {
65
+ const { rows } = readAll(memDir)
66
+ const map = new Map()
67
+ for (const r of rows) {
68
+ if (!before(r, until)) continue
69
+ const list = map.get(r.id) || []
70
+ list.push(r)
71
+ map.set(r.id, list)
72
+ }
73
+ return map
74
+ }
75
+
76
+ export function list(memDir, { id = '', limit = 20 } = {}) {
77
+ const { rows } = readAll(memDir)
78
+ return rows.filter((r) => !id || r.id === id).slice(-limit).reverse()
79
+ }
80
+
81
81
  export const internals = { FILE }
@@ -1,15 +1,15 @@
1
- export interface LinkEvent {
2
- from: string
3
- to: string
4
- at: string
5
- day: string
6
- reason: string
7
- }
8
-
9
- export function eventsFile(memDir: string): string
10
- export function readAll(memDir: string): { rows: LinkEvent[]; bad: number }
11
- /** 同一对(不分方向)只连一次;重复是 noop。自己连自己会抛错 */
12
- export function link(memDir: string, opts: { from: string; to: string; reason: string }, lockOpts?: Record<string, unknown>): { row: LinkEvent | null; noop: boolean }
13
- /** 每条经历连着哪些(两头都有);until 用于翻回那天 */
14
- export function linksByExp(memDir: string, opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
15
- export const internals: { FILE: string }
1
+ export interface LinkEvent {
2
+ from: string
3
+ to: string
4
+ at: string
5
+ day: string
6
+ reason: string
7
+ }
8
+
9
+ export function eventsFile(memDir: string): string
10
+ export function readAll(memDir: string): { rows: LinkEvent[]; bad: number }
11
+ /** 同一对(不分方向)只连一次;重复是 noop。自己连自己会抛错 */
12
+ export function link(memDir: string, opts: { from: string; to: string; reason: string }, lockOpts?: Record<string, unknown>): { row: LinkEvent | null; noop: boolean }
13
+ /** 每条经历连着哪些(两头都有);until 用于翻回那天 */
14
+ export function linksByExp(memDir: string, opts?: { until?: number | null }): Map<string, Array<{ other: string; reason: string; at: string; day: string }>>
15
+ export const internals: { FILE: string }
@@ -1,33 +1,33 @@
1
- // 事后联想:她后来才发现两件事有关,亲手把它们连起来
2
- // 一行一个 { from, to, at, day, reason },只追加。不按相似度自动连;不写理由不连
3
- // 和出处(then.refs)的区别:出处是写下这条时就知道的依据;联想是写下之后才发现的关系
4
- import { createLog, stamp } from './event-log.js'
5
- import { before } from './as-of.js'
6
-
7
- const log = createLog('link-events.jsonl', { valid: (r) => Boolean(r.from && r.to && r.reason) })
8
- export const eventsFile = log.eventsFile
9
- export const readAll = log.readAll
10
- export const internals = { FILE: log.FILE }
11
-
12
- const pair = (a, b) => [String(a), String(b)].sort().join('|')
13
-
14
- // 同一对经历(不分方向)只连一次;重复提交是 noop
15
- export function link(memDir, { from, to, reason }, opts = {}) {
16
- if (!from || !to) throw new Error('需要两条经历的 id')
17
- if (String(from) === String(to)) throw new Error('不能把一件事和它自己连起来。')
18
- return log.decide(memDir, (rows) => rows.some((r) => pair(r.from, r.to) === pair(from, to))
19
- ? null
20
- : { from: String(from), to: String(to), ...stamp(), reason: String(reason) }, opts)
21
- }
22
-
23
- // 每条经历连着哪些:不分方向,两头都能看到;until 用于翻回那天
24
- export function linksByExp(memDir, { until = null } = {}) {
25
- const map = new Map()
26
- const push = (id, other, r) => map.set(id, [...(map.get(id) || []), { other, reason: r.reason, at: r.at, day: r.day }])
27
- for (const r of readAll(memDir).rows) {
28
- if (!before(r, until)) continue
29
- push(r.from, r.to, r)
30
- push(r.to, r.from, r)
31
- }
32
- return map
33
- }
1
+ // 事后联想:她后来才发现两件事有关,亲手把它们连起来
2
+ // 一行一个 { from, to, at, day, reason },只追加。不按相似度自动连;不写理由不连
3
+ // 和出处(then.refs)的区别:出处是写下这条时就知道的依据;联想是写下之后才发现的关系
4
+ import { createLog, stamp } from './event-log.js'
5
+ import { before } from './as-of.js'
6
+
7
+ const log = createLog('link-events.jsonl', { valid: (r) => Boolean(r.from && r.to && r.reason) })
8
+ export const eventsFile = log.eventsFile
9
+ export const readAll = log.readAll
10
+ export const internals = { FILE: log.FILE }
11
+
12
+ const pair = (a, b) => [String(a), String(b)].sort().join('|')
13
+
14
+ // 同一对经历(不分方向)只连一次;重复提交是 noop
15
+ export function link(memDir, { from, to, reason }, opts = {}) {
16
+ if (!from || !to) throw new Error('Need the ids of two experiences(需要两条经历的 id)')
17
+ if (String(from) === String(to)) throw new Error('Cannot link an experience to itself.(不能把一件事和它自己连起来。)')
18
+ return log.decide(memDir, (rows) => rows.some((r) => pair(r.from, r.to) === pair(from, to))
19
+ ? null
20
+ : { from: String(from), to: String(to), ...stamp(), reason: String(reason) }, opts)
21
+ }
22
+
23
+ // 每条经历连着哪些:不分方向,两头都能看到;until 用于翻回那天
24
+ export function linksByExp(memDir, { until = null } = {}) {
25
+ const map = new Map()
26
+ const push = (id, other, r) => map.set(id, [...(map.get(id) || []), { other, reason: r.reason, at: r.at, day: r.day }])
27
+ for (const r of readAll(memDir).rows) {
28
+ if (!before(r, until)) continue
29
+ push(r.from, r.to, r)
30
+ push(r.to, r.from, r)
31
+ }
32
+ return map
33
+ }
@@ -36,6 +36,61 @@ export function queryTerms(q) {
36
36
  return { cleaned, terms }
37
37
  }
38
38
 
39
+ // 只起语法作用的单字:算「查询里有多少意思被这段记忆接住了」时不计入
40
+ const STOP_CHARS = new Set([...'的了吗呢吧啊呀么着过在里那这个些次段事就也都还又很把被给跟和与及或是有我你他她它们嘛啦哦呃'])
41
+ // 聊天里的垫话:只是在问"那件事",本身不带内容。只在算覆盖率时跳过,不改 STOP(旧口径和 loose 不受影响)
42
+ const FILLER = new Set([
43
+ '怎么样', '怎样', '上次', '之前', '最近', '说说', '讲讲', '聊聊', '说过', '提过', '讲过', '记不记得', '还记得',
44
+ '跟我', '说的', '讲的', '提到', '那件', '那次', '那段', '那天', '那个时候',
45
+ 'remember', 'recall', 'tell', 'me', 'do', 'does', 'know', 'talk', 'about'
46
+ ])
47
+ // 停用词里只有这些(时间、代词、虚词)整个跳过;「买了 / 说了 / 去了」这类带动作的,动作那个字要算
48
+ const SKIP_WORDS = new Set([...[...STOP].filter((w) => !['买了', '说了', '去了', '来了', '做了', '看到', '了什'].includes(w)), ...FILLER])
49
+ // 任意长度的停用词都要能跳过(以前只看两字,「是不是」「有没有」「记不记得」从来没跳过)
50
+ const SKIP_LENS = [...new Set([...SKIP_WORDS].filter((w) => !/[a-z]/.test(w)).map((w) => w.length))].sort((a, b) => b - a)
51
+ // 单独出现的字在长记忆里很容易碰巧有:记忆越长,单字给的分越少
52
+ const ISOLATED_LEN = 60
53
+ // 可以跟在内容字右边、算作"连着"的助词和语气词
54
+ const SUFFIX = new Set([...'了的吗呢吧啊呀么着过'])
55
+
56
+ // 查询里要被接住的单位:拉丁字母按整词;其余按单字,并记下它左右两个两字组(用来判断是不是连着出现)
57
+ export function contentUnits(q) {
58
+ const lower = String(q || '').toLowerCase()
59
+ const units = []
60
+ for (const w of lower.match(/[a-z]+/g) || []) if (w.length >= 2 && !STOP.has(w) && !FILLER.has(w)) units.push({ u: w, pairs: [] })
61
+ for (const run of lower.replace(/[a-z]+/g, ' ').split(/[\s\p{P}\p{S}]+/u)) {
62
+ const skip = new Set()
63
+ for (let i = 0; i < run.length; i++) for (const L of SKIP_LENS) if (i + L <= run.length && SKIP_WORDS.has(run.slice(i, i + L))) for (let k = i; k < i + L; k++) skip.add(k)
64
+ const content = (i) => i >= 0 && i < run.length && !skip.has(i) && !STOP_CHARS.has(run[i])
65
+ for (let i = 0; i < run.length; i++) {
66
+ if (!content(i)) continue
67
+ // 两字组:左边只认内容字(「他想」的"他"不算,长记忆里随便一个"他想"都能接住);
68
+ // 右边还认紧跟着的语气、助词(「凉了」「好的」:形容词、动词后面常跟它们)
69
+ const right = content(i + 1) || (i + 1 < run.length && SUFFIX.has(run[i + 1]))
70
+ units.push({ u: run[i], pairs: [content(i - 1) ? run.slice(i - 1, i + 1) : '', right ? run.slice(i, i + 2) : ''].filter(Boolean) })
71
+ }
72
+ }
73
+ return units
74
+ }
75
+
76
+ // 覆盖率:查询里的意思有几成在这段记忆里找得到(0~1)
77
+ // 和左右任一个内容字连着出现在记忆里 → 1 分;只是单独出现 → 0.5 × min(1, 60 / 记忆长度) 分;没有 → 0
78
+ // 「灯塔里的猫」:灯塔连着在,猫不在 → 2/3,不算想起来;「守灯人修透镜那段」→ 5.5/6
79
+ export function coverage(units, text) {
80
+ if (!units.length) return 0
81
+ const t = normalizeText(text)
82
+ let got = 0
83
+ for (const x of units) {
84
+ if (!x.pairs.length) { if (t.includes(x.u)) got += 1; continue }
85
+ if (x.pairs.some((p) => t.includes(p))) got += 1
86
+ else if (t.includes(x.u)) got += 0.5 * Math.min(1, ISOLATED_LEN / Math.max(1, t.length))
87
+ }
88
+ return got / units.length
89
+ }
90
+
91
+ // strict 的门槛:至少对上一个两字词(有个落脚点),并且查询的意思至少有这么多被接住
92
+ export const MIN_COVER = 0.7
93
+
39
94
  // mode='strict':长查询(≥8 字)要求 ≥minRatio 的词命中,宁可不召回也不硬凑
40
95
  // mode='loose':只要求 minOverlap 个词命中
41
96
  export function requiredOverlap({ cleaned, terms }, { mode = 'strict', minOverlap = 1, minRatio = 0.6 } = {}) {
@@ -1,25 +1,25 @@
1
- export interface RecallEvent {
2
- id: string
3
- at: string
4
- query: string
5
- chatKey: string
6
- backfilled?: boolean
7
- }
8
-
9
- export function eventsFile(memDir: string): string
10
-
11
- export function append(memDir: string, event: {
12
- id: string
13
- query?: string
14
- chatKey?: string
15
- backfilled?: boolean
16
- }, opts?: { timeoutMs?: number }): RecallEvent
17
-
18
- export function readAll(memDir: string): { rows: RecallEvent[]; bad: number }
19
-
20
- /** until:只数这一刻(毫秒时间戳)之前(含)的想起 */
21
- export function countByExp(memDir: string, opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
22
-
23
- export function list(memDir: string, opts?: { id?: string; limit?: number }): RecallEvent[]
24
-
1
+ export interface RecallEvent {
2
+ id: string
3
+ at: string
4
+ query: string
5
+ chatKey: string
6
+ backfilled?: boolean
7
+ }
8
+
9
+ export function eventsFile(memDir: string): string
10
+
11
+ export function append(memDir: string, event: {
12
+ id: string
13
+ query?: string
14
+ chatKey?: string
15
+ backfilled?: boolean
16
+ }, opts?: { timeoutMs?: number }): RecallEvent
17
+
18
+ export function readAll(memDir: string): { rows: RecallEvent[]; bad: number }
19
+
20
+ /** until:只数这一刻(毫秒时间戳)之前(含)的想起 */
21
+ export function countByExp(memDir: string, opts?: { until?: number | null }): Map<string, { count: number; lastAt: string }>
22
+
23
+ export function list(memDir: string, opts?: { id?: string; limit?: number }): RecallEvent[]
24
+
25
25
  export const internals: { FILE: string }
@@ -1,98 +1,98 @@
1
- // 想起是事件:只追加,不改经历正文
2
- // 一行一个 { id, at, query, chatKey?, backfilled? }
3
- // 参数是记忆目录本身(<data>/plugin-data/biomimetic-memory),与 self-experience 一致
4
- import fs from 'node:fs'
5
- import path from 'node:path'
6
- import { withFileLock } from './file-lock.js'
7
- import { before } from './as-of.js'
8
-
9
- const FILE = 'recall-events.jsonl'
10
-
11
- export function eventsFile(memDir) {
12
- return path.join(memDir, FILE)
13
- }
14
-
15
- function ensureDir(memDir) {
16
- fs.mkdirSync(memDir, { recursive: true })
17
- }
18
-
19
-
20
-
21
- export function append(memDir, { id, query = '', chatKey = '', backfilled = false } = {}, opts = {}) {
22
- if (!String(id || '').trim()) throw new Error('id 不能为空')
23
- const row = {
24
- id: String(id),
25
- at: new Date().toISOString(),
26
- query: String(query || '').slice(0, 200),
27
- chatKey: String(chatKey || '').slice(0, 120)
28
- }
29
- if (backfilled) row.backfilled = true
30
-
31
- ensureDir(memDir)
32
- return withFileLock(eventsFile(memDir) + '.lock', () => {
33
- const file = eventsFile(memDir)
34
- let prefix = ''
35
- try {
36
- const st = fs.statSync(file)
37
- if (st.size) {
38
- const fd = fs.openSync(file, 'r')
39
- const buf = Buffer.alloc(1)
40
- fs.readSync(fd, buf, 0, 1, st.size - 1)
41
- fs.closeSync(fd)
42
- if (buf[0] !== 10) prefix = '\n'
43
- }
44
- } catch { }
45
- fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
46
- return row
47
- }, opts)
48
- }
49
-
50
- export function readAll(memDir) {
51
- let raw = ''
52
- try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
53
- const rows = []
54
- let bad = 0
55
- for (const line of raw.split('\n')) {
56
- if (!line.trim()) continue
57
- try {
58
- const r = JSON.parse(line)
59
- if (r && r.id) rows.push(r)
60
- else bad += 1
61
- } catch { bad += 1 }
62
- }
63
- return { rows, bad }
64
- }
65
-
66
- // 进程内缓存:同一进程里连续 recall 不再重复解析整个事件文件
67
- const memo = new Map()
68
-
69
- // until:只数这一刻之前(含)的想起;截断查询不走缓存
70
- export function countByExp(memDir, { until = null } = {}) {
71
- const file = eventsFile(memDir)
72
- let stamp = ''
73
- try { const st = fs.statSync(file); stamp = st.mtimeMs + ':' + st.size } catch { }
74
- const hit = until === null ? memo.get(memDir) : null
75
- if (hit && hit.stamp === stamp) return hit.map
76
-
77
- const { rows } = readAll(memDir)
78
- const map = new Map()
79
- for (const r of rows) {
80
- if (!before(r, until)) continue
81
- const cur = map.get(r.id) || { count: 0, lastAt: '' }
82
- cur.count += 1
83
- if (String(r.at || '') > cur.lastAt) cur.lastAt = String(r.at || '')
84
- map.set(r.id, cur)
85
- }
86
- if (until === null) memo.set(memDir, { stamp, map })
87
- return map
88
- }
89
-
90
- export function list(memDir, { id = '', limit = 20 } = {}) {
91
- const { rows } = readAll(memDir)
92
- return rows
93
- .filter((r) => !id || r.id === id)
94
- .slice(-limit)
95
- .reverse()
96
- }
97
-
1
+ // 想起是事件:只追加,不改经历正文
2
+ // 一行一个 { id, at, query, chatKey?, backfilled? }
3
+ // 参数是记忆目录本身(<data>/plugin-data/biomimetic-memory),与 self-experience 一致
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
7
+ import { before } from './as-of.js'
8
+
9
+ const FILE = 'recall-events.jsonl'
10
+
11
+ export function eventsFile(memDir) {
12
+ return path.join(memDir, FILE)
13
+ }
14
+
15
+ function ensureDir(memDir) {
16
+ fs.mkdirSync(memDir, { recursive: true })
17
+ }
18
+
19
+
20
+
21
+ export function append(memDir, { id, query = '', chatKey = '', backfilled = false } = {}, opts = {}) {
22
+ if (!String(id || '').trim()) throw new Error('id cannot be empty(id 不能为空)')
23
+ const row = {
24
+ id: String(id),
25
+ at: new Date().toISOString(),
26
+ query: String(query || '').slice(0, 200),
27
+ chatKey: String(chatKey || '').slice(0, 120)
28
+ }
29
+ if (backfilled) row.backfilled = true
30
+
31
+ ensureDir(memDir)
32
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
33
+ const file = eventsFile(memDir)
34
+ let prefix = ''
35
+ try {
36
+ const st = fs.statSync(file)
37
+ if (st.size) {
38
+ const fd = fs.openSync(file, 'r')
39
+ const buf = Buffer.alloc(1)
40
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
41
+ fs.closeSync(fd)
42
+ if (buf[0] !== 10) prefix = '\n'
43
+ }
44
+ } catch { }
45
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
46
+ return row
47
+ }, opts)
48
+ }
49
+
50
+ export function readAll(memDir) {
51
+ let raw = ''
52
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
53
+ const rows = []
54
+ let bad = 0
55
+ for (const line of raw.split('\n')) {
56
+ if (!line.trim()) continue
57
+ try {
58
+ const r = JSON.parse(line)
59
+ if (r && r.id) rows.push(r)
60
+ else bad += 1
61
+ } catch { bad += 1 }
62
+ }
63
+ return { rows, bad }
64
+ }
65
+
66
+ // 进程内缓存:同一进程里连续 recall 不再重复解析整个事件文件
67
+ const memo = new Map()
68
+
69
+ // until:只数这一刻之前(含)的想起;截断查询不走缓存
70
+ export function countByExp(memDir, { until = null } = {}) {
71
+ const file = eventsFile(memDir)
72
+ let stamp = ''
73
+ try { const st = fs.statSync(file); stamp = st.mtimeMs + ':' + st.size } catch { }
74
+ const hit = until === null ? memo.get(memDir) : null
75
+ if (hit && hit.stamp === stamp) return hit.map
76
+
77
+ const { rows } = readAll(memDir)
78
+ const map = new Map()
79
+ for (const r of rows) {
80
+ if (!before(r, until)) continue
81
+ const cur = map.get(r.id) || { count: 0, lastAt: '' }
82
+ cur.count += 1
83
+ if (String(r.at || '') > cur.lastAt) cur.lastAt = String(r.at || '')
84
+ map.set(r.id, cur)
85
+ }
86
+ if (until === null) memo.set(memDir, { stamp, map })
87
+ return map
88
+ }
89
+
90
+ export function list(memDir, { id = '', limit = 20 } = {}) {
91
+ const { rows } = readAll(memDir)
92
+ return rows
93
+ .filter((r) => !id || r.id === id)
94
+ .slice(-limit)
95
+ .reverse()
96
+ }
97
+
98
98
  export const internals = { FILE }
package/lib/recap.d.ts CHANGED
@@ -1,23 +1,23 @@
1
- import type { AsOf } from './self-experience.js'
2
-
3
- export interface RecapItem {
4
- id: string
5
- day: string
6
- text: string
7
- }
8
-
9
- export interface Recap {
10
- from: string
11
- to: string
12
- days: number
13
- written: Array<RecapItem & { kind: string; feeling: string[]; refs: string[] }>
14
- revised: Array<RecapItem & { thought: string; feeling: string[]; at: string; laterDay: string }>
15
- feelingShifts: Array<RecapItem & { then: string[]; now: string[]; laterDay: string }>
16
- settled: Array<RecapItem & { unfinished: string; choice: 'done' | 'shelved'; stateDay: string }>
17
- reopened: Array<RecapItem & { unfinished: string; choice: 'reopen'; stateDay: string }>
18
- stillOpen: Array<RecapItem & { unfinished: string }>
19
- }
20
-
21
- /** 只整理事实,不调模型、不下结论;她封存了的不列 */
22
- export function recap(dir: string, opts?: { days?: number; asOf?: AsOf; now?: Date }): Recap
23
- export function renderRecap(recap: Recap): string
1
+ import type { AsOf } from './self-experience.js'
2
+
3
+ export interface RecapItem {
4
+ id: string
5
+ day: string
6
+ text: string
7
+ }
8
+
9
+ export interface Recap {
10
+ from: string
11
+ to: string
12
+ days: number
13
+ written: Array<RecapItem & { kind: string; feeling: string[]; refs: string[] }>
14
+ revised: Array<RecapItem & { thought: string; feeling: string[]; at: string; laterDay: string }>
15
+ feelingShifts: Array<RecapItem & { then: string[]; now: string[]; laterDay: string }>
16
+ settled: Array<RecapItem & { unfinished: string; choice: 'done' | 'shelved'; stateDay: string }>
17
+ reopened: Array<RecapItem & { unfinished: string; choice: 'reopen'; stateDay: string }>
18
+ stillOpen: Array<RecapItem & { unfinished: string }>
19
+ }
20
+
21
+ /** 只整理事实,不调模型、不下结论;她封存了的不列 */
22
+ export function recap(dir: string, opts?: { days?: number; asOf?: AsOf; now?: Date }): Recap
23
+ export function renderRecap(recap: Recap): string