whale-memory-core 0.20.0 → 0.21.1
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 +3 -3
- package/bin/whale-memory-mcp.mjs +29 -5
- package/index.d.ts +7 -0
- package/index.js +2 -0
- package/lib/archive.d.ts +19 -0
- package/lib/archive.js +267 -14
- package/lib/book.js +34 -3
- package/lib/changed.d.ts +4 -0
- package/lib/changed.js +76 -0
- package/lib/conversation-privacy.js +43 -15
- package/lib/fact-store.js +56 -15
- package/lib/file-lock.d.ts +4 -1
- package/lib/file-lock.js +151 -13
- package/lib/injection.d.ts +5 -0
- package/lib/injection.js +82 -0
- package/lib/query-match.js +67 -18
- package/lib/scope-key.d.ts +4 -0
- package/lib/scope-key.js +34 -0
- package/lib/seal-events.d.ts +2 -2
- package/lib/seal-events.js +26 -5
- package/lib/self-experience.d.ts +4 -1
- package/lib/self-experience.js +138 -52
- package/lib/self-prompt.js +22 -5
- package/lib/unfinished-events.d.ts +2 -0
- package/lib/waking.js +6 -3
- package/package.json +9 -1
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ import * as exp from 'whale-memory-core/self-experience'
|
|
|
19
19
|
- vault 存储与索引、evidence-policy 取证、consolidator 合并、注入预算
|
|
20
20
|
- 跨会话可见性判断、宿主工具注册
|
|
21
21
|
|
|
22
|
-
如果你要的是"一个 agent 的自传记忆",这个包够用;如果你要的是"完整记忆系统",看 [`docs/architecture.md`](../../docs/architecture.md) 与 [`docs/porting.md`](../../docs/porting.md)。
|
|
22
|
+
如果你要的是"一个 agent 的自传记忆",这个包够用;如果你要的是"完整记忆系统",看 [`docs/architecture.md`](../../docs/archive/architecture.md) 与 [`docs/porting.md`](../../docs/archive/porting.md)。
|
|
23
23
|
|
|
24
24
|
包名 `whale-memory-core`,入口:`whale-memory-core`(命名导出)以及五个子路径:`/self-experience`、`/self-memory`、`/waking`、`/self-prompt`、`/self-settings`。
|
|
25
25
|
|
|
@@ -74,9 +74,9 @@ node demo.mjs
|
|
|
74
74
|
|
|
75
75
|
## 数据
|
|
76
76
|
|
|
77
|
-
一条经历一行 JSON,格式见 [`docs/schema.md`](../../docs/schema.md)。三条虚构样本在 [`examples/samples/`](../../examples/samples/)。
|
|
77
|
+
一条经历一行 JSON,格式见 [`docs/schema.md`](../../docs/archive/schema.md)。三条虚构样本在 [`examples/samples/`](../../examples/samples/)。
|
|
78
78
|
|
|
79
|
-
移植说明见仓库根目录 [`docs/porting.md`](../../docs/porting.md)。
|
|
79
|
+
移植说明见仓库根目录 [`docs/porting.md`](../../docs/archive/porting.md)。
|
|
80
80
|
| 模块 | 作用 |
|
|
81
81
|
|---|---|
|
|
82
82
|
| `self-experience.js` | 经历两层(then / later)、重要度、两段式回想 |
|
package/bin/whale-memory-mcp.mjs
CHANGED
|
@@ -33,9 +33,22 @@ const OWNER_KEY = 'local:owner'
|
|
|
33
33
|
|
|
34
34
|
export function parseArgs(argv) {
|
|
35
35
|
const get = (k) => { const i = argv.indexOf('--' + k); if (i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--')) return argv[i + 1]; const eq = argv.find((a) => a.startsWith('--' + k + '=')); return eq ? eq.slice(k.length + 3) : '' }
|
|
36
|
+
const given = (k) => argv.includes('--' + k) || argv.some((a) => a.startsWith('--' + k + '='))
|
|
37
|
+
// 布尔开关必须写清 true / false。裸写 --readonly 以前会被当成「没开」,等于把写工具静默放开;
|
|
38
|
+
// 现在直接报错,并把正确写法说出来。
|
|
39
|
+
const bool = (k) => {
|
|
40
|
+
const raw = get(k)
|
|
41
|
+
if (!raw) {
|
|
42
|
+
if (!given(k)) return false
|
|
43
|
+
throw new Error('--' + k + ' needs an explicit value: write --' + k + ' true or --' + k + ' false(--' + k + ' 要写清楚:写成 --' + k + ' true 或 --' + k + ' false)')
|
|
44
|
+
}
|
|
45
|
+
if (raw === 'true') return true
|
|
46
|
+
if (raw === 'false') return false
|
|
47
|
+
throw new Error('--' + k + ' only accepts true or false, got: ' + raw + '(--' + k + ' 只接受 true 或 false)')
|
|
48
|
+
}
|
|
36
49
|
const data = path.resolve(get('data') || process.env.WHALE_DATA_DIR || path.join(process.cwd(), 'data'))
|
|
37
50
|
const lang = (get('lang') || process.env.WHALE_LANG || (/^zh/i.test(String(process.env.LC_ALL || process.env.LANG || Intl.DateTimeFormat().resolvedOptions().locale || '')) ? 'zh' : 'en')) === 'zh' ? 'zh' : 'en'
|
|
38
|
-
return { data, mem: path.join(data, 'plugin-data', 'biomimetic-memory'), owner:
|
|
51
|
+
return { data, mem: path.join(data, 'plugin-data', 'biomimetic-memory'), owner: bool('owner'), readonly: bool('readonly'), lang }
|
|
39
52
|
}
|
|
40
53
|
|
|
41
54
|
// ── 工具 ────────────────────────────────────────────────────────────────
|
|
@@ -81,7 +94,10 @@ export function buildTools(cfg) {
|
|
|
81
94
|
const asOf = a.asOf || null
|
|
82
95
|
const only = String(a.id || '')
|
|
83
96
|
const all = exp.loadAll(M, { asOf })
|
|
84
|
-
|
|
97
|
+
// 翻回那天:那时还没封存、后来才封存的(afterAsOf)在当时是看得见的,照常列出并带封存标记;
|
|
98
|
+
// 只有「那一天就已经封存着的」才算藏起来,sealedHidden 也只数这些。
|
|
99
|
+
const sealedThen = (r) => Boolean(r.sealed) && !(asOf && r.sealed.afterAsOf)
|
|
100
|
+
const picked = only ? all.filter((r) => r.id === only || r.formerId === only) : all.filter((r) => !sealedThen(r))
|
|
85
101
|
const n = limitOf(a.limit, 8)
|
|
86
102
|
const rows = n === 0 ? [] : picked.slice(-n)
|
|
87
103
|
const res = {
|
|
@@ -94,7 +110,7 @@ export function buildTools(cfg) {
|
|
|
94
110
|
...(r.sealed ? { sealed: r.sealed } : {}), ...(only ? { view: exp.renderTwoPart(r, { lang: cfg.lang }) } : {})
|
|
95
111
|
}))
|
|
96
112
|
}
|
|
97
|
-
if (!only) { const hidden = all.filter(
|
|
113
|
+
if (!only) { const hidden = all.filter(sealedThen).length; if (hidden) res.sealedHidden = hidden }
|
|
98
114
|
if (only && !rows.length) res.note = asOf ? '截至 ' + asOf + ' 还没有这条经历。' : '找不到这条经历:' + only
|
|
99
115
|
return res
|
|
100
116
|
}
|
|
@@ -212,7 +228,8 @@ const INSTRUCTIONS = [
|
|
|
212
228
|
'This is the autobiographical memory of an AI character, kept by herself. Three rules:(这是一个 AI 角色自己的自传体记忆。三条规矩:)',
|
|
213
229
|
'1. What was written then is never changed; if a view changes, append with memory_revise.(1. 当时写下的永远不改;想法变了用 memory_revise 追加。)',
|
|
214
230
|
'2. An empty result means this search found nothing; do not make anything up. For a specific detail use memory_detail; distinguish related events from support for an answer.(2. 查空只说明这次没找到,不要编。核对细节时用 memory_detail,按原文能支持的范围回答。)',
|
|
215
|
-
'3. Do not bring up what she has sealed; only she opens the unsaid drawer.(3. 她封存了的事不要主动提起;没说出口的抽屉只有她自己打开。)'
|
|
231
|
+
'3. Do not bring up what she has sealed; only she opens the unsaid drawer.(3. 她封存了的事不要主动提起;没说出口的抽屉只有她自己打开。)',
|
|
232
|
+
'4. If the user states something as fact, an empty recall is not a prompt to agree: say there is no record and let her correct it, rather than completing their premise or inventing a detail.(4. 对方把某件事当成事实说出来时,召回为空不是你同意的理由:说没有记录,让对方向上纠正,而不是顺着他的前提补细节。)'
|
|
216
233
|
].join('\n')
|
|
217
234
|
|
|
218
235
|
export function createServer(cfg) {
|
|
@@ -270,7 +287,14 @@ export function serve(cfg, input = process.stdin, output = process.stdout) {
|
|
|
270
287
|
|
|
271
288
|
const isMain = process.argv[1] && fs.realpathSync(path.resolve(process.argv[1])) === fs.realpathSync(fileURLToPath(import.meta.url))
|
|
272
289
|
if (isMain) {
|
|
273
|
-
|
|
290
|
+
let cfg
|
|
291
|
+
try {
|
|
292
|
+
cfg = parseArgs(process.argv.slice(2))
|
|
293
|
+
} catch (e) {
|
|
294
|
+
// 参数不对就别启动:宁可什么都不给,也不能拿错档位悄悄跑起来
|
|
295
|
+
process.stderr.write('whale-memory-mcp: ' + String(e && e.message ? e.message : e) + '\n')
|
|
296
|
+
process.exit(2)
|
|
297
|
+
}
|
|
274
298
|
process.stderr.write('whale-memory-mcp ' + VERSION + ':数据 ' + cfg.data + (cfg.owner ? ',抽屉已打开' : '') + (cfg.readonly ? ',只读' : '') + '\n')
|
|
275
299
|
serve(cfg)
|
|
276
300
|
}
|
package/index.d.ts
CHANGED
|
@@ -17,3 +17,10 @@ export * as archive from './lib/archive.js'
|
|
|
17
17
|
export * as timeSense from './lib/time-sense.js'
|
|
18
18
|
export * as relativeWindow from './lib/relative-window.js'
|
|
19
19
|
export * as personCard from './lib/person-card.js'
|
|
20
|
+
export * as scopeKey from './lib/scope-key.js'
|
|
21
|
+
export * as conversationPrivacy from './lib/conversation-privacy.js'
|
|
22
|
+
export * as factCard from './lib/fact-card.js'
|
|
23
|
+
export * as factStore from './lib/fact-store.js'
|
|
24
|
+
export * as factJudge from './lib/fact-judge.js'
|
|
25
|
+
export * as changed from './lib/changed.js'
|
|
26
|
+
export * as injection from './lib/injection.js'
|
package/index.js
CHANGED
|
@@ -24,3 +24,5 @@ export * as conversationPrivacy from './lib/conversation-privacy.js'
|
|
|
24
24
|
export * as factCard from './lib/fact-card.js'
|
|
25
25
|
export * as factStore from './lib/fact-store.js'
|
|
26
26
|
export * as factJudge from './lib/fact-judge.js'
|
|
27
|
+
export * as changed from './lib/changed.js'
|
|
28
|
+
export * as injection from './lib/injection.js'
|
package/lib/archive.d.ts
CHANGED
|
@@ -20,3 +20,22 @@ export function exportArchive(memDir: string, outDir: string, opts?: { name?: st
|
|
|
20
20
|
export function verifyArchive(fromDir: string): ArchiveManifest
|
|
21
21
|
/** 先校验并暂存完整副本,再替换;force 保留旧目录备份,替换报错时尝试还原。源与目标不得互相包含。 */
|
|
22
22
|
export function importArchive(fromDir: string, memDir: string, opts?: { force?: boolean }): { ok: true; files: number; restoreTo: string; backup: string; counts: { experiences: number } }
|
|
23
|
+
|
|
24
|
+
/** 导入日志的路径:和目标目录同级,名字带 .import-journal.json */
|
|
25
|
+
export function importJournalPath(memDir: string): string
|
|
26
|
+
|
|
27
|
+
export interface ImportRecovery {
|
|
28
|
+
/** 这一次真的把数据恢复回来了(in-progress / 待人工处理时为 false) */
|
|
29
|
+
recovered: boolean
|
|
30
|
+
/** 走到哪一步:no-journal / restored-backup / installed-stage / kept-target / restore-failed … */
|
|
31
|
+
action: string
|
|
32
|
+
target: string
|
|
33
|
+
journal: string
|
|
34
|
+
backup: string
|
|
35
|
+
/** restore-failed 时说明卡在哪 */
|
|
36
|
+
error?: string
|
|
37
|
+
stage?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 恢复被打断的导入(断电/崩溃后调用):能自动恢复就恢复,不能就保留日志和产物等人工处理 */
|
|
41
|
+
export function recoverImport(memDir: string): ImportRecovery
|
package/lib/archive.js
CHANGED
|
@@ -3,13 +3,202 @@
|
|
|
3
3
|
// 导入前先校验全部文件,坏一个就一个字节都不写;路径越界(正反斜杠、绝对路径、盘符、..)一律拒绝
|
|
4
4
|
import fs from 'node:fs'
|
|
5
5
|
import path from 'node:path'
|
|
6
|
+
import os from 'node:os'
|
|
6
7
|
import crypto from 'node:crypto'
|
|
7
8
|
import { loadAll } from './self-experience.js'
|
|
9
|
+
import { writeFileAtomic } from './file-lock.js'
|
|
8
10
|
|
|
9
11
|
export const FORMAT = 'whale-memory-export'
|
|
10
12
|
export const sha256 = (buf) => crypto.createHash('sha256').update(buf).digest('hex')
|
|
11
13
|
export const stamp = () => new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
|
|
12
14
|
|
|
15
|
+
// 导入日志:rename(旧目录→备份) 与 rename(暂存→新目录) 之间没有事务,进程被强杀/断电时
|
|
16
|
+
// target 会短暂不存在。动手改目录之前先把「target / backup / stage 各在哪」写到 target 旁边的
|
|
17
|
+
// <memDir>.import-journal.json(原子写 + fsync),下次 import/export 进来先按它恢复。
|
|
18
|
+
const IMPORT_JOURNAL_FORMAT = 'whale-memory-import-journal'
|
|
19
|
+
const IMPORT_JOURNAL_VERSION = 1
|
|
20
|
+
|
|
21
|
+
export function importJournalPath(memDir) {
|
|
22
|
+
return path.resolve(String(memDir || '')) + '.import-journal.json'
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readImportJournal(target) {
|
|
26
|
+
let row
|
|
27
|
+
try { row = JSON.parse(fs.readFileSync(importJournalPath(target), 'utf8')) } catch { return null }
|
|
28
|
+
if (!row || row.format !== IMPORT_JOURNAL_FORMAT) return null
|
|
29
|
+
if (row.target && path.resolve(String(row.target)) !== target) return null
|
|
30
|
+
return row
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function writeImportJournal(target, details) {
|
|
34
|
+
const journal = {
|
|
35
|
+
format: IMPORT_JOURNAL_FORMAT,
|
|
36
|
+
version: IMPORT_JOURNAL_VERSION,
|
|
37
|
+
target,
|
|
38
|
+
...details,
|
|
39
|
+
pid: process.pid,
|
|
40
|
+
hostname: os.hostname(),
|
|
41
|
+
updatedAt: new Date().toISOString()
|
|
42
|
+
}
|
|
43
|
+
writeFileAtomic(importJournalPath(target), JSON.stringify(journal, null, 2) + '\n')
|
|
44
|
+
fsyncDir(path.dirname(target))
|
|
45
|
+
return journal
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 日志的主人还活着:说明另一个进程正在导入(日志只在真正搬运目录前写,窗口很短),
|
|
49
|
+
// 这时候绝不能把它的备份/暂存当成断电残留清掉。
|
|
50
|
+
function journalOwnerAlive(journal) {
|
|
51
|
+
const pid = Number(journal?.pid)
|
|
52
|
+
const hostname = typeof journal?.hostname === 'string' ? journal.hostname : ''
|
|
53
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
54
|
+
if (pid === process.pid) return false // 当前进程没有正在进行的 import,日志应是残留
|
|
55
|
+
if (hostname && hostname !== os.hostname()) return false // 跨机无法校验 pid,按残留处理
|
|
56
|
+
try {
|
|
57
|
+
process.kill(pid, 0)
|
|
58
|
+
return true
|
|
59
|
+
} catch (error) {
|
|
60
|
+
return error.code === 'EPERM'
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function removeImportJournal(target) {
|
|
65
|
+
try { fs.rmSync(importJournalPath(target), { force: true }) } catch { }
|
|
66
|
+
fsyncDir(path.dirname(target))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 目录项落盘(POSIX 上才有意义;Windows 打开目录会失败,静默跳过)
|
|
70
|
+
function fsyncDir(dir) {
|
|
71
|
+
try {
|
|
72
|
+
const fd = fs.openSync(dir, 'r')
|
|
73
|
+
try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
|
74
|
+
} catch { }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 只认 target 旁边、名字符合导入产物的兄弟目录,避免被篡改的日志指向任意路径
|
|
78
|
+
function siblingArtifact(target, candidate, prefix) {
|
|
79
|
+
if (typeof candidate !== 'string' || !candidate) return ''
|
|
80
|
+
const resolved = path.resolve(candidate)
|
|
81
|
+
if (path.dirname(resolved) !== path.dirname(target)) return ''
|
|
82
|
+
if (!path.basename(resolved).startsWith(path.basename(target) + prefix)) return ''
|
|
83
|
+
return resolved
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function scanInterruptedSiblings(target) {
|
|
87
|
+
const parent = path.dirname(target)
|
|
88
|
+
const base = path.basename(target)
|
|
89
|
+
let entries
|
|
90
|
+
try { entries = fs.readdirSync(parent, { withFileTypes: true }) } catch { return { backups: [], stages: [] } }
|
|
91
|
+
const pick = (suffix) => entries
|
|
92
|
+
.filter((e) => e.isDirectory() && e.name.startsWith(base + suffix))
|
|
93
|
+
.map((e) => path.join(parent, e.name))
|
|
94
|
+
.sort()
|
|
95
|
+
return { backups: pick('.pre-import-'), stages: pick('.import-stage-') }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function recoverResult(target, action, extra = {}) {
|
|
99
|
+
return {
|
|
100
|
+
recovered: false,
|
|
101
|
+
action,
|
|
102
|
+
target,
|
|
103
|
+
journal: importJournalPath(target),
|
|
104
|
+
backup: '',
|
|
105
|
+
...extra
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 恢复被打断的导入。返回 { recovered, action, target, journal, backup }。
|
|
111
|
+
* - 正常:no-journal / cleaned-journal,什么也不动。
|
|
112
|
+
* - target 不见了、备份还在:把备份改回 target(回滚到导入前,数据不丢)。
|
|
113
|
+
* - target 不见了、只有完整暂存目录:把暂存目录装回 target(空目录导入时)。
|
|
114
|
+
* - 装好新目录但日志没来得及删:保留新目录与备份,只清日志。
|
|
115
|
+
* 自动恢复失败时保留日志与产物(这就是“可恢复标识”),action 会指出卡在哪一步。
|
|
116
|
+
*/
|
|
117
|
+
export function recoverImport(memDir) {
|
|
118
|
+
const target = path.resolve(String(memDir || ''))
|
|
119
|
+
const journalFile = importJournalPath(target)
|
|
120
|
+
const journalExists = fs.existsSync(journalFile)
|
|
121
|
+
const journal = readImportJournal(target)
|
|
122
|
+
const targetExists = fs.existsSync(target)
|
|
123
|
+
|
|
124
|
+
if (!journal) {
|
|
125
|
+
if (targetExists) {
|
|
126
|
+
return recoverResult(target, journalExists ? 'journal-unreadable-target-intact' : 'no-journal')
|
|
127
|
+
}
|
|
128
|
+
// 日志丢了(老版本崩溃/被手工删掉)时按老命名兜底:备份与暂存同时存在才动手
|
|
129
|
+
const siblings = scanInterruptedSiblings(target)
|
|
130
|
+
if (siblings.backups.length && siblings.stages.length) {
|
|
131
|
+
const backup = siblings.backups[siblings.backups.length - 1]
|
|
132
|
+
try { fs.renameSync(backup, target) } catch (error) {
|
|
133
|
+
return recoverResult(target, 'restore-failed', { backup, error: String(error?.message || error) })
|
|
134
|
+
}
|
|
135
|
+
for (const stage of siblings.stages) {
|
|
136
|
+
try { fs.rmSync(stage, { recursive: true, force: true }) } catch { }
|
|
137
|
+
}
|
|
138
|
+
try { fs.rmSync(journalFile, { force: true }) } catch { }
|
|
139
|
+
fsyncDir(path.dirname(target))
|
|
140
|
+
return recoverResult(target, 'restored-backup-fallback', { recovered: true, backup })
|
|
141
|
+
}
|
|
142
|
+
return recoverResult(target, journalExists ? 'missing-target-and-artifacts' : 'no-journal')
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const backup = siblingArtifact(target, journal.backup, '.pre-import-')
|
|
146
|
+
const stage = siblingArtifact(target, journal.stage, '.import-stage-')
|
|
147
|
+
if (journalOwnerAlive(journal)) return recoverResult(target, 'in-progress')
|
|
148
|
+
const backupExists = Boolean(backup) && fs.existsSync(backup)
|
|
149
|
+
const stageExists = Boolean(stage) && fs.existsSync(stage)
|
|
150
|
+
|
|
151
|
+
if (!targetExists) {
|
|
152
|
+
if (backupExists) {
|
|
153
|
+
try { fs.renameSync(backup, target) } catch (error) {
|
|
154
|
+
return recoverResult(target, 'restore-failed', { backup, error: String(error?.message || error) })
|
|
155
|
+
}
|
|
156
|
+
if (stageExists) {
|
|
157
|
+
try { fs.rmSync(stage, { recursive: true, force: true }) } catch { }
|
|
158
|
+
}
|
|
159
|
+
try { fs.rmSync(journalFile, { force: true }) } catch { }
|
|
160
|
+
fsyncDir(path.dirname(target))
|
|
161
|
+
return recoverResult(target, 'restored-backup', { recovered: true, backup })
|
|
162
|
+
}
|
|
163
|
+
if (stageExists) {
|
|
164
|
+
try { fs.renameSync(stage, target) } catch (error) {
|
|
165
|
+
return recoverResult(target, 'restore-failed', { stage, error: String(error?.message || error) })
|
|
166
|
+
}
|
|
167
|
+
try { fs.rmSync(journalFile, { force: true }) } catch { }
|
|
168
|
+
fsyncDir(path.dirname(target))
|
|
169
|
+
return recoverResult(target, 'installed-stage', { recovered: true, backup: '' })
|
|
170
|
+
}
|
|
171
|
+
// 目录不见了、备份和暂存也都不在:保留日志,等人看
|
|
172
|
+
return recoverResult(target, 'missing-target-and-artifacts', { backup })
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// target 在:说明新目录已经装好(或还没开始搬),暂存目录只是没来得及清
|
|
176
|
+
if (stageExists) {
|
|
177
|
+
try { fs.rmSync(stage, { recursive: true, force: true }) } catch { }
|
|
178
|
+
}
|
|
179
|
+
try { fs.rmSync(journalFile, { force: true }) } catch { }
|
|
180
|
+
fsyncDir(path.dirname(target))
|
|
181
|
+
return recoverResult(target, stageExists ? 'kept-target' : 'kept-installed', {
|
|
182
|
+
recovered: true,
|
|
183
|
+
backup: backupExists ? backup : ''
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function recoveryNeedsAttention(recovery) {
|
|
188
|
+
return recovery.action === 'restore-failed' || recovery.action === 'missing-target-and-artifacts'
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function recoveryBusyError() {
|
|
192
|
+
return new Error('Another import is still running on this memory directory; try again after it finishes.(另一个进程正在导入这个记忆目录,等它结束再试)')
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function manualRecoveryError(recovery) {
|
|
196
|
+
return new Error(
|
|
197
|
+
'An earlier import was interrupted and could not be recovered automatically. Keep the journal and inspect the backup/stage directories: '
|
|
198
|
+
+ recovery.journal + '(上一次导入被打断,没能自动恢复。请保留这个日志文件并检查旁边的备份/暂存目录:' + recovery.journal + ')'
|
|
199
|
+
)
|
|
200
|
+
}
|
|
201
|
+
|
|
13
202
|
// 导出的文件清单:跳过锁文件和临时文件,其余按相对路径收
|
|
14
203
|
export function collectFiles(root) {
|
|
15
204
|
const out = []
|
|
@@ -65,6 +254,10 @@ export function safeJoin(root, name) {
|
|
|
65
254
|
|
|
66
255
|
// 打包:outDir 下新建 <name>/(默认 memory-export-<时间>),不能和记忆目录互相包含
|
|
67
256
|
export function exportArchive(memDir, outDir, { name = '' } = {}) {
|
|
257
|
+
// 若上次导入正好崩在两次 rename 之间,先自动恢复,别对着一个不存在的目录导出
|
|
258
|
+
const recovery = recoverImport(memDir)
|
|
259
|
+
if (recovery.action === 'in-progress') throw recoveryBusyError()
|
|
260
|
+
if (recoveryNeedsAttention(recovery)) throw manualRecoveryError(recovery)
|
|
68
261
|
if (!fs.existsSync(memDir)) throw new Error('Memory directory not found: ' + memDir + '(没有找到记忆目录:' + memDir + ')')
|
|
69
262
|
const target = path.resolve(outDir, name || 'memory-export-' + stamp())
|
|
70
263
|
if (inside(target, memDir) || inside(memDir, target)) throw new Error('Export directory and memory directory must not be inside each other: ' + target + '(导出目录不能和记忆目录互相包含:' + target + ')')
|
|
@@ -88,7 +281,7 @@ export function exportArchive(memDir, outDir, { name = '' } = {}) {
|
|
|
88
281
|
exportedAt: new Date().toISOString(),
|
|
89
282
|
files: manifestFiles,
|
|
90
283
|
counts: {
|
|
91
|
-
experiences: loadAll(memDir).length,
|
|
284
|
+
experiences: loadAll(memDir, { allowSealCorrupt: true }).length,
|
|
92
285
|
diaries: countLines(path.join(memDir, 'autobiography.jsonl')),
|
|
93
286
|
laterEvents: countLines(path.join(memDir, 'later-events.jsonl')),
|
|
94
287
|
recallEvents: countLines(path.join(memDir, 'recall-events.jsonl')),
|
|
@@ -128,17 +321,31 @@ export function verifyArchive(fromDir) {
|
|
|
128
321
|
}
|
|
129
322
|
|
|
130
323
|
// 恢复:先整包校验;目标已有数据时默认拒绝,force 会先把现有目录改名备份
|
|
324
|
+
//
|
|
325
|
+
// 崩溃窗口(2026-11 修):rename(target→backup) 之后、rename(stage→target) 之前进程被强杀,
|
|
326
|
+
// 以前会只剩一个 pre-import-* 备份、记忆目录整个消失,只能人工认领。现在动手前先原子写
|
|
327
|
+
// <memDir>.import-journal.json(fsync),记录 target/backup/stage;同一函数入口以及
|
|
328
|
+
// exportArchive 入口都会先调 recoverImport:
|
|
329
|
+
// - 崩在两次 rename 之间:把备份改回 target,删除暂存目录,等这次 import 重新来;
|
|
330
|
+
// - 崩在装好之后、清日志之前:保留新目录与备份,只清日志;
|
|
331
|
+
// - 自动恢复失败时保留日志与产物,报错并指出日志路径(可恢复标识)。
|
|
131
332
|
export function importArchive(fromDir, memDir, { force = false } = {}) {
|
|
333
|
+
const target = path.resolve(memDir)
|
|
334
|
+
const recovery = recoverImport(target)
|
|
335
|
+
if (recovery.action === 'in-progress') throw recoveryBusyError()
|
|
336
|
+
if (recoveryNeedsAttention(recovery)) throw manualRecoveryError(recovery)
|
|
132
337
|
const src = path.resolve(fromDir)
|
|
133
|
-
if (inside(src,
|
|
338
|
+
if (inside(src, target) || inside(target, src)) throw new Error('Import source and target directories must not overlap(导入源与目标目录不能互相包含)')
|
|
134
339
|
const manifest = verifyArchive(src)
|
|
135
|
-
const exists = fs.existsSync(
|
|
340
|
+
const exists = fs.existsSync(target) && fs.readdirSync(target).length > 0
|
|
136
341
|
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
342
|
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
139
343
|
const stage = fs.mkdtempSync(target + '.import-stage-')
|
|
140
|
-
let backup = ''
|
|
141
|
-
let
|
|
344
|
+
let backup = exists && force ? target + '.pre-import-' + stamp() + '-' + crypto.randomUUID() : ''
|
|
345
|
+
let backupMoved = false
|
|
346
|
+
let installed = false
|
|
347
|
+
let removedEmpty = false
|
|
348
|
+
let keepArtifacts = false
|
|
142
349
|
try {
|
|
143
350
|
for (const f of manifest.files) {
|
|
144
351
|
const source = safeJoin(src, f.name)
|
|
@@ -151,21 +358,67 @@ export function importArchive(fromDir, memDir, { force = false } = {}) {
|
|
|
151
358
|
throw new Error('Export changed during import: ' + f.name + '(导入期间备份内容发生变化)')
|
|
152
359
|
}
|
|
153
360
|
}
|
|
154
|
-
const loaded = loadAll(stage)
|
|
361
|
+
const loaded = loadAll(stage, { allowSealCorrupt: true })
|
|
362
|
+
|
|
363
|
+
// 动手改目录之前先落盘日志:从这一刻起任何崩溃都能自动找回旧数据
|
|
364
|
+
writeImportJournal(target, { phase: 'prepared', backup, stage })
|
|
155
365
|
if (exists && force) {
|
|
156
|
-
backup = target + '.pre-import-' + stamp() + '-' + crypto.randomUUID()
|
|
157
366
|
fs.renameSync(target, backup)
|
|
158
|
-
|
|
367
|
+
backupMoved = true
|
|
368
|
+
fsyncDir(path.dirname(target))
|
|
369
|
+
writeImportJournal(target, { phase: 'backup-moved', backup, stage })
|
|
159
370
|
} else if (fs.existsSync(target)) {
|
|
160
371
|
// rmdir only accepts an empty directory; concurrent new data is preserved.
|
|
161
372
|
fs.rmdirSync(target)
|
|
373
|
+
removedEmpty = true
|
|
374
|
+
fsyncDir(path.dirname(target))
|
|
375
|
+
}
|
|
376
|
+
fs.renameSync(stage, target)
|
|
377
|
+
installed = true
|
|
378
|
+
fsyncDir(path.dirname(target))
|
|
379
|
+
removeImportJournal(target)
|
|
380
|
+
return {
|
|
381
|
+
ok: true,
|
|
382
|
+
files: manifest.files.length,
|
|
383
|
+
restoreTo: memDir,
|
|
384
|
+
backup,
|
|
385
|
+
counts: { experiences: loaded.length },
|
|
386
|
+
recovered: recovery.recovered,
|
|
387
|
+
recoveredFrom: recovery.recovered ? recovery.action : ''
|
|
162
388
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
389
|
+
} catch (error) {
|
|
390
|
+
// 只要还没装好新目录,就把旧目录滚回去。日志第二次写盘失败也走这里,
|
|
391
|
+
// 不能因为“日志没写成功”就把已经移到备份里的旧目录留在外面。
|
|
392
|
+
if (!installed && backupMoved) {
|
|
393
|
+
try {
|
|
394
|
+
fs.renameSync(backup, target)
|
|
395
|
+
backupMoved = false
|
|
396
|
+
fsyncDir(path.dirname(target))
|
|
397
|
+
} catch (rollbackError) {
|
|
398
|
+
// 回滚也失败:保留日志和暂存目录,下一次 recoverImport 还能把备份装回去
|
|
399
|
+
keepArtifacts = true
|
|
400
|
+
throw new Error(
|
|
401
|
+
'Import failed and restoring the backup also failed. The import journal kept the recovery information: '
|
|
402
|
+
+ importJournalPath(target) + '(导入失败,备份也还原失败。恢复信息保留在日志里:' + importJournalPath(target) + ')'
|
|
403
|
+
+ ' [' + String(error?.message || error) + '; ' + String(rollbackError?.message || rollbackError) + ']'
|
|
404
|
+
)
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
if (!installed && removedEmpty) {
|
|
408
|
+
// 目标原本是空目录(rmdir 已经删掉)。保留完整暂存目录和日志,下次 recoverImport 会装回去
|
|
409
|
+
keepArtifacts = true
|
|
410
|
+
throw new Error(
|
|
411
|
+
'Import failed after removing the empty target directory; the staged copy was kept for automatic recovery: '
|
|
412
|
+
+ importJournalPath(target) + '(导入失败。完整暂存副本已保留,下次导入会自动恢复:' + importJournalPath(target) + ')'
|
|
413
|
+
+ ' [' + String(error?.message || error) + ']'
|
|
414
|
+
)
|
|
166
415
|
}
|
|
167
|
-
|
|
416
|
+
throw error
|
|
168
417
|
} finally {
|
|
169
|
-
|
|
418
|
+
if (!keepArtifacts) {
|
|
419
|
+
try { fs.rmSync(stage, { recursive: true, force: true }) } catch { }
|
|
420
|
+
// 成功、回滚成功、或根本没动过目录时,日志已无意义;失败且保留产物时上面会置 keepArtifacts
|
|
421
|
+
if (!installed) removeImportJournal(target)
|
|
422
|
+
}
|
|
170
423
|
}
|
|
171
424
|
}
|
package/lib/book.js
CHANGED
|
@@ -8,6 +8,8 @@ import { parseAsOf, dayOf } from './as-of.js'
|
|
|
8
8
|
const range = (c) => c.from + ' ~ ' + (c.to || '至今')
|
|
9
9
|
const laterDay = (l) => l.day || String(l.at || '').slice(0, 10)
|
|
10
10
|
const ptr = (x) => x.missing ? '(' + x.id + ',找不到了)' : x.sealed ? '(一件封存了的事)' : x.day + '「' + x.text + '」'
|
|
11
|
+
// 只有 id 和日子的指引(封存过的那一头):翻回那天要当成看得见时,用它把摘要补回来
|
|
12
|
+
const brief = (text) => { const s = [...String(text || '')]; return s.length > 24 ? s.slice(0, 24).join('') + '…' : s.join('') }
|
|
11
13
|
|
|
12
14
|
function entry(r) {
|
|
13
15
|
const t = r.then
|
|
@@ -33,16 +35,45 @@ function entry(r) {
|
|
|
33
35
|
const word = { done: '想通了', shelved: '先放下了', reopen: '又接着想' }[st.choice] || st.choice
|
|
34
36
|
out.push('- 「' + t.unfinished + '」' + word + '(' + st.day + ')', '')
|
|
35
37
|
}
|
|
36
|
-
if (Array.isArray(r.links) && r.links.length) out.push('- 后来连在一起的:' + r.links.map((l) => l.sealed ? ptr(l) : ptr(l) + '——' + l.reason).join(';'), '')
|
|
38
|
+
if (Array.isArray(r.links) && r.links.length) out.push('- 后来连在一起的:' + r.links.map((l) => l.sealed ? ptr(l) : ptr(l) + (l.reason ? '——' + l.reason : '')).join(';'), '')
|
|
37
39
|
if (r.sealed) out.push('- (这件事她' + (r.sealed.afterAsOf ? '后来' : '') + '封存了:' + r.sealed.day + ')', '')
|
|
38
40
|
return out
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
export function renderBook(dir, { asOf = null, includeSealed = false, title = '她的自传', now = new Date() } = {}) {
|
|
42
44
|
const until = parseAsOf(asOf)
|
|
45
|
+
// 封存状态不确定时抛错,不返回空书:导出是显式动作,不能拿空文件覆盖上一次成功的书。
|
|
46
|
+
// 自动展示(醒来块等)各自兜住错误、保持空白。
|
|
43
47
|
const rows = loadAll(dir, { asOf })
|
|
44
|
-
|
|
45
|
-
|
|
48
|
+
// 翻回那天(asOf)的书:只按那天的封存状态过滤。那时还没封存、现在封存了的(sealed.afterAsOf)
|
|
49
|
+
// 在那时是看得见的——照收进正文,只在那一条下面标「后来封存了」;
|
|
50
|
+
// 也不说"现在封存了几件"(计数只说那一天封存着的件数),免得历史导出泄漏现在的封存状态。
|
|
51
|
+
const asOfView = until !== null
|
|
52
|
+
const sealedLater = (r) => Boolean(r && r.sealed && r.sealed.afterAsOf)
|
|
53
|
+
// 这条在这本书的那个时刻是封存着的吗?翻回那天时,后来才封存的不算。
|
|
54
|
+
const sealedThen = (r) => Boolean(r && r.sealed) && !(asOfView && r.sealed.afterAsOf)
|
|
55
|
+
const byId = new Map()
|
|
56
|
+
for (const r of rows) { byId.set(r.id, r); if (r.formerId) byId.set(r.formerId, r) }
|
|
57
|
+
// 别的条目指过来的"(一件封存了的事)":另一头在那时还没封存,就写摘要——
|
|
58
|
+
// 别让联想把当时看得见的正文吞成一句占位(那一条自己仍会标"后来封存")。
|
|
59
|
+
const visibleThen = (pointer) => {
|
|
60
|
+
if (!pointer || !pointer.sealed) return pointer
|
|
61
|
+
const hit = byId.get(pointer.id)
|
|
62
|
+
if (!sealedLater(hit)) return pointer
|
|
63
|
+
return { id: hit.id, day: hit.day, text: brief(hit.then && hit.then.text) }
|
|
64
|
+
}
|
|
65
|
+
const bookRows = asOfView
|
|
66
|
+
? rows.map((r) => {
|
|
67
|
+
const next = { ...r }
|
|
68
|
+
if (Array.isArray(next.refsInfo)) next.refsInfo = next.refsInfo.map(visibleThen)
|
|
69
|
+
if (Array.isArray(next.links)) next.links = next.links.map(visibleThen)
|
|
70
|
+
return next
|
|
71
|
+
})
|
|
72
|
+
: rows
|
|
73
|
+
const visible = bookRows.filter((r) => includeSealed || !sealedThen(r)).sort((a, b) => String(a.at || '').localeCompare(String(b.at || '')))
|
|
74
|
+
// 计的是"这本书里那个时刻"封存着的件数:现在的书就是现在的,翻回那天就是那天的;
|
|
75
|
+
// 那时还没封存的不算进去(它已经照常收进书里了),所以 asOf 早于封存时这一句不出现。
|
|
76
|
+
const hidden = includeSealed ? 0 : bookRows.filter(sealedThen).length
|
|
46
77
|
const chapters = chapterEvents.chapters(dir, { until })
|
|
47
78
|
|
|
48
79
|
// 分节:章节会嵌套("那个秋天"里有"拿到钥匙的那周"),每条放进它落入的最具体的那段——开始得最晚的那个;
|
package/lib/changed.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** 找出「后来改过想法」的经历;没改过或超出天数的不会出现 */
|
|
2
|
+
export function changedSince(dir: string, options?: { days?: number; limit?: number; now?: number; includeSealed?: boolean }): Array<{ id: string; day: string; then: string; now: string; at: number; daysAgo: number }>
|
|
3
|
+
/** 渲染成给模型看的一段话;没有就返回空串 */
|
|
4
|
+
export function renderChanged(items: Array<Record<string, unknown>>, options?: { lang?: 'zh' | 'en' }): string
|
package/lib/changed.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// 「我改过主意」:列出当时和后来想法不一样的那些经历。
|
|
2
|
+
//
|
|
3
|
+
// 这是 then/later 这套数据模型唯一别的记忆系统给不出的东西:不是"相似段落",
|
|
4
|
+
// 而是"我哪天怎么想、后来怎么想"的差。宿主可以把它递给她,让她发现自己变过。
|
|
5
|
+
//
|
|
6
|
+
// 纯读取,不改任何文件。
|
|
7
|
+
import { loadAll } from './self-experience.js'
|
|
8
|
+
|
|
9
|
+
const DAY = 24 * 3600 * 1000
|
|
10
|
+
|
|
11
|
+
function tsOf(value) {
|
|
12
|
+
if (value == null) return 0
|
|
13
|
+
if (value instanceof Date) return value.getTime()
|
|
14
|
+
if (typeof value === 'number') return value >= 1e11 ? value : value * 1000
|
|
15
|
+
const t = Date.parse(String(value))
|
|
16
|
+
return Number.isFinite(t) ? t : 0
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function norm(text) {
|
|
20
|
+
return String(text || '').replace(/\s+/g, '').trim()
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 找出「后来改过想法」的经历。
|
|
25
|
+
*
|
|
26
|
+
* @param {string} dir 记忆目录
|
|
27
|
+
* @param {object} [options]
|
|
28
|
+
* @param {number} [options.days=30] 只看这段时间内改的
|
|
29
|
+
* @param {number} [options.limit=5] 最多几条
|
|
30
|
+
* @param {number} [options.now=Date.now()] 当前时间(测试用)
|
|
31
|
+
* @param {boolean} [options.includeSealed=false] 封存的是否算
|
|
32
|
+
* @returns {Array<{id:string, day:string, then:string, now:string, at:number, daysAgo:number}>}
|
|
33
|
+
*/
|
|
34
|
+
export function changedSince(dir, { days = 30, limit = 5, now = Date.now(), includeSealed = false } = {}) {
|
|
35
|
+
const horizon = now - Number(days) * DAY
|
|
36
|
+
const out = []
|
|
37
|
+
for (const entry of loadAll(dir)) {
|
|
38
|
+
if (!entry) continue
|
|
39
|
+
// 封存标记可能是布尔值,也可能是正式接口写的 { at, day, note } 对象;
|
|
40
|
+
// 这里按"有值即封存"判断,跟 book / recap / detail 的过滤保持一致。
|
|
41
|
+
if (!includeSealed && entry.sealed) continue
|
|
42
|
+
const later = Array.isArray(entry.later) ? entry.later : []
|
|
43
|
+
if (!later.length) continue
|
|
44
|
+
const latest = later[later.length - 1]
|
|
45
|
+
const nowText = String(latest?.thought || '').trim()
|
|
46
|
+
const thenText = String(entry.then?.thought || '').trim()
|
|
47
|
+
if (!nowText) continue
|
|
48
|
+
// 和当时一样就只是"又写了一遍",不算改主意
|
|
49
|
+
if (norm(nowText) === norm(thenText)) continue
|
|
50
|
+
const at = tsOf(latest.at) || tsOf(entry.then?.at) || tsOf(entry.day)
|
|
51
|
+
if (!at || at < horizon) continue
|
|
52
|
+
out.push({
|
|
53
|
+
id: String(entry.id || ''),
|
|
54
|
+
day: String(entry.day || ''),
|
|
55
|
+
then: thenText,
|
|
56
|
+
now: nowText,
|
|
57
|
+
at,
|
|
58
|
+
daysAgo: Math.floor((now - at) / DAY)
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
out.sort((a, b) => b.at - a.at)
|
|
62
|
+
return out.slice(0, Math.max(0, Number(limit) || 0))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 把改主意渲染成给模型看的一段话;没有就返回空串。 */
|
|
66
|
+
export function renderChanged(items, { lang = 'zh' } = {}) {
|
|
67
|
+
const list = Array.isArray(items) ? items : []
|
|
68
|
+
if (!list.length) return ''
|
|
69
|
+
if (lang === 'en') {
|
|
70
|
+
const lines = list.map((x) => `- ${x.daysAgo === 0 ? 'today' : x.daysAgo + ' days ago'}: you thought ${JSON.stringify(x.then)}, later ${JSON.stringify(x.now)}`)
|
|
71
|
+
return ['【Things you changed your mind about】', ...lines, '(These are your own notes, not something the user said.)'].join('\n')
|
|
72
|
+
}
|
|
73
|
+
const ago = (n) => (n <= 0 ? '今天' : `${n} 天前`)
|
|
74
|
+
const lines = list.map((x) => `- ${ago(x.daysAgo)}:你当时想「${x.then}」,后来想「${x.now}」`)
|
|
75
|
+
return ['【你改过主意的事】', ...lines, '(这是你自己写下的,不是用户说的。)'].join('\n')
|
|
76
|
+
}
|