whale-memory-core 0.11.2 → 0.15.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.d.ts CHANGED
@@ -1,8 +1,15 @@
1
- export * as selfExperience from './lib/self-experience.js'
2
- export * as selfMemory from './lib/self-memory.js'
3
- export * as waking from './lib/waking.js'
4
- export * as selfPrompt from './lib/self-prompt.js'
5
- export * as selfSettings from './lib/self-settings.js'
6
- export * as evidencePolicy from './lib/evidence-policy.js'
7
- export * as evidenceFromExperience from './lib/evidence-from-experience.js'
8
- export * as unfinishedEvents from './lib/unfinished-events.js'
1
+ export * as selfExperience from './lib/self-experience.js'
2
+ export * as selfMemory from './lib/self-memory.js'
3
+ export * as waking from './lib/waking.js'
4
+ export * as selfPrompt from './lib/self-prompt.js'
5
+ export * as selfSettings from './lib/self-settings.js'
6
+ export * as evidencePolicy from './lib/evidence-policy.js'
7
+ export * as evidenceFromExperience from './lib/evidence-from-experience.js'
8
+ export * as unfinishedEvents from './lib/unfinished-events.js'
9
+ export * as sealEvents from './lib/seal-events.js'
10
+ export * as recap from './lib/recap.js'
11
+ export * as linkEvents from './lib/link-events.js'
12
+ export * as chapterEvents from './lib/chapter-events.js'
13
+ export * as book from './lib/book.js'
14
+ export * as unsaid from './lib/unsaid.js'
15
+ export * as archive from './lib/archive.js'
package/index.js CHANGED
@@ -1,10 +1,17 @@
1
- // whale-memory core:不依赖 QQ Agent 的可复用记忆内核
2
- // 只放通用模块;宿主相关的工具注册与提示词拼接由使用者自己实现
3
- export * as selfExperience from './lib/self-experience.js'
4
- export * as selfMemory from './lib/self-memory.js'
5
- export * as waking from './lib/waking.js'
6
- export * as selfPrompt from './lib/self-prompt.js'
7
- export * as selfSettings from './lib/self-settings.js'
8
- export * as evidencePolicy from './lib/evidence-policy.js'
9
- export * as evidenceFromExperience from './lib/evidence-from-experience.js'
10
- export * as unfinishedEvents from './lib/unfinished-events.js'
1
+ // whale-memory core:不依赖 QQ Agent 的可复用记忆内核
2
+ // 只放通用模块;宿主相关的工具注册与提示词拼接由使用者自己实现
3
+ export * as selfExperience from './lib/self-experience.js'
4
+ export * as selfMemory from './lib/self-memory.js'
5
+ export * as waking from './lib/waking.js'
6
+ export * as selfPrompt from './lib/self-prompt.js'
7
+ export * as selfSettings from './lib/self-settings.js'
8
+ export * as evidencePolicy from './lib/evidence-policy.js'
9
+ export * as evidenceFromExperience from './lib/evidence-from-experience.js'
10
+ export * as unfinishedEvents from './lib/unfinished-events.js'
11
+ export * as sealEvents from './lib/seal-events.js'
12
+ export * as recap from './lib/recap.js'
13
+ export * as linkEvents from './lib/link-events.js'
14
+ export * as chapterEvents from './lib/chapter-events.js'
15
+ export * as book from './lib/book.js'
16
+ export * as unsaid from './lib/unsaid.js'
17
+ export * as archive from './lib/archive.js'
@@ -0,0 +1,22 @@
1
+ export const FORMAT: 'whale-memory-export'
2
+ export function sha256(buf: Uint8Array | string): string
3
+ export function stamp(): string
4
+ export function collectFiles(root: string): Array<{ name: string; abs: string }>
5
+ /** a 是否等于 b 或在 b 里面(按解析后的绝对路径) */
6
+ export function inside(a: string, b: string): boolean
7
+ /** 越界路径(正反斜杠、绝对路径、盘符、..)抛错 */
8
+ export function safeJoin(root: string, name: string): string
9
+
10
+ export interface ArchiveManifest {
11
+ format: 'whale-memory-export'
12
+ version: number
13
+ exportedAt: string
14
+ files: Array<{ name: string; bytes: number; sha256: string }>
15
+ counts: Record<string, number>
16
+ }
17
+
18
+ export function exportArchive(memDir: string, outDir: string, opts?: { name?: string }): { ok: true; dir: string; files: number; bytes: number; counts: Record<string, number> }
19
+ /** 整包校验;不对就抛错并说清是哪个文件 */
20
+ export function verifyArchive(fromDir: string): ArchiveManifest
21
+ /** 先整包校验;目标已有数据时默认拒绝,force 先把现有目录改名备份 */
22
+ export function importArchive(fromDir: string, memDir: string, opts?: { force?: boolean }): { ok: true; files: number; restoreTo: string; backup: string; counts: { experiences: number } }
package/lib/archive.js ADDED
@@ -0,0 +1,135 @@
1
+ // 记忆目录的打包与恢复:导出、校验、导入共用这一份。CLI 的 export/import、tools/backup.mjs、tools/restore-check.mjs 都走这里
2
+ // 导出包 = 记忆目录里每个文件的原样副本 + manifest.json(每个文件的大小与 SHA-256)
3
+ // 导入前先校验全部文件,坏一个就一个字节都不写;路径越界(正反斜杠、绝对路径、盘符、..)一律拒绝
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import crypto from 'node:crypto'
7
+ import { loadAll } from './self-experience.js'
8
+
9
+ export const FORMAT = 'whale-memory-export'
10
+ export const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex')
11
+ export const stamp = () => new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
12
+
13
+ // 导出的文件清单:跳过锁文件和临时文件,其余按相对路径收
14
+ export function collectFiles(root) {
15
+ const out = []
16
+ const walk = (dir, rel) => {
17
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
18
+ if (e.name.endsWith('.lock') || e.name.includes('.tmp-')) continue
19
+ const abs = path.join(dir, e.name)
20
+ const next = rel ? rel + '/' + e.name : e.name
21
+ if (e.isDirectory()) { walk(abs, next); continue }
22
+ if (e.isFile()) out.push({ name: next, abs })
23
+ }
24
+ }
25
+ walk(root, '')
26
+ return out.sort((a, b) => a.name.localeCompare(b.name))
27
+ }
28
+
29
+ function countLines(file) {
30
+ try {
31
+ return fs.readFileSync(file, 'utf8').split('\n').filter((l) => l.trim()).length
32
+ } catch { return 0 }
33
+ }
34
+
35
+ // a 是否等于 b 或在 b 里面(都按解析后的绝对路径比)
36
+ export function inside(a, b) {
37
+ const x = path.resolve(a), y = path.resolve(b)
38
+ return x === y || x.startsWith(y + path.sep)
39
+ }
40
+
41
+ // 导出包里的相对路径:正反斜杠、绝对路径、盘符相对路径、任何 '..' 段都拒绝,
42
+ // 再用解析后的绝对路径确认确实落在 root 里面(不靠枚举写法)
43
+ export function safeJoin(root, name) {
44
+ const n = String(name || '')
45
+ if (!n || n.includes('\0')) throw new Error('导出里有可疑路径:' + JSON.stringify(name))
46
+ if (path.isAbsolute(n) || path.win32.isAbsolute(n) || /^[a-zA-Z]:/.test(n)) throw new Error('导出里有绝对路径:' + n)
47
+ if (n.split(/[\\/]+/).includes('..')) throw new Error('导出里有越界路径:' + n)
48
+ const rootAbs = path.resolve(root)
49
+ const abs = path.resolve(rootAbs, n)
50
+ if (abs !== rootAbs && !abs.startsWith(rootAbs + path.sep)) throw new Error('导出里有越界路径:' + n)
51
+ return abs
52
+ }
53
+
54
+ // 打包:outDir 下新建 <name>/(默认 memory-export-<时间>),不能和记忆目录互相包含
55
+ export function exportArchive(memDir, outDir, { name = '' } = {}) {
56
+ if (!fs.existsSync(memDir)) throw new Error('没有找到记忆目录:' + memDir)
57
+ const target = path.resolve(outDir, name || 'memory-export-' + stamp())
58
+ if (inside(target, memDir) || inside(memDir, target)) throw new Error('导出目录不能和记忆目录互相包含:' + target)
59
+ if (fs.existsSync(target)) throw new Error('导出目录已存在:' + target)
60
+
61
+ const files = collectFiles(memDir)
62
+ fs.mkdirSync(target, { recursive: true })
63
+ const manifestFiles = []
64
+ let bytes = 0
65
+ for (const f of files) {
66
+ const content = fs.readFileSync(f.abs)
67
+ const dest = path.join(target, f.name)
68
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
69
+ fs.writeFileSync(dest, content)
70
+ manifestFiles.push({ name: f.name, bytes: content.length, sha256: sha256(content) })
71
+ bytes += content.length
72
+ }
73
+ const manifest = {
74
+ format: FORMAT,
75
+ version: 1,
76
+ exportedAt: new Date().toISOString(),
77
+ files: manifestFiles,
78
+ counts: {
79
+ experiences: loadAll(memDir).length,
80
+ diaries: countLines(path.join(memDir, 'autobiography.jsonl')),
81
+ laterEvents: countLines(path.join(memDir, 'later-events.jsonl')),
82
+ recallEvents: countLines(path.join(memDir, 'recall-events.jsonl')),
83
+ unfinishedEvents: countLines(path.join(memDir, 'unfinished-events.jsonl')),
84
+ sealEvents: countLines(path.join(memDir, 'seal-events.jsonl')),
85
+ linkEvents: countLines(path.join(memDir, 'link-events.jsonl')),
86
+ chapterEvents: countLines(path.join(memDir, 'chapter-events.jsonl')),
87
+ unsaidEvents: countLines(path.join(memDir, 'unsaid-events.jsonl'))
88
+ }
89
+ }
90
+ fs.writeFileSync(path.join(target, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8')
91
+ return { ok: true, dir: target, files: manifestFiles.length, bytes, counts: manifest.counts }
92
+ }
93
+
94
+ // 校验导出包:manifest 读得出、格式对、每个文件都在且 SHA-256 一致;不对就抛错,说清是哪一个
95
+ export function verifyArchive(fromDir) {
96
+ const src = path.resolve(fromDir)
97
+ const manifestFile = path.join(src, 'manifest.json')
98
+ if (!fs.existsSync(manifestFile)) throw new Error('不是 whale-memory 导出目录(缺 manifest.json):' + src)
99
+ let manifest
100
+ try { manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8')) } catch {
101
+ throw new Error('manifest.json 读不出来:' + manifestFile)
102
+ }
103
+ if (!manifest || manifest.format !== FORMAT || !Array.isArray(manifest.files)) {
104
+ throw new Error('manifest.json 格式不对:' + manifestFile)
105
+ }
106
+ for (const f of manifest.files) {
107
+ const n = String(f.name || '')
108
+ const abs = safeJoin(src, n)
109
+ if (!fs.existsSync(abs)) throw new Error('导出缺少文件:' + n)
110
+ const buf = fs.readFileSync(abs)
111
+ if (sha256(buf) !== f.sha256) throw new Error('文件校验不通过:' + n)
112
+ }
113
+ return manifest
114
+ }
115
+
116
+ // 恢复:先整包校验;目标已有数据时默认拒绝,force 会先把现有目录改名备份
117
+ export function importArchive(fromDir, memDir, { force = false } = {}) {
118
+ const src = path.resolve(fromDir)
119
+ const manifest = verifyArchive(src)
120
+ const exists = fs.existsSync(memDir) && fs.readdirSync(memDir).length > 0
121
+ if (exists && !force) throw new Error('目标已有数据:' + memDir + '。确认覆盖请加 --force true(会先备份)')
122
+ let backup = ''
123
+ if (exists && force) {
124
+ backup = memDir + '.pre-import-' + stamp()
125
+ fs.renameSync(memDir, backup)
126
+ }
127
+ fs.mkdirSync(memDir, { recursive: true })
128
+ for (const f of manifest.files) {
129
+ const dest = safeJoin(memDir, f.name)
130
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
131
+ fs.copyFileSync(safeJoin(src, f.name), dest)
132
+ }
133
+ const loaded = loadAll(memDir)
134
+ return { ok: true, files: manifest.files.length, restoreTo: memDir, backup, counts: { experiences: loaded.length } }
135
+ }
package/lib/as-of.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /** 「2026-11-15」= 那天本地时间最后一刻;也接受 ISO 时间或 Date;空值返回 null(不截断) */
2
+ export function parseAsOf(v: string | Date | null | undefined): number | null
3
+ /** 这条记录是否发生在截断时刻之前(含);until 为 null 表示不截断 */
4
+ export function before(row: { at?: string } | null | undefined, until: number | null | undefined): boolean
5
+ export function dayOf(ms: number): string
package/lib/as-of.js ADDED
@@ -0,0 +1,32 @@
1
+ // 「翻回那天的自己」用的时间口径:只在这里定义一次
2
+ // 「2026-11-15」= 那天本地时间的最后一刻(23:59:59.999);也接受完整的 ISO 时间
3
+ // 没有时间戳的记录无法放到时间线上:截断时一律不算在"那时"里
4
+
5
+ export function parseAsOf(v) {
6
+ if (v === undefined || v === null || v === '') return null
7
+ if (v instanceof Date) {
8
+ const t = v.getTime()
9
+ if (!Number.isFinite(t)) throw new Error('as-of 时间不合法。')
10
+ return t
11
+ }
12
+ const s = String(v).trim()
13
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s)
14
+ if (day) {
15
+ const [y, m, d] = [Number(day[1]), Number(day[2]), Number(day[3])]
16
+ const end = new Date(y, m - 1, d, 23, 59, 59, 999)
17
+ if (end.getFullYear() !== y || end.getMonth() !== m - 1 || end.getDate() !== d) throw new Error('as-of 日期不存在:' + s)
18
+ return end.getTime()
19
+ }
20
+ const t = Date.parse(s)
21
+ if (!Number.isFinite(t)) throw new Error('as-of 时间看不懂:' + s + '(用 2026-11-15 这样的日期,或完整的 ISO 时间)')
22
+ return t
23
+ }
24
+
25
+ // 这条记录在截断时刻之前(含)发生过吗?until 为 null 表示不截断
26
+ export function before(row, until) {
27
+ if (until === null || until === undefined) return true
28
+ const t = Date.parse(String((row && row.at) || ''))
29
+ return Number.isFinite(t) && t <= until
30
+ }
31
+
32
+ export const dayOf = (ms) => new Date(ms).toLocaleDateString('sv-SE')
package/lib/book.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { AsOf } from './self-experience.js'
2
+
3
+ /** 人能读的 Markdown 自传:按章节分组,章节外按月份;封存的默认不收 */
4
+ export function renderBook(dir: string, opts?: { asOf?: AsOf; includeSealed?: boolean; title?: string; now?: Date }): string
package/lib/book.js ADDED
@@ -0,0 +1,75 @@
1
+ // 她的书:把自传导出成人能读的 Markdown
2
+ // 按她起过名字的章节分组;没归进章节的按月份。每一条的「当时」是原样,「后来」按时间接在后面
3
+ // 封存了的默认不收,只说收了几件、没收几件;asOf 导出"那时的她"写到那天为止的书
4
+ import { loadAll } from './self-experience.js'
5
+ import * as chapterEvents from './chapter-events.js'
6
+ import { parseAsOf, dayOf } from './as-of.js'
7
+
8
+ const range = (c) => c.from + ' ~ ' + (c.to || '至今')
9
+ const laterDay = (l) => l.day || String(l.at || '').slice(0, 10)
10
+ const ptr = (x) => x.missing ? '(' + x.id + ',找不到了)' : x.sealed ? '(一件封存了的事)' : x.day + '「' + x.text + '」'
11
+
12
+ function entry(r) {
13
+ const t = r.then
14
+ const out = ['### ' + (r.day || '没有日期') + (r.kind && r.kind !== '其它' ? ' · ' + r.kind : '') + (r.weight === 'important' ? ' · 重要' : ''), '']
15
+ if (t.scene) out.push('*' + t.scene + '*', '')
16
+ if (t.quote && t.quote.text) out.push('> ' + t.quote.text + (t.quote.source ? '(' + t.quote.source + ')' : ''), '')
17
+ out.push(t.text, '')
18
+ const meta = []
19
+ if (Array.isArray(r.refsInfo) && r.refsInfo.length) meta.push('是从这些事想到的:' + r.refsInfo.map(ptr).join(';'))
20
+ if ((t.feeling || []).length) meta.push('当时的感觉:' + t.feeling.join('、'))
21
+ if (t.thought) meta.push('当时的想法:' + t.thought)
22
+ if (t.unfinished) meta.push('还没完的:' + t.unfinished)
23
+ for (const m of meta) out.push('- ' + m)
24
+ if (meta.length) out.push('')
25
+ const later = r.later || []
26
+ if (later.length) {
27
+ out.push('**后来**', '')
28
+ for (const l of later) out.push('- ' + laterDay(l) + ':' + l.thought + (Array.isArray(l.feeling) && l.feeling.length ? '(再想起时:' + l.feeling.join('、') + ')' : ''))
29
+ out.push('')
30
+ }
31
+ const st = r.unfinishedState
32
+ if (st && t.unfinished) {
33
+ const word = { done: '想通了', shelved: '先放下了', reopen: '又接着想' }[st.choice] || st.choice
34
+ out.push('- 「' + t.unfinished + '」' + word + '(' + st.day + ')', '')
35
+ }
36
+ if (Array.isArray(r.links) && r.links.length) out.push('- 后来连在一起的:' + r.links.map((l) => l.sealed ? ptr(l) : ptr(l) + '——' + l.reason).join(';'), '')
37
+ if (r.sealed) out.push('- (这件事她封存了:' + r.sealed.day + ')', '')
38
+ return out
39
+ }
40
+
41
+ export function renderBook(dir, { asOf = null, includeSealed = false, title = '她的自传', now = new Date() } = {}) {
42
+ const until = parseAsOf(asOf)
43
+ const rows = loadAll(dir, { asOf })
44
+ const visible = rows.filter((r) => includeSealed || !r.sealed).sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
45
+ const hidden = rows.length - visible.length
46
+ const chapters = chapterEvents.chapters(dir, { until })
47
+
48
+ // 分节:章节会嵌套("那个秋天"里有"拿到钥匙的那周"),每条放进它落入的最具体的那段——开始得最晚的那个;
49
+ // 一件事只印一遍,其余更大的章节在条目里提一句
50
+ const sections = new Map()
51
+ for (const c of chapters) sections.set(c.id, { key: c.from, heading: c.name, sub: range(c) + (c.names.length > 1 ? ',以前叫' + c.names.slice(0, -1).map((n) => '「' + n + '」').join('、') : ''), items: [] })
52
+ const primaryOf = (r) => (r.chapters || [])[(r.chapters || []).length - 1]
53
+ for (const r of visible) {
54
+ const first = primaryOf(r)
55
+ if (first && sections.has(first.id)) { sections.get(first.id).items.push(r); continue }
56
+ const month = String(r.day || '').slice(0, 7) || '没有日期'
57
+ if (!sections.has('m:' + month)) sections.set('m:' + month, { key: month + '-01', heading: month, sub: '没有归进章节的日子', items: [] })
58
+ sections.get('m:' + month).items.push(r)
59
+ }
60
+
61
+ const lines = ['# ' + title, '']
62
+ lines.push('> ' + (until !== null ? '截至 ' + dayOf(until) + ' 的样子,那之后写下的不在这本里。' : '导出于 ' + now.toLocaleString('zh-CN', { hour12: false }) + '。') + '每一条的正文是那天写下的原样,「后来」按时间接在后面。')
63
+ lines.push('>', '> 收了 ' + visible.length + ' 件' + (hidden ? ';有 ' + hidden + ' 件她封存了的事没有收进来' : '') + '。', '')
64
+ if (!visible.length) lines.push('(还没有可以收进来的记录。)', '')
65
+ const ordered = [...sections.values()].filter((s) => s.items.length).sort((a, b) => a.key.localeCompare(b.key))
66
+ for (const s of ordered) {
67
+ lines.push('## ' + s.heading, '', '*' + s.sub + '*', '')
68
+ for (const r of s.items) {
69
+ lines.push(...entry(r))
70
+ const others = (r.chapters || []).slice(0, -1)
71
+ if (others.length) lines.push('- 也在这段日子里:' + others.map((c) => '「' + c.name + '」').join('、'), '')
72
+ }
73
+ }
74
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd() + '\n'
75
+ }
@@ -0,0 +1,39 @@
1
+ export type ChapterAction = 'open' | 'rename' | 'close'
2
+
3
+ export const ACTIONS: Set<ChapterAction>
4
+
5
+ export interface ChapterEvent {
6
+ id: string
7
+ at: string
8
+ day: string
9
+ action: ChapterAction
10
+ name?: string
11
+ from?: string
12
+ to?: string
13
+ note?: string
14
+ }
15
+
16
+ export interface Chapter {
17
+ id: string
18
+ /** 现在(或截至 until)的名字 */
19
+ name: string
20
+ /** 起过的所有名字,按先后;最后一个就是 name */
21
+ names: string[]
22
+ from: string
23
+ /** 空字符串表示"还在这段日子里" */
24
+ to: string
25
+ note: string
26
+ openedAt: string
27
+ }
28
+
29
+ export function eventsFile(memDir: string): string
30
+ export function readAll(memDir: string): { rows: ChapterEvent[]; bad: number }
31
+ export function chapters(memDir: string, opts?: { until?: number | null }): Chapter[]
32
+ /** 这一天落在哪些章节里(章节可以重叠) */
33
+ export function chaptersOn(list: Chapter[], day: string): Chapter[]
34
+ /** from 默认今天;同名同起点重复提交是 noop */
35
+ export function open(memDir: string, opts: { name: string; from?: string; to?: string; note?: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
36
+ export function rename(memDir: string, opts: { id: string; name: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
37
+ /** to 默认今天;再 close 一次可以改结束日期 */
38
+ export function close(memDir: string, opts: { id: string; to?: string }, lockOpts?: Record<string, unknown>): { row: ChapterEvent | null; noop: boolean }
39
+ export const internals: { FILE: string }
@@ -0,0 +1,89 @@
1
+ // 人生章节:她给一段日子起的名字(Conway 自传记忆模型里的"人生时期")
2
+ // 一行一个 { id, at, day, action: open|rename|close, name?, from?, to?, note? },只追加
3
+ // 名字是后来起的、也可以再改:改名不抹掉旧名字,翻回那天看到的是她那时的叫法
4
+ // 经历按 day 落进章节:from ≤ day ≤ to(没写 to 就是"还在这段日子里");章节可以重叠
5
+ import { createLog, stamp } from './event-log.js'
6
+ import { before, parseAsOf } from './as-of.js'
7
+
8
+ export const ACTIONS = new Set(['open', 'rename', 'close'])
9
+ const log = createLog('chapter-events.jsonl', { valid: (r) => Boolean(r.id && ACTIONS.has(r.action)) })
10
+ export const eventsFile = log.eventsFile
11
+ export const readAll = log.readAll
12
+ export const internals = { FILE: log.FILE }
13
+
14
+ const LIMIT_NAME = 30
15
+ const DATE = /^\d{4}-\d{2}-\d{2}$/
16
+
17
+ function checkName(name) {
18
+ const s = String(name || '').trim()
19
+ if (!s) throw new Error('章节要有个名字,比如「在灯塔书店打工的那个月」。')
20
+ if ([...s].length > LIMIT_NAME) throw new Error(`章节名太长(${[...s].length}/${LIMIT_NAME} 字)。`)
21
+ return s
22
+ }
23
+
24
+ function checkDay(v, label) {
25
+ const s = String(v || '').trim()
26
+ if (!DATE.test(s)) throw new Error(`${label} 要写成 2026-11-01 这样的日期。`)
27
+ parseAsOf(s) // 不存在的日期(2026-02-30)在这里报错
28
+ return s
29
+ }
30
+
31
+ // 重放事件,得到每个章节现在(或截至 until)的样子
32
+ export function chapters(memDir, { until = null } = {}) {
33
+ const map = new Map()
34
+ for (const r of readAll(memDir).rows) {
35
+ if (!before(r, until)) continue
36
+ if (r.action === 'open') map.set(r.id, { id: r.id, name: r.name, names: [r.name], from: r.from, to: r.to || '', note: r.note || '', openedAt: r.at })
37
+ const c = map.get(r.id)
38
+ if (!c) continue
39
+ if (r.action === 'rename' && r.name !== c.name) { c.name = r.name; c.names.push(r.name) }
40
+ if (r.action === 'close') c.to = r.to
41
+ }
42
+ return [...map.values()].sort((a, b) => a.from.localeCompare(b.from) || a.openedAt.localeCompare(b.openedAt))
43
+ }
44
+
45
+ export const chaptersOn = (list, day) => list.filter((c) => day >= c.from && (!c.to || day <= c.to))
46
+
47
+ // 开一个章节。同名、同起点的重复提交是 noop
48
+ export function open(memDir, { name, from, to = '', note = '' } = {}, opts = {}) {
49
+ const n = checkName(name)
50
+ const f = checkDay(from || new Date().toLocaleDateString('sv-SE'), 'from')
51
+ const t = to ? checkDay(to, 'to') : ''
52
+ if (t && t < f) throw new Error('结束日期不能早于开始日期。')
53
+ return log.decide(memDir, (rows) => rows.some((r) => r.action === 'open' && r.name === n && r.from === f)
54
+ ? null
55
+ : { id: 'ch_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), ...stamp(), action: 'open', name: n, from: f, to: t, note: String(note || '').slice(0, 200) }, opts)
56
+ }
57
+
58
+ // 在已读出的事件里重放某一个章节(decide 的锁内用,不再重读文件)
59
+ function current(rows, id) {
60
+ let ch = null
61
+ for (const r of rows) {
62
+ if (r.id !== id) continue
63
+ if (r.action === 'open') ch = { name: r.name, from: r.from, to: r.to || '' }
64
+ else if (ch && r.action === 'rename') ch.name = r.name
65
+ else if (ch && r.action === 'close') ch.to = r.to
66
+ }
67
+ return ch
68
+ }
69
+
70
+ // 改名:旧名字留在 names 里
71
+ export function rename(memDir, { id, name } = {}, opts = {}) {
72
+ const n = checkName(name)
73
+ return log.decide(memDir, (rows) => {
74
+ const ch = current(rows, id)
75
+ if (!ch) throw new Error('找不到这个章节:' + id)
76
+ return ch.name === n ? null : { id: String(id), ...stamp(), action: 'rename', name: n }
77
+ }, opts)
78
+ }
79
+
80
+ // 这段日子结束了(再 close 一次可以改结束日期)
81
+ export function close(memDir, { id, to } = {}, opts = {}) {
82
+ const t = checkDay(to || new Date().toLocaleDateString('sv-SE'), 'to')
83
+ return log.decide(memDir, (rows) => {
84
+ const ch = current(rows, id)
85
+ if (!ch) throw new Error('找不到这个章节:' + id)
86
+ if (t < ch.from) throw new Error('结束日期不能早于开始日期(' + ch.from + ')。')
87
+ return ch.to === t ? null : { id: String(id), ...stamp(), action: 'close', to: t }
88
+ }, opts)
89
+ }
@@ -0,0 +1,10 @@
1
+ export interface EventLog<T> {
2
+ FILE: string
3
+ eventsFile(memDir: string): string
4
+ readAll(memDir: string): { rows: T[]; bad: number }
5
+ /** 锁内重读 → judge 决定要不要追加(返回 null 即 noop) */
6
+ decide(memDir: string, judge: (rows: T[]) => T | null, opts?: Record<string, unknown>): { row: T | null; noop: boolean }
7
+ }
8
+
9
+ export function createLog<T = Record<string, unknown>>(fileName: string, opts?: { valid?: (row: T) => boolean }): EventLog<T>
10
+ export function stamp(): { at: string; day: string }
@@ -0,0 +1,61 @@
1
+ // 只追加的事件文件:一行一个 JSON。新加的事件类型共用这一份读写,不再各抄一遍
2
+ // - readAll:坏行跳过、计数,不阻断读取
3
+ // - decide:同一把锁里「重读 → 判断 → 追加」,重复提交只记一次
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { withFileLock } from './file-lock.js'
7
+
8
+ export function createLog(fileName, { valid = (r) => Boolean(r) } = {}) {
9
+ const eventsFile = (memDir) => path.join(memDir, fileName)
10
+
11
+ function readAll(memDir) {
12
+ let raw = ''
13
+ try { raw = fs.readFileSync(eventsFile(memDir), 'utf8') } catch { return { rows: [], bad: 0 } }
14
+ const rows = []
15
+ let bad = 0
16
+ for (const line of raw.split('\n')) {
17
+ if (!line.trim()) continue
18
+ try {
19
+ const r = JSON.parse(line)
20
+ if (r && valid(r)) rows.push(r)
21
+ else bad += 1
22
+ } catch { bad += 1 }
23
+ }
24
+ return { rows, bad }
25
+ }
26
+
27
+ // 调用前必须已经持有锁
28
+ function appendUnlocked(memDir, row) {
29
+ const file = eventsFile(memDir)
30
+ let prefix = ''
31
+ try {
32
+ const st = fs.statSync(file)
33
+ if (st.size) {
34
+ const fd = fs.openSync(file, 'r')
35
+ const buf = Buffer.alloc(1)
36
+ fs.readSync(fd, buf, 0, 1, st.size - 1)
37
+ fs.closeSync(fd)
38
+ if (buf[0] !== 10) prefix = '\n'
39
+ }
40
+ } catch { }
41
+ fs.appendFileSync(file, prefix + JSON.stringify(row) + '\n', 'utf8')
42
+ return row
43
+ }
44
+
45
+ // judge(rows) 返回要追加的那一行,或 null 表示不用写(noop)
46
+ function decide(memDir, judge, opts = {}) {
47
+ fs.mkdirSync(memDir, { recursive: true })
48
+ return withFileLock(eventsFile(memDir) + '.lock', () => {
49
+ const row = judge(readAll(memDir).rows)
50
+ if (!row) return { row: null, noop: true }
51
+ return { row: appendUnlocked(memDir, row), noop: false }
52
+ }, opts)
53
+ }
54
+
55
+ return { FILE: fileName, eventsFile, readAll, decide }
56
+ }
57
+
58
+ export const stamp = () => {
59
+ const now = new Date()
60
+ return { at: now.toISOString(), day: now.toLocaleDateString('sv-SE') }
61
+ }
@@ -1,7 +1,9 @@
1
- import type { Fact, Verdict } from './evidence-policy.js'
2
- import type { Experience } from './self-experience.js'
3
-
4
- export function moodFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
5
- export function quoteFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
6
- export function factsFromExperiences(experiences: Experience[], opts?: { subject?: string }): Fact[]
1
+ import type { Fact, Verdict } from './evidence-policy.js'
2
+ import type { Experience } from './self-experience.js'
3
+
4
+ export function moodFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
5
+ export function quoteFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
6
+ /** 她对每件事的感觉:slot 为 feeling:<经历 id>;后来写了感觉的后记会取代前一条 */
7
+ export function feelingFacts(experiences: Experience[], opts?: { subject?: string }): Fact[]
8
+ export function factsFromExperiences(experiences: Experience[], opts?: { subject?: string }): Fact[]
7
9
  export function ask(experiences: Experience[], opts: { slot: string; at?: string; subject?: string }): Verdict