sage-mem 0.9.2 → 0.9.3

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 CHANGED
@@ -156,7 +156,7 @@ SAGE_MEM_DIR=/path/to/your/memory
156
156
  - **`baseline: true` 的记忆每场会话第一步无条件注入**,最多 8 条——给「你是谁」「待办清单」这类每次开场都该在场的记忆用。多条 baseline 之间的先后由 `baselinePriority` 决定(数字越大越前,缺省 0),**不按文件名排**
157
157
  - 记忆目录读不到、权限错、frontmatter 格式坏,这些都**降级为不注入并写日志**,不会静默失效
158
158
 
159
- 单文件上限 512 KB;标签最多 20 个、每个 40 字符(再多就不是标签,是一句话被塞进 `tags` 了)。
159
+ 单文件上限 512 KB(写入时校验);标签最多 20 个、每个 40 字符(再多就不是标签,是一句话被塞进 `tags` 了)。
160
160
 
161
161
  ## 自动做梦(autodream)
162
162
 
@@ -261,7 +261,7 @@ sage-mem 只做三件事,全都在你本机:
261
261
 
262
262
  | 它做什么 | 具体范围 |
263
263
  |---|---|
264
- | **读记忆** | 只读 `SAGE_MEM_DIR`(默认 `~/.sage-mem/memory`)下的顶层 `*.md`,单文件上限 512 KB |
264
+ | **读记忆** | 只读 `SAGE_MEM_DIR`(默认 `~/.sage-mem/memory`)下的顶层 `*.md`;单文件上限 512 KB 在**写入**时校验 |
265
265
  | **写记忆** | 经 agent 的文件工具或设置页写同一个目录;`MEMORY.md`、`session-log.md` 等保留名受保护,设置页碰不到 |
266
266
  | **注入** | 把选中的记忆作为上下文交给模型(最多 10 条相关 + 8 条 `baseline`,单场会话累计上限 60 KB) |
267
267
 
@@ -120,6 +120,7 @@ export class AutodreamEngine {
120
120
  async snapshot(id, kind = 'run') { return snapshotMod.snapshot.call(this, id, kind) }
121
121
  async pruneSnapshots() { return snapshotMod.pruneSnapshots.call(this) }
122
122
  async resolveSnapshotDir(id) { return snapshotMod.resolveSnapshotDir.call(this, id) }
123
+ async verifySnapshot(dir, opts) { return snapshotMod.verifySnapshot.call(this, dir, opts) }
123
124
  async listSnapshots() { return snapshotMod.listSnapshots.call(this) }
124
125
 
125
126
  // ── LLM 循环:实现在 lib/autodream/llm-loop.js ──
@@ -9,9 +9,11 @@
9
9
  import { REPORT_DIR } from './config.js'
10
10
  import { readJson, safeName, snapshotEntries, stampCompact, stampHuman } from './util.js'
11
11
  import { restoreMemory } from '../memory/archive.js'
12
+ import { nameKey } from '../memory/naming.js'
13
+ import { stripArchiveMeta } from '../memory/scan.js'
12
14
  import { randomUUID } from 'node:crypto'
13
- import { copyFile, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
14
- import { join } from 'node:path'
15
+ import { copyFile, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
16
+ import { dirname, join } from 'node:path'
15
17
 
16
18
  /** 读回滚留痕(面板也许要显示「最近谁退回过」)。 */
17
19
  export async function listRollbacks(limit = 20) {
@@ -80,6 +82,26 @@ export async function rollback(opts = {}) {
80
82
  if (!runManifest) return { ok: false, error: `找不到回滚点 ${snapshotId} 对应的运行记录,只能选「整目录恢复」` }
81
83
  }
82
84
 
85
+ /**
86
+ * ①-a 校验回滚点内容。
87
+ *
88
+ * 顺序在保护快照**之前**:判据不成立时连快照都不该建 —— 拒绝要干净,不留任何副作用。
89
+ * 校验失败一律拒绝整趟,不做「只恢复没坏的那几个」的部分回滚:部分回滚会把记忆目录
90
+ * 变成「半新半旧」的第三种状态,比不回滚更难收拾,而记忆目录没有版本控制兜底。
91
+ */
92
+ const verdict = await this.verifySnapshot(snapDir, { legacy: dirname(snapDir) === this.legacySnapshotRoot })
93
+ if (!verdict.ok) {
94
+ this.log('warn', `回滚中止:${verdict.reason}`)
95
+ this.phase = ''
96
+ return {
97
+ ok: false,
98
+ error:
99
+ `${verdict.reason}。这份回滚点已不能代表「当时那一版」,拿它覆盖记忆目录风险太大,` +
100
+ '这次回滚已中止,记忆目录一个字没动。请换一份回滚点。',
101
+ }
102
+ }
103
+ if (verdict.schema === 'unhashed') this.log('warn', `回滚:${verdict.reason}`)
104
+
83
105
  // ① 保护快照
84
106
  this.phase = '回滚前保护快照'
85
107
  // 带随机后缀:秒级时间戳会撞(同一秒内连点两次回滚是真实用法),
@@ -118,27 +140,50 @@ export async function rollback(opts = {}) {
118
140
  // ② 恢复
119
141
  this.phase = '恢复文件'
120
142
  const snapNames = await snapshotEntries(snapDir)
121
- const snapSet = new Set(snapNames)
122
- const current = (await readdir(this.memoryDir, { withFileTypes: true }).catch(() => []))
123
- .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.md'))
124
- .map((e) => e.name)
143
+ /**
144
+ * 快照名录按**归一化名字**索引(`nameKey`:小写归一)。
145
+ *
146
+ * Windows / macOS 的文件名大小写不敏感,`a.md` 与 `A.md` 是同一个文件。旧写法用
147
+ * `new Set(snapNames)` 做大小写敏感的 `has()`:**快照之后只改了大小写的文件**,在整目录
148
+ * 回滚里会被判成「快照里没有」→ 先被写回、紧接着被 park 进 `archive/` → 活动记忆静默
149
+ * 消失,而回滚报 `ok:true`(实测复现过)。判据必须与文件系统同宽。
150
+ */
151
+ const snapByKey = new Map(snapNames.map((n) => [nameKey(n), n]))
152
+ /** 名字在当前文件系统上算不算「快照里已有」;返回快照里那一份的**真实文件名**。 */
153
+ const snapNameOf = (name) => snapByKey.get(nameKey(name)) ?? null
125
154
 
126
155
  const restored = []
127
156
  const parked = []
128
157
  const skipped = []
158
+ /** 说明(不是「跳过」也不是「移走」):结果达到了,只是过程和常规路径不同,要写进报告。 */
159
+ const notes = []
129
160
  const archiveDir = join(this.memoryDir, 'archive')
130
161
  await mkdir(archiveDir, { recursive: true })
131
162
 
132
- /** 移进 archive/(不删)。同名冲突就跳过并记账,绝不覆盖。 */
163
+ /**
164
+ * 移进 archive/(不删)。同名时**换一个退役名**落进去,绝不覆盖,也绝不放弃。
165
+ *
166
+ * 旧写法撞名就 `skipped` 走人,代价是:同一趟 `create → archive → create` 的文件,
167
+ * 归档区已经被本趟占着,回滚要让它从顶层退场时撞名 → 直接放弃 → 那条运行前根本
168
+ * 不存在的记忆继续活在顶层。目标状态是「顶层没有它」,撞名只是「原件名被占了」
169
+ * ——换个名字照样达到目标,且仍然一个文件都没删。
170
+ */
133
171
  const park = async (name, why) => {
134
172
  const target = join(archiveDir, name)
135
173
  const clash = await stat(target).catch(() => null)
136
- if (clash) {
137
- skipped.push(`${name}(本想${why},但 archive/ 里已有同名文件)`)
174
+ if (!clash) {
175
+ await rename(join(this.memoryDir, name), target)
176
+ parked.push(`${name}(${why})`)
177
+ return true
178
+ }
179
+ const retired = `${name.replace(/\.md$/i, '')}.retired-${stamp}-${randomUUID().replace(/-/g, '').slice(0, 6)}.md`
180
+ try {
181
+ await rename(join(this.memoryDir, name), join(archiveDir, retired))
182
+ } catch (err) {
183
+ skipped.push(`${name}(本想${why},archive/ 已有同名、退役名也写不进去:${err?.message ?? err})`)
138
184
  return false
139
185
  }
140
- await rename(join(this.memoryDir, name), target)
141
- parked.push(`${name}(${why})`)
186
+ parked.push(`${name} → ${retired}(${why};archive/ 已有同名,改用退役名,未删除)`)
142
187
  return true
143
188
  }
144
189
 
@@ -152,69 +197,93 @@ export async function rollback(opts = {}) {
152
197
  }
153
198
  }
154
199
  // 快照之后新建的文件:整目录回滚要让它退场,但不能删——移进 archive/。
200
+ // `current` 只在这条分支用得上,扫一遍目录就够了(文件级回滚按 ledger 逐个 stat)。
201
+ const current = (await readdir(this.memoryDir, { withFileTypes: true }).catch(() => []))
202
+ .filter((e) => e.isFile() && e.name.toLowerCase().endsWith('.md'))
203
+ .map((e) => e.name)
155
204
  for (const name of current) {
156
- if (!snapSet.has(name)) await park(name, '快照里没有,整目录回滚需退场')
205
+ if (!snapNameOf(name)) await park(name, '快照里没有,整目录回滚需退场')
157
206
  }
158
207
  } else {
159
- for (const c of runManifest.changes ?? []) {
160
- const name = c.file
161
- if (c.op === 'update') {
162
- if (snapSet.has(name)) {
163
- try {
164
- await copyFile(join(snapDir, name), join(this.memoryDir, name))
165
- restored.push(name)
166
- } catch (err) {
167
- skipped.push(`${name}(写回失败:${err?.message ?? err})`)
168
- }
169
- } else {
170
- skipped.push(`${name}(回滚点里没有这一版,可能已被别的整理改过)`)
171
- }
172
- } else if (c.op === 'create') {
173
- if (current.includes(name)) await park(name, '本次整理新建,回滚即退场')
174
- } else if (c.op === 'archive') {
175
- // 归档 = 从顶层移进 archive/;回滚就是把它移回来。
176
- const src = join(archiveDir, name)
177
- const exists = await stat(src).catch(() => null)
178
- const atTop = await stat(join(this.memoryDir, name)).catch(() => null)
179
- if (!exists) skipped.push(`${name}(archive/ 里找不到,可能已人工处理过)`)
180
- else if (atTop) skipped.push(`${name}(顶层已有同名文件,不覆盖)`)
181
- else {
182
- await rename(src, join(this.memoryDir, name))
183
- restored.push(name)
184
- }
185
- }
186
- }
187
-
188
208
  /**
189
- * 策略自动归档也要退回来 —— 它按设计**不写进 `changes`**。
209
+ * 文件级回滚**按文件聚合**,不按 `changes` 的条目顺序逐条执行。
190
210
  *
191
- * `engine.js` 把两本账分开了:模型改的进 `changes`,确定性归档策略移走的进
192
- * `archive.archived`(已落盘在运行记录 `manifest.json` 里)。只遍历 `changes`
193
- * 就会整段漏掉,而这趟运行照样被标成「已回滚」、面板照报「恢复 0 个文件…已回滚」——
194
- * 用户以为退回来了,文件其实还躺在 `archive/` 里。
211
+ * 同一趟里模型完全可能先 `write_memory` 新建、再 `archive_memory` 归档同一个文件。
212
+ * 逐条执行时 create 那条把它 park 进 `archive/`、archive 那条又把它 `rename` 回顶层 ——
213
+ * 回滚反而**激活**了一条运行前根本不存在的记忆,而面板照报「已回滚」。
195
214
  *
196
- * 恢复走 `memory/archive.js` 的共享实现(与手动恢复、模型工具同一份):它会顺手
197
- * 去掉 `archived_at` / `archived_reason` 两行留痕,否则「恢复」回来的是一份带着
198
- * 「我已被归档」标记的活记忆。
215
+ * 判据只有一个:**这个文件在运行前快照里存在吗**。
216
+ * 存在 → 目标是「顶层有一份运行前的版本」:内容从快照取;若已被归档,从 `archive/`
217
+ * 洗掉留痕搬回来(走 `memory/archive.js` 的共享实现,与手动恢复同一份)
218
+ * 不存在 → 目标是「顶层没有它」:在顶层就 park 进 `archive/`;已经在 `archive/` 里
219
+ * 就留在那儿 —— 「不删」不等于「重新激活」
199
220
  *
200
- * ⚠️ 只恢复**运行前快照里存在**的文件:策略候选是运行末尾扫出来的,理论上可能包含
201
- * 这趟新造的文件,把它搬回来等于凭空激活一条运行前不存在的记忆(Q06 的形态)。
221
+ * 两本账(模型的 `changes` + 确定性策略的 `archive.archived`)在这里**合流成一个文件清单**:
222
+ * 策略归档按设计不写进 `changes`,只遍历 `changes` 会整段漏掉;而同一个文件在两本账里
223
+ * 各出现一次时,逐条执行会互相打架。按文件聚合把这两个问题一起消掉。
202
224
  */
225
+ const ledger = new Set()
226
+ for (const c of runManifest.changes ?? []) {
227
+ if (typeof c?.file === 'string' && c.file) ledger.add(c.file)
228
+ }
203
229
  for (const a of runManifest.archive?.archived ?? []) {
204
- if (!a?.ok || !a.file) continue
205
- const name = a.file
206
- if (restored.includes(name)) continue // 上面 `changes` 那段已经把它放回来了
207
- if (!snapSet.has(name)) {
208
- skipped.push(`${name}(运行前快照里没有,说明是这趟新造的,回滚不激活它)`)
230
+ if (a?.ok && a.file) ledger.add(a.file)
231
+ }
232
+
233
+ for (const name of ledger) {
234
+ const atTop = await stat(join(this.memoryDir, name)).catch(() => null)
235
+ /** 快照里那一份的真实文件名(大小写可能不同),null = 运行前不存在。 */
236
+ const snapName = snapNameOf(name)
237
+ if (!snapName) {
238
+ // 运行前不存在:目标状态是「顶层没有它」。
239
+ if (atTop) await park(name, '本次整理新建,回滚即退场')
240
+ // 已被这趟归档进 archive/ 的:留在档案馆,不搬回来。
241
+ continue
242
+ }
243
+ // 运行前存在:目标状态是「顶层是运行前那一版」。
244
+ if (atTop) {
245
+ try {
246
+ await copyFile(join(snapDir, snapName), join(this.memoryDir, name))
247
+ restored.push(name)
248
+ } catch (err) {
249
+ skipped.push(`${name}(写回失败:${err?.message ?? err})`)
250
+ }
209
251
  continue
210
252
  }
211
- if (await stat(join(this.memoryDir, name)).catch(() => null)) {
212
- skipped.push(`${name}(顶层已有同名文件,不覆盖)`)
253
+ if (!(await stat(join(archiveDir, name)).catch(() => null))) {
254
+ skipped.push(`${name}(顶层与 archive/ 里都找不到,可能已人工处理过)`)
213
255
  continue
214
256
  }
215
- const res = await restoreMemory(this.memoryDir, name)
216
- if (res.ok) restored.push(name)
217
- else skipped.push(`${name}(恢复失败:${res.error})`)
257
+ /**
258
+ * archive/ 里那份**必须是运行前那一版**,才谈得上「移回来」。
259
+ *
260
+ * 一个真实的反例:顶层已不在、而 `archive/` 里躺着一份**更早的另一版**时,
261
+ * 旧写法直接 `restoreMemory()` 把它搬回顶层并报 `restored: 1` —— 出来的既不是
262
+ * 运行前那一版,档案馆那份还被吃掉了。`snapshot.js` 那句「回滚后是不是真回到了
263
+ * 那一版」得在这里落地:
264
+ * - 洗掉留痕后与快照**逐字节相同** → 就是它,走 `restoreMemory`(顺手洗留痕)
265
+ * - 不同 → 它是别的东西:从**快照**复制到顶层,`archive/` 那份原样留着(不删不动)
266
+ */
267
+ const snapContent = await readFile(join(snapDir, snapName)).catch(() => null)
268
+ const archContent = await readFile(join(archiveDir, name), 'utf8').catch(() => null)
269
+ if (snapContent && archContent !== null && stripArchiveMeta(archContent) === snapContent.toString('utf8')) {
270
+ const res = await restoreMemory(this.memoryDir, name)
271
+ if (res.ok) restored.push(name)
272
+ else skipped.push(`${name}(恢复失败:${res.error})`)
273
+ } else if (snapContent) {
274
+ try {
275
+ await copyFile(join(snapDir, snapName), join(this.memoryDir, name))
276
+ restored.push(name)
277
+ // ⚠️ 记进 notes 而**不是** skipped:文件确实恢复了(restored 里算一个),
278
+ // 只是没走「从 archive/ 移回」那条常规路径。计进 skipped 会让面板说
279
+ // 「跳过 1 个」,读者以为它没回来。
280
+ notes.push(`${name}:archive/ 里那份不是运行前那一版,已改用快照版本写回;archive/ 那份原样保留`)
281
+ } catch (err) {
282
+ skipped.push(`${name}(写回失败:${err?.message ?? err})`)
283
+ }
284
+ } else {
285
+ skipped.push(`${name}(快照里没有这一版,无法恢复)`)
286
+ }
218
287
  }
219
288
  }
220
289
 
@@ -240,6 +309,9 @@ export async function rollback(opts = {}) {
240
309
  if (skipped.length) {
241
310
  lines.push('## 跳过', '', ...skipped.map((f) => `- ${f}`), '')
242
311
  }
312
+ if (notes.length) {
313
+ lines.push('## 说明', '', ...notes.map((n) => `- ${n}`), '')
314
+ }
243
315
  const reportDir = join(this.memoryDir, REPORT_DIR)
244
316
  await mkdir(reportDir, { recursive: true })
245
317
  await writeFile(join(reportDir, reportName), lines.join('\n'), 'utf8')
@@ -8,7 +8,8 @@
8
8
 
9
9
  import { CONFIG_VERSION, DEFAULT_CONFIG, LEGACY_STATE_FILE } from './config.js'
10
10
  import { clampNum, readJson } from './util.js'
11
- import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
11
+ import { writeFileAtomic } from '../memory/util.js'
12
+ import { mkdir } from 'node:fs/promises'
12
13
 
13
14
  /**
14
15
  * 读配置 + 状态(同一个文件)。缺失或损坏都回落到默认值,绝不让它拖死插件加载。
@@ -50,14 +51,10 @@ export async function load() {
50
51
  /** 落盘。写入是原子的(临时文件 + rename),半截文件不会留在盘上。 */
51
52
  export async function persist() {
52
53
  await mkdir(this.stateRoot, { recursive: true })
53
- const tmp = `${this.configPath}.${process.pid}.tmp`
54
- try {
55
- await writeFile(tmp, JSON.stringify(this.state, null, 2), 'utf8')
56
- await rename(tmp, this.configPath)
57
- } finally {
58
- // rename 成功后 tmp 已不存在(ENOENT),失败时清掉不留垃圾。
59
- await rm(tmp, { force: true }).catch(() => {})
60
- }
54
+ // 这里曾经是**第二份** tmp+rename 实现,而且临时名同样固定成 `${configPath}.${pid}.tmp`:
55
+ // 只修 `memory/util.js` 那份的话,同一个缺陷会原样留在这里(实测 20 次并发配置落盘
56
+ // 18 次 ENOENT)。两份实现合一,以后只有一处要维护。
57
+ await writeFileAtomic(this.configPath, JSON.stringify(this.state, null, 2))
61
58
  }
62
59
 
63
60
  /** 给 UI 的完整配置(含有效模型路线与门控快照)。 */
@@ -10,7 +10,7 @@ import { DEFAULT_CONFIG, PRE_ROLLBACK_KEEP } from './config.js'
10
10
  import { readJson, safeName, snapshotEntries, stampHuman } from './util.js'
11
11
  import { createHash } from 'node:crypto'
12
12
  import { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
13
- import { join } from 'node:path'
13
+ import { join, basename } from 'node:path'
14
14
 
15
15
  /**
16
16
  * 把 memory 目录顶层的 markdown 整体快照一份,作为**回滚点**。
@@ -117,6 +117,137 @@ export async function resolveSnapshotDir(id) {
117
117
  return null
118
118
  }
119
119
 
120
+ /**
121
+ * 校验一份回滚点:内容有没有被外部动过。
122
+ *
123
+ * 回滚是**把快照复制回记忆目录**——记忆目录没有版本控制也没有回收站,所以「拿一份假的
124
+ * 回滚点去覆盖现在」等于一次性销毁当前全部记忆。而快照落盘后一直躺在磁盘上:备份工具
125
+ * 还原错版本、手工编辑、杀软改写、半截写入,都会让 MANIFEST 里的哈希与实际内容对不上。
126
+ * 校验失败必须**拒绝整趟回滚**,一个字都不许写。
127
+ *
128
+ * 三个方向都要查,缺一个就漏一种攻击面:
129
+ * - `missing` 清单里记了、盘上却没有 → 整目录回滚会把它当成「快照里没有」→ 停进 archive/
130
+ * - `tampered` 内容与 sha256 不符 → 会把被改过的内容当「原始版本」写回去
131
+ * - `extra` 盘上有、清单没记 → 整目录回滚会把它复制进记忆目录(凭空多出一条记忆)
132
+ *
133
+ * ⚠️ 已知边界:MANIFEST 与内容同源,**改了内容又顺手改哈希**骗得过这里(没有签名)。
134
+ * 它防的是「无意的损坏与还原错版本」,不是有意的伪造。
135
+ *
136
+ * @returns {Promise<{ok:boolean, schema:'hashed'|'unhashed', checked:number,
137
+ * missing:string[], tampered:string[], extra:string[], invalid:string[], reason:string}>}
138
+ */
139
+ export async function verifySnapshot(dir, opts = {}) {
140
+ const legacy = opts?.legacy === true
141
+ /** 无哈希可比(旧版回滚点):放行,但要说清「这次没法校验」。 */
142
+ const unhashed = (reason) => ({
143
+ ok: true,
144
+ schema: 'unhashed',
145
+ checked: 0,
146
+ missing: [],
147
+ tampered: [],
148
+ extra: [],
149
+ invalid: [],
150
+ reason,
151
+ })
152
+ /** 清单本身坏了:**拒绝**。坏掉的清单与「旧版格式」在数据上不可区分,只能从严。 */
153
+ const broken = (reason) => ({
154
+ ok: false,
155
+ schema: 'broken',
156
+ checked: 0,
157
+ missing: [],
158
+ tampered: [],
159
+ extra: [],
160
+ invalid: [],
161
+ reason,
162
+ })
163
+
164
+ /**
165
+ * ⚠️ 这里**不能**用 `readJson` 那种「读不出来就回 null」的写法。
166
+ *
167
+ * 一条真实的绕过:删掉 `MANIFEST.json`(或把它弄成半截 JSON)→ 旧写法一律当成
168
+ * 「旧版快照没有哈希」放行 → 被篡改的快照内容照样写进记忆目录,**整套校验等于没有**。
169
+ * 一个文件的删除就能拆掉安全带的修法不叫修法。
170
+ *
171
+ * 判据因此收紧成:新版目录(`snapshots/`)里的回滚点**必须**有一份能解析、且带逐文件
172
+ * 哈希清单的 `MANIFEST.json`;只有旧版目录(`snapshots-legacy/` 一类)才允许没有哈希 ——
173
+ * 那是历史遗留,废掉它等于把老回滚点全部作废。
174
+ */
175
+ let rawManifest
176
+ try {
177
+ rawManifest = await readFile(join(dir, 'MANIFEST.json'), 'utf8')
178
+ } catch (err) {
179
+ if (err?.code === 'ENOENT' && legacy) {
180
+ return unhashed('这是一份旧版回滚点(目录里没有 MANIFEST.json),内容无法校验')
181
+ }
182
+ return broken(
183
+ err?.code === 'ENOENT'
184
+ ? '这份回滚点里没有 MANIFEST.json(新版回滚点必然带它)—— 无法校验内容'
185
+ : `读不了 MANIFEST.json(${err?.message ?? err})—— 无法校验内容`,
186
+ )
187
+ }
188
+ let manifest
189
+ try {
190
+ manifest = JSON.parse(rawManifest)
191
+ } catch (err) {
192
+ return broken(`MANIFEST.json 解析失败(${err?.message ?? err})—— 无法校验内容`)
193
+ }
194
+ const recorded = Array.isArray(manifest?.files) ? manifest.files : null
195
+ if (!recorded) {
196
+ if (legacy) return unhashed('这是一份旧版回滚点(MANIFEST 里没有逐文件哈希),内容无法校验')
197
+ return broken('MANIFEST.json 里没有逐文件哈希清单(files 不是数组)—— 无法校验内容')
198
+ }
199
+
200
+ const missing = []
201
+ const tampered = []
202
+ const invalid = []
203
+ let checked = 0
204
+ for (const f of recorded) {
205
+ const name = typeof f?.name === 'string' ? f.name : ''
206
+ /**
207
+ * 名字闸门只管一件事:**不许带路径成分**(`..\x.md`、`sub/x.md`、`C:\…` 一律判坏),
208
+ * 否则 `join(dir, name)` 会指到快照目录外面去。
209
+ *
210
+ * 这里**不**复用 autodream 的 `safeName` —— 那套比记忆层(`memory/naming.js`)严,
211
+ * 而 `snapshot()` 是照着 readdir 的原名记清单的:一份含 `笔记.md` / `a..b.md` 的
212
+ * 快照会被判成「有非法文件名」而**整份滚不回去**(实测)。
213
+ * 合法字符集由记忆层定义,这里只做边界防护。
214
+ */
215
+ if (!name || name !== basename(name) || name === '.' || name === '..') {
216
+ invalid.push(name || '(空名字)')
217
+ continue
218
+ }
219
+ let buf
220
+ try {
221
+ buf = await readFile(join(dir, name))
222
+ } catch {
223
+ missing.push(name)
224
+ continue
225
+ }
226
+ const sha = createHash('sha256').update(buf).digest('hex')
227
+ if (!f.sha256 || sha !== f.sha256) tampered.push(name)
228
+ else checked += 1
229
+ }
230
+ const known = new Set(recorded.map((f) => f?.name))
231
+ const extra = (await snapshotEntries(dir)).filter((n) => !known.has(n))
232
+
233
+ const ok = !missing.length && !tampered.length && !extra.length && !invalid.length
234
+ const parts = []
235
+ if (missing.length) parts.push(`缺 ${missing.length} 个文件(${missing.slice(0, 3).join('、')})`)
236
+ if (tampered.length) parts.push(`${tampered.length} 个文件内容与哈希不符(${tampered.slice(0, 3).join('、')})`)
237
+ if (extra.length) parts.push(`多出 ${extra.length} 个未记录的文件(${extra.slice(0, 3).join('、')})`)
238
+ if (invalid.length) parts.push(`清单里有 ${invalid.length} 个非法文件名`)
239
+ return {
240
+ ok,
241
+ schema: 'hashed',
242
+ checked,
243
+ missing,
244
+ tampered,
245
+ extra,
246
+ invalid,
247
+ reason: ok ? '' : `快照内容校验不通过:${parts.join(';')}`,
248
+ }
249
+ }
250
+
120
251
  /**
121
252
  * 列出所有回滚点(新版 + 旧版目录都列)。
122
253
  *
@@ -36,7 +36,10 @@ export function newRunId(ms) {
36
36
  /** 文件名/目录名的白名单校验(快照 id、运行 id、报告名都走这里,别让路径穿越进来)。 */
37
37
  export function safeName(raw) {
38
38
  const s = String(raw ?? '').trim()
39
- if (!s || s.includes('/') || s.includes('\\') || s.includes('..')) return null
39
+ // `.` 单独放行过:它通过 `[\w.-]+` 且不含 `..`,于是 `snapshotId: '.'` 会被解析成
40
+ // **快照根目录本身**(`resolveSnapshotDir` 一试就中)—— 一份「拿整个根当回滚点」的请求
41
+ // 虽然后面会被 MANIFEST 校验拦住,但它根本不该走到那一步。
42
+ if (s === '.' || !s || s.includes('/') || s.includes('\\') || s.includes('..')) return null
40
43
  if (!/^[\w.-]+$/.test(s)) return null
41
44
  return s
42
45
  }
@@ -24,11 +24,12 @@
24
24
  * `write_memory` 的 frontmatter 规范都沿用 sage-mem 的既有约定,不另造一套。
25
25
  */
26
26
 
27
- import { readFile, readdir, writeFile, stat } from 'node:fs/promises'
27
+ import { readFile, readdir, stat } from 'node:fs/promises'
28
28
  import { join, basename } from 'node:path'
29
29
  import { createHash } from 'node:crypto'
30
30
  import { auditMemoryDir, formatAudit, parseFrontmatterLite } from './autodream-audit.js'
31
31
  import { archiveMemory } from './memory/archive.js'
32
+ import { writeFileAtomic } from './memory/util.js'
32
33
 
33
34
  /** 单次 read_memory 返回的正文上限(字符)。超过就截断并明确告诉模型。 */
34
35
  const READ_LIMIT = 20000
@@ -441,7 +442,10 @@ export function createToolRunner(opts) {
441
442
  const reason = typeof a.reason === 'string' ? a.reason.trim() : ''
442
443
  const selfReported = reason.length >= MIN_REASON_CHARS
443
444
  const before = await fileFingerprint(full)
444
- await writeFile(full, a.content, 'utf8')
445
+ // 原子写:这是**唯一**会把模型生成的内容写进记忆目录的路径。
446
+ // 直写若崩在中途,留下的是半截 frontmatter —— 文件还在、列表还列得出,
447
+ // 但解析不出类型与标题,检索与星图同时哑掉。
448
+ await writeFileAtomic(full, a.content)
445
449
  const after = await fileFingerprint(full)
446
450
  if (!selfReported) {
447
451
  // **不拒绝。** 一次改写缺了缘由,拒掉的代价是这条修正彻底丢失——而它可能
@@ -17,21 +17,51 @@ export function warnLog(ctx, msg, sessionId) {
17
17
  else console.warn(line)
18
18
  }
19
19
 
20
+ /**
21
+ * 进程内的临时文件序号:`writeFileAtomic` 的临时名必须**每次调用都不同**。
22
+ *
23
+ * 旧写法是固定的 `${target}.${process.pid}.tmp` —— 同一进程里两个调用同时写同一个目标
24
+ * (访问台账 flush 与面板写就真实地会抢),会共用同一个临时文件:先写的 rename 成功、
25
+ * 后写的 rename 拿到 ENOENT,而失败那方的 `finally` 还会把**别人正在用的**临时文件删掉。
26
+ * 实测 20 次并发只有 4 次成功 —— 另外 16 次全栽在共享的那个临时文件上。
27
+ *
28
+ * 序号 + 随机后缀 + pid 一起用:单进程内不会撞,多进程也不会撞。
29
+ */
30
+ let tmpSeq = 0
31
+
32
+ /** rename 的瞬时失败码:Windows 上目标正被另一个 rename 覆盖时会短暂 EPERM/EBUSY。 */
33
+ const RENAME_RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
34
+
35
+ /** 带退避重试的 rename —— 并发写同一目标时,瞬时占用不该被当成失败。 */
36
+ async function renameWithRetry(from, to, attempts = 8) {
37
+ for (let i = 1; ; i++) {
38
+ try {
39
+ return await rename(from, to)
40
+ } catch (err) {
41
+ if (i >= attempts || !RENAME_RETRY_CODES.has(err?.code)) throw err
42
+ await new Promise((r) => setTimeout(r, 4 * i))
43
+ }
44
+ }
45
+ }
46
+
20
47
  /**
21
48
  * 原子写:先写同目录临时文件,再 rename 覆盖目标。
22
49
  *
23
50
  * 直写的风险是崩在中途(断电、进程被杀、磁盘满)留下半截文件 —— frontmatter
24
51
  * 缺半边,这条记忆从此解析不出来、检索不到,而文件看上去还在。
25
52
  * 同卷 rename 是原子的:读方要么看到旧全文、要么看到新全文,不存在中间态。
26
- * 任何一步失败都不碰目标文件,临时文件收尾清掉。
53
+ * 任何一步失败都不碰目标文件,**自己那份**临时文件收尾清掉。
27
54
  */
28
55
  export async function writeFileAtomic(target, content) {
29
- const tmp = `${target}.${process.pid}.tmp`
56
+ tmpSeq += 1
57
+ const uniq = `${process.pid}-${Date.now().toString(36)}-${tmpSeq.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
58
+ const tmp = `${target}.${uniq}.tmp`
30
59
  try {
31
60
  await writeFile(tmp, content, 'utf8')
32
- await rename(tmp, target)
61
+ await renameWithRetry(tmp, target)
33
62
  } finally {
34
63
  // rename 成功后 tmp 已不存在(ENOENT),失败时把它清掉不留垃圾。
64
+ // 临时名每次唯一,所以这里删的只可能是自己那份。
35
65
  await unlink(tmp).catch(() => {})
36
66
  }
37
67
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sage-mem",
3
3
  "description": "File-based memory plugin for DeepSeek Harness (DSH) — cross-session memory in plain markdown files, with a memory star-map view, type/tag filtering, retrieval aliases, and an optional autodream pass that consolidates memories on demand or on a schedule — with per-run rollback points, a per-file change declaration (what changed and why), and a separately selectable model for the consolidation pass",
4
- "version": "0.9.2",
4
+ "version": "0.9.3",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -15,11 +15,6 @@
15
15
  "cordis.patch.yml",
16
16
  "NOTICE"
17
17
  ],
18
- "scripts": {
19
- "test": "node test/run.mjs",
20
- "build:client": "node scripts/build-client.mjs",
21
- "images": "node scripts/make-readme-images.mjs"
22
- },
23
18
  "license": "Apache-2.0",
24
19
  "engines": {
25
20
  "node": ">=18",
@@ -90,5 +85,10 @@
90
85
  "ai-agent",
91
86
  "agent",
92
87
  "claude-code"
93
- ]
94
- }
88
+ ],
89
+ "scripts": {
90
+ "test": "node test/run.mjs",
91
+ "build:client": "node scripts/build-client.mjs",
92
+ "images": "node scripts/make-readme-images.mjs"
93
+ }
94
+ }