whale-memory-core 0.14.0 → 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
@@ -11,3 +11,5 @@ export * as recap from './lib/recap.js'
11
11
  export * as linkEvents from './lib/link-events.js'
12
12
  export * as chapterEvents from './lib/chapter-events.js'
13
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
@@ -13,3 +13,5 @@ export * as recap from './lib/recap.js'
13
13
  export * as linkEvents from './lib/link-events.js'
14
14
  export * as chapterEvents from './lib/chapter-events.js'
15
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
+ }
@@ -0,0 +1,28 @@
1
+ export type UnsaidKind = 'draft' | 'question' | 'held'
2
+ export type UnsaidStatus = 'open' | 'spoken' | 'discarded'
3
+
4
+ export const KINDS: Set<UnsaidKind>
5
+ export const LIMITS: { text: number; reason: number }
6
+
7
+ export interface UnsaidItem {
8
+ id: string
9
+ day: string
10
+ kind: UnsaidKind
11
+ text: string
12
+ reason: string
13
+ status: 'open' | 'spoken'
14
+ spokenDay?: string
15
+ }
16
+
17
+ type Fail = { ok: false; error: string }
18
+
19
+ /** 只在认得出的一对一会话里可用;同 kind 同原文还开着时重复提交是 noop */
20
+ export function leaveUnsaid(dir: string, opts: { chatKey: string; kind?: UnsaidKind; text: string; reason?: string }): { ok: true; id: string; day?: string; noop: boolean } | Fail
21
+ /** 默认只给开着的;all=true 连说出口的也给。丢掉的从不给 */
22
+ export function listUnsaid(dir: string, opts: { chatKey: string; all?: boolean }): { ok: true; items: UnsaidItem[] } | Fail
23
+ export function markUnsaidSpoken(dir: string, opts: { chatKey: string; id: string }): { ok: true; id: string; status: 'spoken'; noop: boolean } | Fail
24
+ export function discardUnsaid(dir: string, opts: { chatKey: string; id: string }): { ok: true; id: string; status: 'discarded'; noop: boolean } | Fail
25
+ /** 坏行数,只给数字 */
26
+ export function badLines(dir: string): number
27
+ export function eventsFile(dir: string): string
28
+ export const internals: { FILE: string }
package/lib/unsaid.js ADDED
@@ -0,0 +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')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "whale-memory-core",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Self-layer autobiographical memory core: then / later, append-only. Vault, evidence and consolidation live in the QQ Agent plugin.",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -73,6 +73,14 @@
73
73
  "./book": {
74
74
  "types": "./lib/book.d.ts",
75
75
  "default": "./lib/book.js"
76
+ },
77
+ "./unsaid": {
78
+ "types": "./lib/unsaid.d.ts",
79
+ "default": "./lib/unsaid.js"
80
+ },
81
+ "./archive": {
82
+ "types": "./lib/archive.d.ts",
83
+ "default": "./lib/archive.js"
76
84
  }
77
85
  },
78
86
  "files": [