sage-mem 2.19.1 → 2.20.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.en.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  **Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
14
14
 
15
- **Current release: `2.19.1`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
15
+ **Current release: `2.20.1`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
16
16
  [frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
17
17
 
18
18
  If it is useful to you, a Star is the most direct feedback.
@@ -744,7 +744,7 @@ No. Whether to store is judged by the model according to rules: nothing without
744
744
  Open the memory directory; it is all Markdown. The 「记忆管理」(Memory management) page in the GUI can also browse, edit and delete.
745
745
 
746
746
  **Is it safe for several DSH instances to share one memory directory?**
747
- No. Serialized writes guarantee only **in-process** ordering; there is no file lock across processes — using two instances to write to the same directory at the same time can still lose one write. This is a known boundary.
747
+ Three layers. ① **Individual memory-file writes are atomic and version-guarded** — a save that finds the file changed since it was read stops instead of silently overwriting the newer version. ② **sage-mem's own state files** (the lock table and access ledger) have their read-modify-write serialized since 2.20.0 by a short lease under the same state root, so two instances locking files or recording access no longer overwrite each other; this lock protects only sage-mem's own writes. ③ **This is not a transaction**: multi-file operations such as archiving and conflict arbitration can still stop mid-way; external editors, sync clients and git are outside the plugin's control, and lock exclusivity on network volumes is not promised. See `docs/decisions.md` D52 for the exact residual windows.
748
748
 
749
749
  **Can I do without autodream?**
750
750
  Yes, it is off by default. It and archiving are two different things: archiving is a deterministic rule (by idle days), calls no model and costs nothing.
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  > File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
16
16
 
17
- **当前发布版本:`2.19.1`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
17
+ **当前发布版本:`2.20.1`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
18
18
  [契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
19
19
 
20
20
  如果它对你有用,给个 Star 是最直接的反馈。
@@ -749,7 +749,7 @@ npm test # 全部断言(含三条守卫)
749
749
  打开记忆目录,全是 Markdown。GUI 里的「记忆管理」页也能浏览、编辑、删除。
750
750
 
751
751
  **多个 DSH 实例共用同一个记忆目录安全吗?**
752
- 不。写入串行只保证**进程内**,跨进程没有文件锁 —— 同时用两个实例写同一目录仍可能丢一次。这是已知边界。
752
+ 分三层说。① **单份记忆文件的写入是原子的**,带版本守卫的写入发现文件已变就停手,不会静默覆盖别人刚改的版本。② **sage-mem 自己维护的状态文件**(锁表、访问台账)的「读→改→写」在 2.20.0 起由同一状态根下的短租约串行,所以两个实例同时上锁、同时记账不会再互相冲掉;这把锁只保护 sage-mem 自己的写入。③ **这不是事务**:归档、裁决这类跨文件操作仍可能停在中间态;外部编辑器、同步盘、git 的写入不受插件控制,网络卷上的锁排他性也不作承诺。取舍与残留窗口见 `docs/decisions.md` D52。
753
753
 
754
754
  **能不用自动做梦吗?**
755
755
  能,它默认就是关闭的。它和归档是两件事:归档是确定性规则(按闲置天数),不调模型、不花钱。
@@ -1,15 +1,15 @@
1
1
  /**
2
- * autodream —— 门控(时间 / 会话 / 锁)与锁本身(引擎方法体)。
2
+ * autodream —— 门控(时间 / 会话 / 锁)与锁适配层。
3
3
  *
4
- * 本文件里的函数都是 `AutodreamEngine` 的方法体:`engine.js` 里保留同名同签名的方法,
5
- * 用 `xxxMod.name.call(this, …)` 转发进来 —— 所以函数体里的 `this` 就是引擎实例,
6
- * 与拆分前完全一致,没有引入任何模块级可变状态。
4
+ * 锁协议本身在 `../shared/file-lease.js`:内存状态文件与 autodream 运行锁共用同一套
5
+ * token / mtime / rename 复核语义,避免两份实现各自漂移。这里只保留 autodream 特有策略:
6
+ * 2 小时过期、legacy `dream.lock` 前置检查、`boolean + 裸 token` 的旧调用接口。
7
7
  */
8
8
 
9
9
  import { LOCK_STALE_MS, SESSION_SCAN_INTERVAL_MS } from './config.js'
10
- import { countSessionsSince, readJson } from './util.js'
11
- import { link, mkdir, open, rename, rm, stat } from 'node:fs/promises'
12
- import { randomUUID } from 'node:crypto'
10
+ import { countSessionsSince } from './util.js'
11
+ import { stat } from 'node:fs/promises'
12
+ import { createFileLease } from '../shared/file-lease.js'
13
13
 
14
14
  /**
15
15
  * 三级门控(顺序即成本顺序)。
@@ -49,189 +49,45 @@ export async function gate() {
49
49
 
50
50
  // ────────────────────────────── 锁 ──────────────────────────────
51
51
 
52
+ function leaseFor(engine) {
53
+ return createFileLease({
54
+ lockPath: engine.lockPath,
55
+ staleMs: LOCK_STALE_MS,
56
+ waitMs: 0,
57
+ meta: () => ({ runId: engine.runId }),
58
+ log: (level, msg) => engine.log?.(level, msg),
59
+ })
60
+ }
61
+
62
+ /**
63
+ * 抢 autodream 运行锁。
64
+ *
65
+ * 保持旧接口:成功 `true`、抢不到 `false`;token 仍是裸字符串存在 `this.lockToken`。
66
+ * `dream.lock` 是升级过渡期的旧锁文件 —— 它一样在改 memory,所以新鲜时就不尝试。
67
+ */
52
68
  export async function acquireLock() {
53
- await mkdir(this.home, { recursive: true })
54
- // 改名过渡期:旧版进程的 `dream.lock` 本插件看不见,但它一样在改 memory。
55
- // 新鲜(未过期)就先拒绝——正常升级流程会重启进程,这条只兜「新旧并行」那一小段窗口。
56
69
  const legacy = await stat(this.legacyLockPath).catch(() => null)
57
70
  if (legacy && Date.now() - legacy.mtimeMs <= LOCK_STALE_MS) return false
58
- /** 本次持有的凭据:释放时靠它认「这把锁还是我的吗」。 */
59
- const token = randomUUID()
60
- try {
61
- const fh = await open(this.lockPath, 'wx')
62
- await fh.write(JSON.stringify({ pid: process.pid, at: Date.now(), runId: this.runId, token }))
63
- await fh.close()
64
- this.lockToken = token
65
- return true
66
- } catch (err) {
67
- if (err?.code !== 'EEXIST') throw err
68
- const info = await stat(this.lockPath).catch(() => null)
69
- if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
70
- /**
71
- * 上次进程崩了留下的锁:清掉重来(不然 autodream 永远回不来)。
72
- *
73
- * 「判断过期 → 删掉 → 重来」这三步之间有窗口:另一个进程可能在这中间**抢到了这把锁**。
74
- * 所以改用 `rename` 抢占(原子,同一把锁只有一个进程能移走)。移走之后**两道复核**,
75
- * 缺一不可:
76
- *
77
- * ① `mtime` 仍然超期 —— 这是**真正的判据**。`stat` 判过期与读 `before` 之间还有一次
78
- * FS 操作的缝:若这期间别人已完成抢占并建了一把**新鲜**锁,我们读到的 `before`
79
- * 就是它,token 比对会放行,于是两个实例都以为自己拿到了(实测能复现)。
80
- * ② `token` 与读到的 `before` 一致 —— 防「内容被换过」。
81
- *
82
- * 任一条不成立:说明我们移走的不是自己判定的那把过期锁,**还回去、认输**。
83
- */
84
- const before = await readJson(this.lockPath)
85
- const grabbed = `${this.lockPath}.stale-${randomUUID().replace(/-/g, '')}`
86
- const moveErr = await rename(this.lockPath, grabbed).then(
87
- () => null,
88
- (err) => err,
89
- )
90
- if (moveErr) {
91
- /**
92
- * ⚠️ 失败要分流,否则「占用/权限类失败」会让这条路径**递归到自己爆栈**
93
- * (旧写法 `if (!moved) return this.acquireLock()`:锁没被移走,重来再走同一条分支,
94
- * 一路递归下去)。只有 ENOENT(别人抢先移走了、锁位确实空着)重来才有意义。
95
- */
96
- if (moveErr?.code === 'ENOENT') return this.acquireLock() // 别人抢先移走了,直接重来
97
- this.log?.('warn', `抢占过期锁失败(rename ${moveErr?.code ?? moveErr}):${this.lockPath} 没能移走;${moveErr?.message ?? moveErr}`)
98
- return false
99
- }
100
- const movedInfo = await stat(grabbed).catch(() => null)
101
- const after = await readJson(grabbed)
102
- const stillStale = movedInfo !== null && Date.now() - movedInfo.mtimeMs > LOCK_STALE_MS
103
- if (!stillStale || after?.token !== before?.token) {
104
- // 还回去**不能覆盖**已经存在的锁(Windows 的 rename 会直接盖掉别人刚建的新锁)。
105
- // 用 `link` 还原:目标存在时它报 EEXIST,不会覆盖任何东西。
106
- const restored = await link(grabbed, this.lockPath).then(
107
- () => true,
108
- () => false,
109
- )
110
- if (restored) {
111
- // 名字已经回到原位,这个私有名可以收掉了。
112
- await rm(grabbed, { force: true }).catch((err) => {
113
- this.log?.('warn', `锁抢占复核不通过且遗留文件清不掉:${grabbed}(${err?.message ?? err})`)
114
- })
115
- } else {
116
- /**
117
- * ⚠️ 还回失败(锁位置已被第三方占用)时**不能删 `grabbed`**。
118
- *
119
- * 它是我们误移走的那份锁的唯一落身处,删掉等于「既没还回去、又把人家的凭据抹了」
120
- * —— 与 R05 同一个根因。留着它:名字带 `.stale-` 后缀,不会被任何逻辑当成锁路径,
121
- * 内容还在磁盘上,排错时看得见。
122
- */
123
- this.log?.('warn', `锁抢占复核不通过,且锁位置已被占用 —— 未覆盖它;被移走的那份留在 ${grabbed}`)
124
- }
125
- return false
126
- }
127
- await rm(grabbed, { force: true }).catch((err) => {
128
- this.log?.('warn', `过期锁清理失败(残留 ${grabbed}):${err?.message ?? err}`)
129
- })
130
- return this.acquireLock()
131
- }
71
+
72
+ const got = await leaseFor(this).acquire()
73
+ if (!got.ok) {
74
+ // lock_busy 是正常的「别人在跑」,不刷 warn;真正的 IO 异常才值得留痕。
75
+ if (got.code !== 'lock_busy') this.log?.('warn', `获取运行锁失败:${got.reason ?? got.code}`)
132
76
  return false
133
77
  }
78
+ this.lockToken = got.token
79
+ return true
134
80
  }
135
81
 
136
82
  /**
137
- * 释放锁 —— **只删自己那一把**。
138
- *
139
- * 旧实现是无条件 `rm`:一个慢下来的持有者(比如刚跑完两小时的整理)释放时,
140
- * 会把**别人中途抢到的新锁**删掉 —— 于是两个整理进程同时往里写,而两边都以为自己独占。
141
- * 判据落在锁文件里的 `token` 上:不是自己的,一个字都不动。
142
- *
143
- * ⚠️ 光有 token 判据还不够(2026-10-12 复审 R05):「读锁 → 比 token → rm」是三次独立
144
- * 系统调用,**比较通过之后、rm 之前**别人完全可能抢走过期锁并写入新 token(实测用
145
- * 两个真实进程 + IPC 暂停点即可稳定复现:新持有者拿到了锁,随即被旧持有者删掉)。
146
- * 判据正确的写法必须让「删」这个动作本身带上身份前提 —— 这里复用 `acquireLock` 里
147
- * 抢占过期锁的同一套手法:
148
- *
149
- * ① `rename(lockPath, 私有名)` —— **原子地**把锁文件移走。同一把锁只可能被一个进程移走;
150
- * ② 读移走的那份,token 是**自己的** → `rm` 私有名,释放完成;
151
- * ③ token **不是自己的**(说明我们移走的是别人刚建的新锁)→ 用 `link()` 还回去。
152
- * `link` 在锁位置已被占用时报 EEXIST,**绝不覆盖**;还回去了就什么都不少。
153
- *
154
- * 顺序是**三层**:预检(廉价,挡住绝大多数)→ `rename` 抢占(原子)→ 复核 + 还回(兜换主)。
155
- * 三层缺一不可:只有预检就是原来的 R05;只有 rename + 复核则会留下「锁位空着的窗口」——
156
- * 第三方在那个窗口里 `open(wx)` 能直接拿到锁(三实例实测),所以预检必须先做。
157
- *
158
- * 两条已知残留,说清楚不藏:
159
- * · 预检通过之后、`rename` 之前换主 → 移走别人的锁 → 复核发现 → `link` 还回(不会删错东西);
160
- * 若此刻锁位已被第三方占用,还回失败,那份锁会**留在 `.released-*`**(内容不丢,可人工捞,
161
- * 不会被任何路径当成锁)。
162
- * · 进程在本函数中途被 kill → 锁位可能空着,后来者免过期直接拿到锁。这是「崩溃」的代价,
163
- * 与「两把锁同时有效」不同:那时没有任何进程会以为自己还持着已被移走的那把。
164
- *
165
- * ⚠️ 边界说清楚:`token` 明文躺在锁文件里,**它不是秘密**,防的是「协作的两个实例各跑各的」
166
- * 这类误删,不防「能读这个目录的对手」—— 那种对手本来就能直接删锁文件。
83
+ * 释放运行锁。不是自己的 token 一个字节都不动;IO 失败保留 token,下一次还能再试。
167
84
  */
168
85
  export async function releaseLock() {
169
- const token = this.lockToken
170
- // 没持有过(acquireLock 从没成功过)→ 什么都不做。旧实现会在这里删掉别人的锁。
171
- if (!token) return
172
- /**
173
- * ① **廉价预检**:锁位上现在这把还是我的吗?不是就**一个动作都不做**。
174
- *
175
- * 这一步不能省(复审复核实测的三实例反例):只靠「rename 移走 + 复核 + 还回」的话,
176
- * 从 `rename` 成功到 `link` 还回之间,**锁位置是空的** —— 第三方在这个窗口里
177
- * `open(wx)` 能直接拿到锁,而原来那把(B 的)还躺在 `.released-*` 里;
178
- * 终态是「B 以为独占、C 也拿着锁」,正是 R05 要防的两个整理进程同时写。
179
- * 预检把绝大多数情况挡在 `rename` 之前(旧实现本来就有这一步,不该丢),
180
- * `rename + 复核 + 还回` 只用来兜「预检通过之后才换主」那一小段。
181
- */
182
- const head = await readJson(this.lockPath)
183
- if (!head || head.token !== token) {
184
- this.lockToken = ''
185
- return
186
- }
187
- const grabbed = `${this.lockPath}.released-${randomUUID().replace(/-/g, '')}`
188
- const moveErr = await rename(this.lockPath, grabbed).then(
189
- () => null,
190
- (err) => err,
191
- )
192
- if (moveErr) {
193
- /**
194
- * ⚠️ 这里**必须分流**(复审复核实测,真机 Windows):`rename` 失败的原因不只有
195
- * 「锁已经不在」。锁文件被占用(AV / 同步盘 / 只读共享)时报 EBUSY / EPERM / EACCES,
196
- * 那时锁**还留在盘上**,而旧写法把它和 ENOENT 混成一个分支、清掉 token 就返回 ——
197
- * 一行日志都没有,engine 以为自己释放了,autodream 却被自己的判据挡满 LOCK_STALE_MS。
198
- * `util.js` 头注那条「非 ENOENT 的失败必须落到日志」正在这条路上。
199
- */
200
- if (moveErr?.code === 'ENOENT') {
201
- // 锁确实不在了(另一实例抢先释放 / 被人工清掉):没有可删的东西,也不算失败。
202
- this.lockToken = ''
203
- return
204
- }
205
- this.log?.('warn', `释放锁失败(rename ${moveErr?.code ?? moveErr}):${this.lockPath} 没能移走,锁可能仍在盘上;${moveErr?.message ?? moveErr}`)
206
- // 保留 lockToken:锁大概还在,下次再试;也让调用方看得见这次没释放成功。
207
- return
208
- }
209
- const held = await readJson(grabbed)
210
- if (held?.token !== token) {
211
- // 预检之后、移走之前被换主了:移走的是**别人**的锁,还回去。`link` 不覆盖已存在的锁位置。
212
- const restored = await link(grabbed, this.lockPath).then(
213
- () => true,
214
- () => false,
215
- )
216
- if (restored) {
217
- await rm(grabbed, { force: true }).catch((err) => {
218
- this.log?.('warn', `释放锁:归还成功后残留文件清不掉:${grabbed}(${err?.message ?? err})`)
219
- })
220
- } else {
221
- /**
222
- * ⚠️ 归还失败时**不能删 `grabbed`**:那是被我们误移走的那份锁的唯一落身处。
223
- * 删掉它就成了「既没还回去、又把人家的凭据抹了」—— 与 R05 同一个根因。
224
- * 名字带 `.released-` 后缀,不会在任何路径上被当成锁;内容留着,排错时看得见。
225
- */
226
- this.log?.('warn', `释放锁:移走的不是自己的锁,且锁位置已被占用 —— 未覆盖它;被移走的那份留在 ${grabbed}`)
227
- }
86
+ if (!this.lockToken) return
87
+ const result = await leaseFor(this).release(this.lockToken)
88
+ if (result.ok) {
228
89
  this.lockToken = ''
229
90
  return
230
91
  }
231
- await rm(grabbed, { force: true }).catch((err) => {
232
- this.log?.('warn', `释放锁:删自己的私有名失败(${err?.message ?? err});残留 ${grabbed}`)
233
- })
234
- this.lockToken = ''
92
+ this.log?.('warn', `释放运行锁失败:${result.reason ?? result.code};token 保留以便下次重试`)
235
93
  }
236
-
237
- // ────────────────────────────── 回滚点(快照) ──────────────────────────────
@@ -17,9 +17,10 @@ import { ARCHIVE_DIR_NAME } from './scan.js'
17
17
  import { isMemoryEntry } from './naming.js'
18
18
  import { parseFrontmatter } from './frontmatter.js'
19
19
  import { createWriteQueue, writeFileAtomic } from './util.js'
20
- import { mkdir, readFile, readdir } from 'node:fs/promises'
20
+ import { mkdir, readFile, readdir, stat } from 'node:fs/promises'
21
21
  import { dirname, join } from 'node:path'
22
22
  import { nameKey } from './naming.js'
23
+ import { createFileLease } from '../shared/file-lease.js'
23
24
 
24
25
  /** 台账文件:状态根下,与记忆文件分开。**用默认记忆目录时**就是它。 */
25
26
  export const ACCESS_LEDGER_FILE = join(STATE_ROOT, 'access.json')
@@ -76,6 +77,19 @@ export function injectedAt(value) {
76
77
  /** 落盘节流:内存先累计,最多每 30 秒写一次盘。 */
77
78
  export const ACCESS_FLUSH_INTERVAL_MS = 30 * 1000
78
79
 
80
+ /** 状态短租约:临界区只含一份小 JSON 的读改写。 */
81
+ const STATE_LEASE_STALE_MS = 5000
82
+ const STATE_LEASE_WAIT_MS = 2000
83
+
84
+ function stateLeaseFor(ledgerFile) {
85
+ return createFileLease({
86
+ lockPath: join(dirname(ledgerFile), 'write.lock'),
87
+ staleMs: STATE_LEASE_STALE_MS,
88
+ waitMs: STATE_LEASE_WAIT_MS,
89
+ meta: () => ({ purpose: 'access-ledger' }),
90
+ })
91
+ }
92
+
79
93
  /**
80
94
  * 开了才出声:台账写不进去是**静默降级**,没有这个开关就查不出「为什么阈值算不准」。
81
95
  *
@@ -103,8 +117,19 @@ const enqueueFlush = createWriteQueue()
103
117
  /** 内存累计(尚未落盘):文件名 → 各字段的增量(见 `record` 的合并语义)。 */
104
118
  let pending = new Map()
105
119
  let flushTimer = null
120
+ let leaseRetryTimer = null
106
121
  let lastFlushAt = 0
107
122
 
123
+ /** 抢不到租约是正常竞争,不走 scheduleFlush(那会因 lastFlushAt 未前进而立即重入)。 */
124
+ function scheduleLeaseRetry() {
125
+ if (leaseRetryTimer) return
126
+ leaseRetryTimer = setTimeout(() => {
127
+ leaseRetryTimer = null
128
+ flushAccess().catch(() => {})
129
+ }, 1000 + Math.floor(Math.random() * 2000))
130
+ if (typeof leaseRetryTimer.unref === 'function') leaseRetryTimer.unref()
131
+ }
132
+
108
133
  /**
109
134
  * 把一次观测并进内存增量表。
110
135
  *
@@ -253,11 +278,22 @@ export async function flushAccess(memoryDir = MEMORY_DIR) {
253
278
  async function flushAccessLocked(memoryDir) {
254
279
  // 排队期间可能已经被前一个任务刷掉了。
255
280
  if (pending.size === 0) return { ok: true, written: 0 }
256
- const batch = pending
257
- pending = new Map()
281
+ const file = ledgerFileFor(memoryDir)
282
+ // 目录扫描放在锁外:它可能耗时,而租约只该覆盖「一份小 JSON 的读改写」。
283
+ const alive = await currentMemoryNames(memoryDir)
284
+ const lease = stateLeaseFor(file)
285
+ const got = await lease.acquire()
286
+ if (!got.ok) {
287
+ scheduleLeaseRetry()
288
+ return { ok: false, code: 'lock_busy', error: got.reason ?? 'state lease busy' }
289
+ }
290
+
291
+ let batch = null
258
292
  try {
259
- // 台账必须与**这次回收所依据的那个目录**配套(见 ledgerFileFor 的注释)。
260
- const file = ledgerFileFor(memoryDir)
293
+ // 等到锁之后才摘 batch:抢锁失败时 pending 根本没被碰过。
294
+ if (pending.size === 0) return { ok: true, written: 0 }
295
+ batch = pending
296
+ pending = new Map()
261
297
  const onDisk = await readAccessLedger(file)
262
298
  // 逐字段合并(`readAccessLedger` 已经归一成 v2 条目,不用再分代)。
263
299
  // 语义与内存里的 `record` 一致:时间戳取较晚、`use` 累加、`readRev` 跟 `read` 走。
@@ -271,22 +307,30 @@ async function flushAccessLocked(memoryDir) {
271
307
  use: (cur.use ?? 0) + (patch.use ?? 0),
272
308
  }
273
309
  }
274
- const alive = await currentMemoryNames(memoryDir)
275
310
  if (alive) {
276
311
  for (const key of Object.keys(onDisk)) {
277
- if (!alive.has(key)) delete onDisk[key]
312
+ if (alive.has(key)) continue
313
+ // alive 是抢锁前的快照:这期间别的实例可能刚建了同名文件。持锁后再按单文件
314
+ // 确认一次(根目录 + archive/),存在就保留,不存在才回收。use 是次数不是时间,
315
+ // 这里根本不用它当判据。
316
+ const exists = await stat(join(memoryDir, key)).then(
317
+ () => true,
318
+ (err) => err?.code !== 'ENOENT',
319
+ ) || await stat(join(memoryDir, ARCHIVE_DIR_NAME, key)).then(
320
+ () => true,
321
+ (err) => err?.code !== 'ENOENT',
322
+ )
323
+ if (!exists) delete onDisk[key]
278
324
  }
279
325
  }
280
326
  // 状态目录是插件自己的地盘,缺了可以建(autodream 的配置也存在这儿)。
281
- // 建不出来(只读、父路径不是目录)就走 catch 静默降级。
282
327
  await mkdir(dirname(file), { recursive: true })
283
- // 落盘一律写 v2(哪怕读进来的是 v1):老格式只在读端兼容,写端不扩散。
284
328
  await writeFileAtomic(file, JSON.stringify({ v: ACCESS_SCHEMA_VERSION, files: onDisk }, null, 2))
285
329
  lastFlushAt = Date.now()
286
330
  return { ok: true, written: batch.size, reclaimed: alive ? true : false }
287
331
  } catch (err) {
288
332
  // 放回内存时**逐字段并回去**,不能整条覆盖 —— 否则失败重试会把期间新攒的字段冲掉。
289
- for (const [name, patch] of batch) {
333
+ for (const [name, patch] of batch ?? []) {
290
334
  const cur = pending.get(name) ?? {}
291
335
  const read = Math.max(cur.read ?? 0, patch.read ?? 0)
292
336
  pending.set(name, {
@@ -296,11 +340,13 @@ async function flushAccessLocked(memoryDir) {
296
340
  use: (cur.use ?? 0) + (patch.use ?? 0),
297
341
  })
298
342
  }
299
- // 静默降级:注入是插件最核心的事,台账写不进去不许把它拖下水。开了 DEBUG 才出声。
300
- // 2.2.1:前缀归一(原来是 `[sage-mem][debug] `)。本函数签名里没有 ctx,
301
- // 所以用 console.warn —— 与 warnLog 的 fallback 形态一致。
302
343
  if (debugEnabled()) console.warn(`sage-mem: access ledger flush failed: ${err?.message ?? err}`)
303
344
  return { ok: false, error: err?.message ?? String(err) }
345
+ } finally {
346
+ const released = await lease.release(got.token)
347
+ if (!released.ok && debugEnabled()) {
348
+ console.warn(`sage-mem: release access state lease failed: ${released.reason ?? released.code}`)
349
+ }
304
350
  }
305
351
  }
306
352
 
@@ -308,6 +354,8 @@ async function flushAccessLocked(memoryDir) {
308
354
  export function __resetAccessPendingForTest() {
309
355
  pending = new Map()
310
356
  flushTimer = null
357
+ if (leaseRetryTimer) clearTimeout(leaseRetryTimer)
358
+ leaseRetryTimer = null
311
359
  lastFlushAt = 0
312
360
  }
313
361
 
@@ -19,11 +19,12 @@
19
19
  * 自动归档会把**受保护**的记忆当成没锁继续删。现在只有 ENOENT 算「确实没有锁」;
20
20
  * 坏 JSON / 权限失败 / 路径是目录……一律 `status:'unknown'`,危险操作据此暂停。
21
21
  */
22
- import { mkdir, readFile } from 'node:fs/promises'
22
+ import { readFile } from 'node:fs/promises'
23
23
  import { dirname, join } from 'node:path'
24
24
  import { nameKey } from './naming.js'
25
25
  import { resolveStateRoot } from './config.js'
26
26
  import { createWriteQueue, writeFileAtomic } from './util.js'
27
+ import { createFileLease } from '../shared/file-lease.js'
27
28
 
28
29
  /**
29
30
  * 锁表文件:状态根下,与记忆文件分开。
@@ -37,12 +38,22 @@ export function lockFileOf(memoryDir, stateRoot) {
37
38
  return join(root, 'locked.json')
38
39
  }
39
40
 
41
+ /** 状态文件的短租约:临界区只含一份小 JSON 的读改写。 */
42
+ const STATE_LEASE_STALE_MS = 5000
43
+ const STATE_LEASE_WAIT_MS = 2000
44
+
45
+ function stateLeaseFor(memoryDir) {
46
+ return createFileLease({
47
+ lockPath: join(dirname(lockFileOf(memoryDir)), 'write.lock'),
48
+ staleMs: STATE_LEASE_STALE_MS,
49
+ waitMs: STATE_LEASE_WAIT_MS,
50
+ meta: () => ({ purpose: 'locked-json' }),
51
+ })
52
+ }
53
+
40
54
  /**
41
55
  * 锁表的**进程内串行队列**,按锁表路径分键(不同记忆目录互不阻塞)。
42
- *
43
- * ⚠️ 边界与 `util.js` 的说明一致:进程内串行,不是跨进程文件锁。真实并发(面板 remote、
44
- * 模型工具、归档策略)都在同一个插件进程里;同时开两个 DSH 实例写同一个记忆目录时仍可能
45
- * 丢一次 —— 那要另加文件锁,本版明确不做。
56
+ * 跨进程互斥由 `stateLeaseFor()` 的短租约负责;队列只减少本进程内无谓争抢。
46
57
  */
47
58
  const lockQueues = new Map()
48
59
  function lockQueueFor(file) {
@@ -122,29 +133,39 @@ export async function isLocked(memoryDir, name) {
122
133
  /**
123
134
  * 上锁 / 解锁。
124
135
  *
125
- * RMW 全程在**按锁表路径分键的进程内队列**里:读最新表 → 改一项 → 原子写回。
126
- * 并发的不同文件因此逐条合并,不再互相覆盖。
127
- *
128
- * 坏表上**拒绝写入**(`{ok:false, code:'lock_table_unknown'}`),而不是把表重置成空表 ——
129
- * 后者会静默抹掉用户的全部保护状态,比「这次没锁上」严重得多。
136
+ * 读最新表 → 改一项 → 原子写回,整段放进按路径分键的进程内队列,并由状态根
137
+ * `<stateRoot>/write.lock` 的短租约串行到**跨进程**。锁表损坏时 fail-closed。
130
138
  */
131
139
  export async function setLocked(memoryDir, name, locked) {
132
140
  const key = nameKey(name)
133
141
  const file = lockFileOf(memoryDir)
134
142
  return lockQueueFor(file)(async () => {
135
- const read = await readLockTable(memoryDir)
136
- if (read.status === 'unknown') {
143
+ const lease = stateLeaseFor(memoryDir)
144
+ const got = await lease.acquire()
145
+ if (!got.ok) {
137
146
  return {
138
147
  ok: false,
139
- code: 'lock_table_unknown',
140
- error: `sage-mem: 锁表不可读(${read.reason}),本次没有写入,也不会把它重置成空表:${name}`,
148
+ code: got.code === 'lock_busy' ? 'lock_busy' : 'lock_io',
149
+ error: `sage-mem: 无法取得状态写租约(${got.reason ?? got.code}),本次没有写入:${name}`,
150
+ }
151
+ }
152
+ try {
153
+ const read = await readLockTable(memoryDir)
154
+ if (read.status === 'unknown') {
155
+ return {
156
+ ok: false,
157
+ code: 'lock_table_unknown',
158
+ error: `sage-mem: 锁表不可读(${read.reason}),本次没有写入,也不会把它重置成空表:${name}`,
159
+ }
141
160
  }
161
+ const table = { ...read.table }
162
+ if (locked) table[key] = true
163
+ else delete table[key]
164
+ await writeFileAtomic(file, JSON.stringify(table, null, 2) + '\n')
165
+ return { ok: true, file: name, locked: !!locked }
166
+ } finally {
167
+ const released = await lease.release(got.token)
168
+ if (!released.ok) console.warn(`sage-mem: 释放锁表写租约失败(${released.reason ?? released.code})`)
142
169
  }
143
- const table = { ...read.table }
144
- if (locked) table[key] = true
145
- else delete table[key]
146
- await mkdir(dirname(file), { recursive: true })
147
- await writeFileAtomic(file, JSON.stringify(table, null, 2) + '\n')
148
- return { ok: true, file: name, locked: !!locked }
149
170
  })
150
171
  }
@@ -305,9 +305,9 @@ export async function retireTaken(taken) {
305
305
  * · 索引 `MEMORY.md`(复审 R07:两条并发归档各摘一行,最后总留一条悬空)
306
306
  * · 访问台账 `access.json`(复审复核点出:debounce 定时器与运行前强刷撞上时丢时间戳)
307
307
  *
308
- * ⚠️ 边界:**进程内**串行,不是跨进程锁。真实并发(界面 remote、模型工具、归档策略、
309
- * 定时器)都在同一个插件进程里,所以覆盖得住;同时开两个 DSH 实例写同一个记忆目录时
310
- * 仍可能丢一次 —— 那要另加文件锁,复杂度与误伤面都不划算,这里明确不做。
308
+ * ⚠️ 边界:本队列只做**进程内**串行。2.20.0 起,`locked.json` 与 `access.json`
309
+ * 的整份 RMW 另由 `lib/shared/file-lease.js` 的跨进程短租约兜住;其它整份 RMW
310
+ *(例如 `MEMORY.md`、settings)仍只靠本队列,不在这条跨进程保证里。
311
311
  *
312
312
  * ⚠️ **队内函数不许再调同一个队列上的函数**(会自己等自己,永久挂住)。
313
313
  *
@@ -56,6 +56,9 @@ export const CODES = Object.freeze({
56
56
  locked: 'locked',
57
57
  lock_unknown: 'lock_unknown',
58
58
  lock_table_unknown: 'lock_table_unknown',
59
+ lock_busy: 'lock_busy',
60
+ lock_io: 'lock_io',
61
+ retry: 'retry',
59
62
  unverified_overwrite: 'unverified_overwrite',
60
63
  // ── 裁段(2.10.1 体积治理)──
61
64
  // 「裁一段下来归档」是一条独立的写路径(trim-archive),它的失败码不能借用整文件归档那套:
@@ -0,0 +1,204 @@
1
+ /**
2
+ * 一个进程间协作的文件租约(**不是分布式事务**)。
3
+ *
4
+ * 协议只解决一件事:让同一台机器、同一个本地卷上的多个 sage-mem 进程,不会同时改写
5
+ * 同一份状态 JSON。它不神奇地让多文件操作变成事务,也不防外部编辑器 / 同步盘 / git。
6
+ *
7
+ * 不变量:
8
+ * - `open(path, 'wx')` 是唯一的创建判定;rename 只用于抢占,绝不当条件替换。
9
+ * - 过期只看锁文件的 **mtime**(JSON 里的 at 仅供诊断,永不推翻 mtime)。
10
+ * - 抢占过期锁后必须双重复核(mtime 仍过期 **且** token 与移走前一致);任一不成立
11
+ * 就用 link 还回。还回不许覆盖别人的新锁。
12
+ * - 释放只删自己 token 那把;预检不过一个动作都不做。
13
+ * - 后缀 `.stale-*` / `.released-*` 是排错落点,永远不会被当成有效锁。
14
+ */
15
+
16
+ import { link, mkdir, open, readFile, rename, rm, stat } from 'node:fs/promises'
17
+ import { dirname } from 'node:path'
18
+ import { randomUUID } from 'node:crypto'
19
+
20
+ async function readJson(path) {
21
+ try {
22
+ return JSON.parse(await readFile(path, 'utf8'))
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
29
+
30
+ /**
31
+ * @param {object} opts
32
+ * @param {string} opts.lockPath 锁文件绝对路径
33
+ * @param {number} opts.staleMs 超过这个 mtime 年龄视为崩溃残留
34
+ * @param {number} [opts.waitMs=0] 抢不到时最多等多久(0 = 立即返回 busy)
35
+ * @param {number[]} [opts.backoffMs=[4,12,36,80]] 每次失败后的等待序列
36
+ * @param {() => object} [opts.meta] 额外写进锁文件的诊断字段
37
+ * @param {(level:string,msg:string)=>void} [opts.log]
38
+ */
39
+ export function createFileLease({
40
+ lockPath,
41
+ staleMs,
42
+ waitMs = 0,
43
+ backoffMs = [4, 12, 36, 80],
44
+ meta = () => ({}),
45
+ log = () => {},
46
+ }) {
47
+ if (!lockPath || !Number.isFinite(staleMs) || staleMs <= 0) {
48
+ throw new Error('createFileLease: lockPath 与 staleMs 必填')
49
+ }
50
+
51
+ const ownerMeta = () => {
52
+ try {
53
+ const value = meta()
54
+ return value && typeof value === 'object' ? value : {}
55
+ } catch {
56
+ return {}
57
+ }
58
+ }
59
+
60
+ /** 原子创建自己的锁文件;EEXIST 是正常的竞争结果。 */
61
+ async function tryCreate(token) {
62
+ let fh = null
63
+ let created = false
64
+ try {
65
+ fh = await open(lockPath, 'wx')
66
+ created = true
67
+ await fh.write(JSON.stringify({ ...ownerMeta(), pid: process.pid, at: Date.now(), token }))
68
+ await fh.close()
69
+ fh = null
70
+ return { ok: true, token }
71
+ } catch (err) {
72
+ if (fh) await fh.close().catch(() => {})
73
+ // 自己创建后写入 / 关闭失败:清掉半截锁,别把后来者永久挡在外面。
74
+ if (created) await rm(lockPath, { force: true }).catch(() => {})
75
+ if (err?.code === 'EEXIST') {
76
+ return { ok: false, code: 'lock_busy', reason: '另一个进程正持有锁' }
77
+ }
78
+ return { ok: false, code: 'lock_io', reason: `创建锁失败:${err?.message ?? err}` }
79
+ }
80
+ }
81
+
82
+ /** 有一次尝试;busy / retry / io 三类结果由 acquire 决定是否再试。 */
83
+ async function acquireOnce() {
84
+ try {
85
+ await mkdir(dirname(lockPath), { recursive: true })
86
+ } catch (err) {
87
+ return { ok: false, code: 'lock_io', reason: `创建锁目录失败:${err?.message ?? err}` }
88
+ }
89
+ const token = randomUUID()
90
+ const fresh = await tryCreate(token)
91
+ if (fresh.ok || fresh.code !== 'lock_busy') return fresh
92
+
93
+ const info = await stat(lockPath).catch(() => null)
94
+ if (!info) return { ok: false, code: 'retry', reason: '锁刚消失' }
95
+ if (Date.now() - info.mtimeMs <= staleMs) {
96
+ return { ok: false, code: 'lock_busy', reason: '另一个进程正持有锁' }
97
+ }
98
+
99
+ // 上面的 info 可能已经是旧快照:rename 前再确认一次,绝不能拿旧判断去移走
100
+ // 别人刚创建的新锁。这是并发接管过期锁时「两个赢家」的第一道闸。
101
+ const recheck = await stat(lockPath).catch(() => null)
102
+ if (!recheck) return { ok: false, code: 'retry', reason: '锁在复核前消失' }
103
+ if (Date.now() - recheck.mtimeMs <= staleMs) {
104
+ return { ok: false, code: 'lock_busy', reason: '复核时锁已换成新鲜锁' }
105
+ }
106
+
107
+ const before = await readJson(lockPath)
108
+ const grabbed = `${lockPath}.stale-${randomUUID().replace(/-/g, '')}`
109
+ const moveErr = await rename(lockPath, grabbed).then(
110
+ () => null,
111
+ (err) => err,
112
+ )
113
+ if (moveErr) {
114
+ if (moveErr?.code === 'ENOENT') return { ok: false, code: 'retry', reason: '别人抢先移走了' }
115
+ return { ok: false, code: 'lock_io', reason: `抢占过期锁失败(${moveErr?.code ?? moveErr})` }
116
+ }
117
+
118
+ const movedInfo = await stat(grabbed).catch(() => null)
119
+ const after = await readJson(grabbed)
120
+ const stillStale = movedInfo !== null && Date.now() - movedInfo.mtimeMs > staleMs
121
+ if (!stillStale || after?.token !== before?.token) {
122
+ const restored = await link(grabbed, lockPath).then(
123
+ () => true,
124
+ () => false,
125
+ )
126
+ if (restored) {
127
+ await rm(grabbed, { force: true }).catch(() => {})
128
+ } else {
129
+ log('warn', `锁抢占复核不通过,且锁位已被占用;被移走的那份留在 ${grabbed}`)
130
+ }
131
+ return { ok: false, code: 'lock_busy', reason: '复核时锁已被换主' }
132
+ }
133
+
134
+ // 复核通过后**立刻**在同一轮创建新锁。旧实现先删 grabbed 再 return retry,
135
+ // 让「锁位置为空」的窗口跨了两次事件循环 —— 另一个 fast-path 正是从那里钻进来的。
136
+ const taken = await tryCreate(token)
137
+ await rm(grabbed, { force: true }).catch(() => {})
138
+ return taken
139
+ }
140
+
141
+ /**
142
+ * 抢锁。返回 `{ok:true, token}` 或 `{ok:false, code, reason}`。
143
+ * 超过 waitMs 或重试序列用尽即返回 busy,不会无限递归。
144
+ */
145
+ async function acquire() {
146
+ const deadline = Date.now() + Math.max(0, waitMs)
147
+ let last = { ok: false, code: 'lock_busy', reason: '未尝试' }
148
+ for (let i = 0; i < 128; i += 1) {
149
+ last = await acquireOnce()
150
+ if (last.ok) return last
151
+ if (last.code === 'lock_io') return last
152
+ // 已清掉过期锁 / 别人刚移走:立刻再做一次。若调用方允许等,也加一点退避,
153
+ // 避免释放窗口里的瞬时 retry 在一微秒内把重试次数烧完。
154
+ if (last.code === 'retry' && waitMs <= 0) continue
155
+ if (last.code === 'lock_busy' && waitMs <= 0) return last
156
+ const base = backoffMs[Math.min(i, backoffMs.length - 1)] ?? 0
157
+ // 两个进程用同一串退避会同步醒来、反复互相撞(实测首轮只差 1/80)。
158
+ // 加 0..base 的抖动,打散轮询节拍;waitMs=0 的 gate 不走这里。
159
+ const wait = base > 0 ? base + Math.floor(Math.random() * (base + 1)) : 1
160
+ const left = deadline - Date.now()
161
+ if (left <= 0) return last
162
+ await delay(Math.min(wait, left))
163
+ }
164
+ return last
165
+ }
166
+
167
+ /**
168
+ * 释放 token 对应那把锁。幂等;不是自己的锁绝不删。
169
+ * @returns {Promise<{ok:boolean, code?:string}>}
170
+ */
171
+ async function release(token) {
172
+ if (!token) return { ok: true }
173
+ const head = await readJson(lockPath)
174
+ if (!head || head.token !== token) return { ok: true }
175
+
176
+ const grabbed = `${lockPath}.released-${randomUUID().replace(/-/g, '')}`
177
+ const moveErr = await rename(lockPath, grabbed).then(
178
+ () => null,
179
+ (err) => err,
180
+ )
181
+ if (moveErr) {
182
+ if (moveErr?.code === 'ENOENT') return { ok: true }
183
+ return { ok: false, code: 'io_error', reason: `释放锁失败(${moveErr?.code ?? moveErr})` }
184
+ }
185
+
186
+ const held = await readJson(grabbed)
187
+ if (held?.token !== token) {
188
+ const restored = await link(grabbed, lockPath).then(
189
+ () => true,
190
+ () => false,
191
+ )
192
+ if (restored) {
193
+ await rm(grabbed, { force: true }).catch(() => {})
194
+ } else {
195
+ log('warn', `释放时移走的不是自己的锁,且锁位已被占用;被移走的那份留在 ${grabbed}`)
196
+ }
197
+ return { ok: true }
198
+ }
199
+ await rm(grabbed, { force: true }).catch(() => {})
200
+ return { ok: true }
201
+ }
202
+
203
+ return { acquire, release }
204
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sage-mem",
3
3
  "description": "Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.",
4
- "version": "2.19.1",
4
+ "version": "2.20.1",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",