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.
- package/README.md +14 -0
- package/bin/whale-memory-mcp.mjs +276 -0
- package/demo.mjs +44 -33
- package/index.d.ts +16 -13
- package/index.js +18 -15
- package/lib/archive.d.ts +22 -0
- package/lib/archive.js +171 -0
- package/lib/as-of.d.ts +5 -5
- package/lib/as-of.js +32 -32
- package/lib/book.d.ts +4 -4
- package/lib/book.js +75 -75
- package/lib/chapter-events.d.ts +39 -39
- package/lib/chapter-events.js +89 -89
- package/lib/detail-recall.d.ts +15 -0
- package/lib/detail-recall.js +174 -0
- package/lib/event-log.d.ts +10 -10
- package/lib/event-log.js +61 -61
- package/lib/evidence-from-experience.d.ts +8 -8
- package/lib/evidence-from-experience.js +62 -62
- package/lib/evidence-policy.js +2 -2
- package/lib/fact-timeline-contract.d.ts +73 -0
- package/lib/fact-timeline-contract.js +226 -0
- package/lib/fact-timeline-query.d.ts +29 -0
- package/lib/fact-timeline-query.js +97 -0
- package/lib/file-lock.js +1 -1
- package/lib/later-events.d.ts +21 -21
- package/lib/later-events.js +80 -80
- package/lib/link-events.d.ts +15 -15
- package/lib/link-events.js +33 -33
- package/lib/query-match.js +55 -0
- package/lib/recall-events.d.ts +24 -24
- package/lib/recall-events.js +97 -97
- package/lib/recap.d.ts +23 -23
- package/lib/recap.js +79 -79
- package/lib/seal-events.d.ts +25 -25
- package/lib/seal-events.js +82 -82
- package/lib/self-experience.d.ts +180 -175
- package/lib/self-experience.js +624 -560
- package/lib/self-memory.js +70 -68
- package/lib/self-prompt.js +8 -4
- package/lib/self-settings.js +2 -2
- package/lib/unfinished-events.d.ts +26 -26
- package/lib/unfinished-events.js +105 -105
- package/lib/unsaid.d.ts +28 -0
- package/lib/unsaid.js +105 -0
- package/lib/waking.d.ts +1 -1
- package/lib/waking.js +99 -92
- package/package.json +127 -105
package/lib/archive.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
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 relative = path.relative(physicalPath(b), physicalPath(a))
|
|
38
|
+
return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Resolve existing parents too, so junctions and differently cased Windows paths
|
|
42
|
+
// cannot disguise overlapping source and destination directories.
|
|
43
|
+
function physicalPath(file) {
|
|
44
|
+
const abs = path.resolve(file)
|
|
45
|
+
try { return fs.realpathSync(abs) } catch (error) {
|
|
46
|
+
if (error.code !== 'ENOENT') throw error
|
|
47
|
+
const parent = path.dirname(abs)
|
|
48
|
+
if (parent === abs) throw error
|
|
49
|
+
return path.join(physicalPath(parent), path.basename(abs))
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 导出包里的相对路径:正反斜杠、绝对路径、盘符相对路径、任何 '..' 段都拒绝,
|
|
54
|
+
// 再用解析后的绝对路径确认确实落在 root 里面(不靠枚举写法)
|
|
55
|
+
export function safeJoin(root, name) {
|
|
56
|
+
const n = String(name || '')
|
|
57
|
+
if (!n || n.includes('\0')) throw new Error('Suspicious path in export: ' + JSON.stringify(name) + '(导出里有可疑路径:' + JSON.stringify(name) + ')')
|
|
58
|
+
if (path.isAbsolute(n) || path.win32.isAbsolute(n) || /^[a-zA-Z]:/.test(n)) throw new Error('Absolute path in export: ' + n + '(导出里有绝对路径:' + n + ')')
|
|
59
|
+
if (n.split(/[\\/]+/).includes('..')) throw new Error('Path in export escapes the export directory: ' + n + '(导出里有越界路径:' + n + ')')
|
|
60
|
+
const rootAbs = path.resolve(root)
|
|
61
|
+
const abs = path.resolve(rootAbs, n)
|
|
62
|
+
if (abs !== rootAbs && !abs.startsWith(rootAbs + path.sep)) throw new Error('Path in export escapes the export directory: ' + n + '(导出里有越界路径:' + n + ')')
|
|
63
|
+
return abs
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 打包:outDir 下新建 <name>/(默认 memory-export-<时间>),不能和记忆目录互相包含
|
|
67
|
+
export function exportArchive(memDir, outDir, { name = '' } = {}) {
|
|
68
|
+
if (!fs.existsSync(memDir)) throw new Error('Memory directory not found: ' + memDir + '(没有找到记忆目录:' + memDir + ')')
|
|
69
|
+
const target = path.resolve(outDir, name || 'memory-export-' + stamp())
|
|
70
|
+
if (inside(target, memDir) || inside(memDir, target)) throw new Error('Export directory and memory directory must not be inside each other: ' + target + '(导出目录不能和记忆目录互相包含:' + target + ')')
|
|
71
|
+
if (fs.existsSync(target)) throw new Error('Export directory already exists: ' + target + '(导出目录已存在:' + target + ')')
|
|
72
|
+
|
|
73
|
+
const files = collectFiles(memDir)
|
|
74
|
+
fs.mkdirSync(target, { recursive: true })
|
|
75
|
+
const manifestFiles = []
|
|
76
|
+
let bytes = 0
|
|
77
|
+
for (const f of files) {
|
|
78
|
+
const content = fs.readFileSync(f.abs)
|
|
79
|
+
const dest = path.join(target, f.name)
|
|
80
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
81
|
+
fs.writeFileSync(dest, content)
|
|
82
|
+
manifestFiles.push({ name: f.name, bytes: content.length, sha256: sha256(content) })
|
|
83
|
+
bytes += content.length
|
|
84
|
+
}
|
|
85
|
+
const manifest = {
|
|
86
|
+
format: FORMAT,
|
|
87
|
+
version: 1,
|
|
88
|
+
exportedAt: new Date().toISOString(),
|
|
89
|
+
files: manifestFiles,
|
|
90
|
+
counts: {
|
|
91
|
+
experiences: loadAll(memDir).length,
|
|
92
|
+
diaries: countLines(path.join(memDir, 'autobiography.jsonl')),
|
|
93
|
+
laterEvents: countLines(path.join(memDir, 'later-events.jsonl')),
|
|
94
|
+
recallEvents: countLines(path.join(memDir, 'recall-events.jsonl')),
|
|
95
|
+
unfinishedEvents: countLines(path.join(memDir, 'unfinished-events.jsonl')),
|
|
96
|
+
sealEvents: countLines(path.join(memDir, 'seal-events.jsonl')),
|
|
97
|
+
linkEvents: countLines(path.join(memDir, 'link-events.jsonl')),
|
|
98
|
+
chapterEvents: countLines(path.join(memDir, 'chapter-events.jsonl')),
|
|
99
|
+
unsaidEvents: countLines(path.join(memDir, 'unsaid-events.jsonl'))
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
fs.writeFileSync(path.join(target, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8')
|
|
103
|
+
return { ok: true, dir: target, files: manifestFiles.length, bytes, counts: manifest.counts }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 校验导出包:manifest 读得出、格式对、每个文件都在且 SHA-256 一致;不对就抛错,说清是哪一个
|
|
107
|
+
export function verifyArchive(fromDir) {
|
|
108
|
+
const src = path.resolve(fromDir)
|
|
109
|
+
const manifestFile = path.join(src, 'manifest.json')
|
|
110
|
+
if (!fs.existsSync(manifestFile)) throw new Error('Not a whale-memory export directory (manifest.json is missing): ' + src + '(不是 whale-memory 导出目录(缺 manifest.json):' + src + ')')
|
|
111
|
+
let manifest
|
|
112
|
+
try { manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8')) } catch {
|
|
113
|
+
throw new Error('Cannot read manifest.json: ' + manifestFile + '(manifest.json 读不出来:' + manifestFile + ')')
|
|
114
|
+
}
|
|
115
|
+
if (!manifest || manifest.format !== FORMAT || !Array.isArray(manifest.files)) {
|
|
116
|
+
throw new Error('manifest.json is malformed: ' + manifestFile + '(manifest.json 格式不对:' + manifestFile + ')')
|
|
117
|
+
}
|
|
118
|
+
for (const f of manifest.files) {
|
|
119
|
+
const n = String(f.name || '')
|
|
120
|
+
const abs = safeJoin(src, n)
|
|
121
|
+
if (!fs.existsSync(abs)) throw new Error('File missing from export: ' + n + '(导出缺少文件:' + n + ')')
|
|
122
|
+
if (!inside(abs, src)) throw new Error('File link escapes export directory: ' + n + '(文件链接越出导出目录)')
|
|
123
|
+
const buf = fs.readFileSync(abs)
|
|
124
|
+
if (sha256(buf) !== f.sha256) throw new Error('Checksum mismatch: ' + n + '(文件校验不通过:' + n + ')')
|
|
125
|
+
if (buf.length !== f.bytes) throw new Error('File size mismatch: ' + n + '(文件大小校验不通过)')
|
|
126
|
+
}
|
|
127
|
+
return manifest
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// 恢复:先整包校验;目标已有数据时默认拒绝,force 会先把现有目录改名备份
|
|
131
|
+
export function importArchive(fromDir, memDir, { force = false } = {}) {
|
|
132
|
+
const src = path.resolve(fromDir)
|
|
133
|
+
if (inside(src, memDir) || inside(memDir, src)) throw new Error('Import source and target directories must not overlap(导入源与目标目录不能互相包含)')
|
|
134
|
+
const manifest = verifyArchive(src)
|
|
135
|
+
const exists = fs.existsSync(memDir) && fs.readdirSync(memDir).length > 0
|
|
136
|
+
if (exists && !force) throw new Error('Target already has data: ' + memDir + '. To overwrite, add --force true (the existing data is backed up first).(目标已有数据:' + memDir + '。确认覆盖请加 --force true(会先备份))')
|
|
137
|
+
const target = path.resolve(memDir)
|
|
138
|
+
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
139
|
+
const stage = fs.mkdtempSync(target + '.import-stage-')
|
|
140
|
+
let backup = ''
|
|
141
|
+
let moved = false
|
|
142
|
+
try {
|
|
143
|
+
for (const f of manifest.files) {
|
|
144
|
+
const source = safeJoin(src, f.name)
|
|
145
|
+
if (!inside(source, src)) throw new Error('File link escapes export directory: ' + f.name)
|
|
146
|
+
const dest = safeJoin(stage, f.name)
|
|
147
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
|
148
|
+
fs.copyFileSync(source, dest)
|
|
149
|
+
const copied = fs.readFileSync(dest)
|
|
150
|
+
if (copied.length !== f.bytes || sha256(copied) !== f.sha256) {
|
|
151
|
+
throw new Error('Export changed during import: ' + f.name + '(导入期间备份内容发生变化)')
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const loaded = loadAll(stage)
|
|
155
|
+
if (exists && force) {
|
|
156
|
+
backup = target + '.pre-import-' + stamp() + '-' + crypto.randomUUID()
|
|
157
|
+
fs.renameSync(target, backup)
|
|
158
|
+
moved = true
|
|
159
|
+
} else if (fs.existsSync(target)) {
|
|
160
|
+
// rmdir only accepts an empty directory; concurrent new data is preserved.
|
|
161
|
+
fs.rmdirSync(target)
|
|
162
|
+
}
|
|
163
|
+
try { fs.renameSync(stage, target) } catch (error) {
|
|
164
|
+
if (moved) fs.renameSync(backup, target)
|
|
165
|
+
throw error
|
|
166
|
+
}
|
|
167
|
+
return { ok: true, files: manifest.files.length, restoreTo: memDir, backup, counts: { experiences: loaded.length } }
|
|
168
|
+
} finally {
|
|
169
|
+
fs.rmSync(stage, { recursive: true, force: true })
|
|
170
|
+
}
|
|
171
|
+
}
|
package/lib/as-of.d.ts
CHANGED
|
@@ -1,5 +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
|
|
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
CHANGED
|
@@ -1,32 +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')
|
|
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('Invalid as-of time.(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 date does not exist: ' + s + '(as-of 日期不存在:' + s + ')')
|
|
18
|
+
return end.getTime()
|
|
19
|
+
}
|
|
20
|
+
const t = Date.parse(s)
|
|
21
|
+
if (!Number.isFinite(t)) throw new Error('Cannot parse as-of time: ' + s + ' (use a date like 2026-11-15, or a full ISO time).(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
CHANGED
|
@@ -1,4 +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
|
|
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
CHANGED
|
@@ -1,75 +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('-
|
|
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
|
-
}
|
|
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.afterAsOf ? '后来' : '') + '封存了:' + 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
|
+
}
|
package/lib/chapter-events.d.ts
CHANGED
|
@@ -1,39 +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 }
|
|
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 }
|