@yolk_vat-y/dsh-project-memory 0.6.5 → 0.6.7

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/src/store.js CHANGED
@@ -2,7 +2,9 @@ import { createHash } from 'node:crypto'
2
2
  import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
3
3
  import path from 'node:path'
4
4
  import { tokenizeRaw, makeSearchText } from './util/search.js'
5
- import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
5
+ import { acquireDirLock, storeKey, writeJsonAtomic } from './util/fs.js'
6
+ import { debugPersistence } from './util/persist.js'
7
+ import { trackDirty, untrackDirty } from './util/flush.js'
6
8
  import { backfillDerivedTriggers } from './readiness.js'
7
9
 
8
10
  const FORMAT_FILE = 'format.json'
@@ -19,29 +21,37 @@ const GITIGNORE_FILE = '.gitignore'
19
21
  const LEGACY_TYPE_CACHE_DIR = 'type-cache'
20
22
 
21
23
  const storeCache = new Map()
24
+ /**
25
+ * `storeKey(解析后的目录)` → `storeCache` 里实际使用的键。Windows/macOS 的文件系统大小写不敏感:
26
+ * `D:\proj\.dsh-project-memory` 与 `d:\PROJ\.DSH-PROJECT-MEMORY` 是同一个目录,但字符串不同。
27
+ * 没有这层别名就会给同一个物理 store 建两份实例——双份内存,且一边未落盘的条目另一边看不见
28
+ * (`load()` 是从盘上读的)。缓存键本身仍保持"真实解析路径"形态:它会出现在告警文案和诊断输出里,
29
+ * 统一改成小写会让这些输出与用户看到的路径不一致。
30
+ */
31
+ const storeCacheAlias = new Map()
22
32
  /** 单实例超预算的告警只打一次(key = 解析后的 store 目录)。 */
23
33
  const warnedOverBudget = new Set()
24
34
  /** 条目数上限(兜底)。 */
25
35
  const STORE_CACHE_MAX = 32
26
36
  /**
27
- * 驻留内存的估算上限。只数"几个 store"是不够的:单个大仓库 store 实测驻留
28
- * 68MB(`load()` 后)~110MB(物化 `searchText` + 建 IDF/符号索引后),
29
- * 语料是 deepseek-harness / 70119 条目。32 个就是几 GB。
30
- * 估算口径见 `_estimateResidentBytes`(对内存里的对象图精确计数,不再用读盘文本量换算)。
37
+ * 驻留内存的预算上限。单个大仓库 store 实测驻留 68MB(`load()` 后)~110MB(物化
38
+ * `searchText` + 建索引后),32 个就是几 GB。口径见 `_estimateResidentBytes`。
31
39
  */
32
40
  let STORE_CACHE_MAX_BYTES = 256 * 1024 * 1024
33
41
  /** 每轮 save 最多补写多少个待压实的老分片(有界,避免升级后一次重写整库)。 */
34
42
  const COMPACT_BATCH = 200
35
43
 
44
+ /** 解析后的真实目录 + 它在缓存里的键(大小写别名命中时是**先插入**的那份写法)。 */
45
+ function cacheKeyFor(dir) {
46
+ const resolved = path.resolve(dir)
47
+ return { resolved, key: storeCacheAlias.get(storeKey(resolved)) ?? resolved }
48
+ }
49
+
36
50
  /**
37
- * 一个值的驻留字节:形状开销 + 字符串的**编码字节数**。
38
- *
39
- * 用 `Buffer.byteLength()` 而不是 `String.length`:CJK 在 UTF-8 里 3 字节/字符,而 V8
40
- * 双字节串 2 字节/字符——UTF-8 对非 ASCII 是偏高的代理指标,对纯 ASCII 精确。缓存预算
41
- * 容得下这个误差(实测两端 ±13%,见 `test/store-cache.test.mjs` 与内部设计笔记)。
42
- *
43
- * 递归用深度上限而不是 `Set` 去环:store 的对象图来自 `JSON.parse`,本就无环;深度上限
44
- * 既挡畸形数据,又比逐对象 `Set` 查重快 ~30%(70119 条目实测 36ms vs 52ms)。
51
+ * 一个值的驻留字节:形状开销 + 字符串的**编码字节数**。用 `Buffer.byteLength()` 而非
52
+ * `String.length`:UTF-8 对 CJK 偏高(3 字节 vs 内存 2 字节),对 ASCII 精确,实测两端 ±13%。
53
+ * 递归用深度上限而非 `Set` 去环:对象图来自 `JSON.parse` 本就无环,且快 ~30%
54
+ * (70119 条目实测 36ms vs 52ms)。
45
55
  */
46
56
  const RESIDENT_OBJ_BYTES = 60
47
57
  const RESIDENT_ARR_BYTES = 40
@@ -50,30 +60,17 @@ const RESIDENT_STR_BYTES = 16
50
60
  const RESIDENT_MAX_DEPTH = 8
51
61
 
52
62
  /**
53
- * 精确计量的版本戳:entries 的构成 + `searchText` 的物化状态 + 辅助集合的内容各算一维。
54
- * 三维缺一不可——漏掉哪一维,估算就停在那一维变更前的水位。
63
+ * 精确计量的版本戳:entries 构成 + `searchText` 物化状态 + 辅助集合内容,三维缺一不可。
55
64
  */
56
65
  function residentStampOf(store) {
57
66
  return `${store._entriesVersion}:${store._materializeVersion}:${store._auxVersion}`
58
67
  }
59
68
 
60
69
  /**
61
- * 精确计量的**触发上界**(不是估算本身):内存里文本字符数 × 4 + 骨架常数。
62
- *
63
- * 为什么必须有它:精确计量要遍历全库字符串(`Buffer.byteLength` 逐串编码),12.6k 文件 /
64
- * 80k 条目实测 ~40ms。放在每次冷加载的热路径上,就是白花这笔钱去判断"要不要逐出"——
65
- * 而绝大多数加载离 256MB 预算差得远,逐出根本不可能发生。
66
- *
67
- * 系数取偏保守:宁可多走一次精确计量,也不能把预算算松。ASCII 下 1 字符 ≈ 1 字节驻留
68
- * 外加键与对象形状开销(符号条目实测 ~4×);CJK 字符驻留 2 字节,而 UTF-8 文本里 3 字节,
69
- * 字符数只会更少。精确数一旦算过且版本未变,直接用它,不必再估。
70
- *
71
- * 两条腿合成一个数:
72
- * - `_textChars`:entries 的文本量,由三条路径维护(读盘分片 / 写条目 / 物化 `searchText`),
73
- * 按文件**替换式**累计,所以重写同一个文件不会把它算两遍;
74
- * - `auxCharsOf()`:辅助集合(experience / insights / tasks / binding / watch)的文本量。
75
- * 它们不在分片文本里,`load()` 之后还会被写大,单列一条腿才不会漏。
76
- * 在真实语料上标定的上界 / 精确值比是 1.16~1.74 倍。
70
+ * 精确计量的**触发上界**:文本字符数 × 4 + 骨架常数。精确计量要遍历全库字符串(80k 条目
71
+ * 实测 ~40ms),而多数加载离 256MB 预算很远、逐出不可能发生,所以先算上界。
72
+ * 系数取保守:宁可多走一次精确计量也不能把预算算松(真实语料上界/精确值 1.16~1.74×)。
73
+ * 两条腿:`_textChars`(entries,替换式累计)与 `auxCharsOf()`(辅助集合,`load()` 后还会写大)。
77
74
  */
78
75
  const RESIDENT_BOUND_PER_CHAR = 4
79
76
  const RESIDENT_SKELETON_BYTES = 1024
@@ -85,8 +82,8 @@ function residentBoundBytes(store) {
85
82
  }
86
83
 
87
84
  /**
88
- * 写路径的文本量估计(只用于上界):`searchText` + 不在它里面的字段 + 每条的键/JSON 开销。
89
- * 不重复计 title / keywords / summary / terms / sourcePath —— 它们都已经在 `searchText` 里。
85
+ * 写路径的文本量估计(只用于上界):`searchText` + 不在其内的字段 + 每条的键/JSON 开销;
86
+ * 已在 `searchText` 里的字段不重复计。
90
87
  */
91
88
  function entryTextChars(entries) {
92
89
  let sum = 0
@@ -105,11 +102,9 @@ export function _residentBoundBytesForTest(store) {
105
102
  }
106
103
 
107
104
  /**
108
- * 驻留量的对象图遍历。精确口径与上界口径**共用这一份**——抄成两份迟早会漂。
109
- *
110
- * `charsOnly` 决定字符串怎么记:精确口径走 `Buffer.byteLength`(真字节数);上界口径只取
111
- * `length` 字符数,省掉编码这一步。它是安全的上界:`RESIDENT_BOUND_PER_CHAR = 4` 保证 ×4 后
112
- * 仍 ≥ 真字节数(UTF-8 里一个 UTF-16 码元最多 3 字节,代理对 2 码元 / 4 字节)。
105
+ * 驻留量的对象图遍历。精确口径与上界口径**共用这一份**,避免两份实现漂移。
106
+ * `charsOnly` 为真时只取 `length` 字符数,是安全的上界:×4 后仍 ≥ UTF-8 真字节数
107
+ * (一个 UTF-16 码元最多 3 字节,代理对 2 码元 / 4 字节)。
113
108
  */
114
109
  function residentSizeOf(value, charsOnly, depth = 0) {
115
110
  if (depth > RESIDENT_MAX_DEPTH) return 0
@@ -136,19 +131,18 @@ function residentBytesOf(value) {
136
131
  }
137
132
 
138
133
  /**
139
- * 上界口径:只数字符(`auxCharsOf` 用)。给辅助集合单开这条路是因为它们条目数小(经验 / 任务
140
- * 都有上限),逐节点求和的代价可以忽略;entries 有几万条,那条路继续走增量记账的 `_textChars`。
134
+ * 上界口径:只数字符(`auxCharsOf` 用)。辅助集合条目数小,逐节点求和的代价可忽略;
135
+ * entries 有几万条,仍走增量记账的 `_textChars`。
141
136
  */
142
137
  function residentCharsOf(value) {
143
138
  return residentSizeOf(value, true, 0)
144
139
  }
145
140
 
146
141
  /**
147
- * 辅助集合的文本量(上界口径),按 `_auxVersion` 记忆化。
148
- *
149
- * 为什么单列:`_textChars` 只跟 entries;这几个集合在 `load()` 之后还会被写大,不进上界就会在
150
- * 缓存其实已超预算时跳过精确计量与逐出(实测单 store 上界 1024 B、实际 19.08 MB)。
151
- * 记忆化是必须的——`evictStoreCache` 对整个缓存逐 store 求和,不记忆化就是每次冷加载重算一遍。
142
+ * 辅助集合的文本量(上界口径),按 `_auxVersion` 记忆化。`_textChars` 只跟 entries,
143
+ * 而辅助集合在 `load()` 之后还会被写大,不进上界就会在已超预算时跳过计量与逐出
144
+ * (实测单 store 上界 1024 B、实际 19.08 MB)。`evictStoreCache` 对整个缓存逐 store
145
+ * 求和,不记忆化等于每次冷加载重算一遍。
152
146
  */
153
147
  function auxCharsOf(store) {
154
148
  if (store._auxStamp === store._auxVersion) return store._auxChars
@@ -162,20 +156,10 @@ function auxCharsOf(store) {
162
156
  }
163
157
 
164
158
  /**
165
- * 单个 store 的驻留估算:数**内存里留下的对象图**,按版本记忆化。
166
- *
167
- * 为什么不是"读盘文本量换算"(旧实现):那个口径有两个错。
168
- * 1. 时序错位——它量的是 `load()` 读进来的 JSON 文本,而 `searchText` 要到
169
- * `allEntries()` 才物化,同一份数据在物化前后估出两个数(实测 76MB → 107MB)。
170
- * 2. 账不对物——旧分片里还带着 `searchText` / `linkedSymbols`,`load()` 会
171
- * `stripPersistedDerived` 把它们删掉,可文本量已经把被删的字节算进去了。
172
- * 实测一个 12.6k 文件的父目录 store:读盘 212.6MB,真实驻留 101.7MB。
173
- *
174
- * 两个版本键都参与失效:`_entriesVersion`(`setEntries` / `removeFile` / `_loadSharded`)
175
- * 与 `_materializeVersion`(`allEntries()` 物化 `searchText`)。漏掉后者就是旧实现的错。
176
- *
177
- * 代价:版本变化后的**一次**全量遍历(70119 条目 ~40ms)。必须记忆化——`evictStoreCache`
178
- * 是对**整个缓存**逐 store 求和的,不记忆化等于每次冷加载都把缓存里所有 store 重数一遍。
159
+ * 单个 store 的驻留估算:数**内存里留下的对象图**,按版本记忆化。不用读盘文本量换算——
160
+ * `searchText` 要到 `allEntries()` 才物化,前后估出两个数(实测 76MB → 107MB),且被
161
+ * `stripPersistedDerived` 删掉的字段也会被算进去。`_entriesVersion` 与 `_materializeVersion`
162
+ * 都参与失效;一次全量遍历 70119 条目 ~40ms,逐出又会遍历整个缓存,所以必须记忆化。
179
163
  */
180
164
  export function _estimateResidentBytes(store) {
181
165
  const stamp = residentStampOf(store)
@@ -194,8 +178,7 @@ export function _estimateResidentBytes(store) {
194
178
 
195
179
  /** 按 LRU 逐出,直到同时满足条数与字节预算;刚加入的 keepKey 即使超预算也保留。 */
196
180
  function evictStoreCache(keepKey) {
197
- // 只在**真有可能逐出**时才付精确计量的钱:条数超上限,或保守上界就已超字节预算。
198
- // 宽裕时(单项目常态)一次对象图遍历都不做——冷加载因此不背那次全库扫描。
181
+ // 条数超上限或上界已超字节预算才做精确计量;宽裕时一次对象图遍历都不做。
199
182
  let exact = storeCache.size > STORE_CACHE_MAX
200
183
  if (!exact) {
201
184
  let bound = 0
@@ -208,8 +191,7 @@ function evictStoreCache(keepKey) {
208
191
  const oldest = storeCache.keys().next().value
209
192
  if (oldest === undefined || oldest === keepKey) break
210
193
  if (exact) total -= _estimateResidentBytes(storeCache.get(oldest))
211
- // 逐出前先落盘:任务热点/人类消息是延迟写的(turn/end 才 flush),
212
- // 若这里直接丢实例,还没到回合结束的变更就再也回不来了。save() 无脏数据时自己早退。
194
+ // 逐出前先落盘:任务热点/人类消息延迟到回合结束才 flush,直接丢实例会丢未落盘的变更。
213
195
  const evicted = storeCache.get(oldest)
214
196
  if (evicted && evicted.hasDirty()) {
215
197
  try {
@@ -219,12 +201,13 @@ function evictStoreCache(keepKey) {
219
201
  }
220
202
  }
221
203
  storeCache.delete(oldest)
204
+ // 别名跟着一起删:留着会让下一次 `load()` 命中一个已经不存在的键。
205
+ storeCacheAlias.delete(storeKey(oldest))
222
206
  }
223
- // 没做过精确计量就不报"单实例超预算":算都没算,报出来的数是估的。真超预算时
224
- // (多一个 store 就会触发上界)下一次加载会走到这里并如实告警。
207
+ // 没做精确计量就不报单实例超预算:真超预算时下一次加载会走到这里并如实告警。
225
208
  if (!exact) return
226
- // keepKey 豁免是**有意**的:刚加载的 store 必须立刻可用。但它的代价是"单实例超预算时
227
- // 预算不再是上界"——这个代价不能是隐式的,所以每个这样的 store 告警一次(每 root 一次)。
209
+ // keepKey 豁免是有意的(刚加载的 store 必须立刻可用);代价是单实例超预算时预算不再是
210
+ // 上界,所以每个这样的 store 每 root 告警一次。
228
211
  const kept = _estimateResidentBytes(storeCache.get(keepKey))
229
212
  if (kept > STORE_CACHE_MAX_BYTES && !warnedOverBudget.has(keepKey)) {
230
213
  warnedOverBudget.add(keepKey)
@@ -266,11 +249,39 @@ function newerIso(a, b) {
266
249
  }
267
250
 
268
251
  /**
269
- * 落盘的 entry 只保留**不可推导的事实**。两个派生字段永远不写盘:
270
- * - `linkedSymbols`:跨实体派生(取决于符号表当前状态),读取期由 src/link.js 解算;
271
- * - `searchText`:自派生(只依赖本 entry),由 `allEntries()` 在内存里物化。
272
- * 旧 store 里的这两个字段在加载时剥掉,于是下一次写盘自然压实。
273
- * 实测两者在一个真实大仓库 store 里合计约 245MB(链接 222.8MB + searchText 22.7MB)。
252
+ * 合并同一任务在两份快照里的 `insights`:以**上次落盘的 id 基线**做三方判断,基线没有、
253
+ * 本地有 → 本地新增;基线有、本地没有 → 本地删除(不复活);两边都有 → `updatedAt` 新者胜。
254
+ * 不能只按任务 `updatedAt` 选一侧:任务条目写入不 bump 任务时间戳,会整段覆盖另一边。
255
+ * @param {object} local
256
+ * @param {object} disk
257
+ * @param {Set<string>} base
258
+ * @returns {object[]}
259
+ */
260
+ function mergeTaskInsights(local, disk, base) {
261
+ const merged = new Map()
262
+ for (const ins of Array.isArray(disk?.insights) ? disk.insights : []) {
263
+ if (ins?.id) merged.set(ins.id, ins)
264
+ }
265
+ const localById = new Map()
266
+ for (const ins of Array.isArray(local?.insights) ? local.insights : []) {
267
+ if (ins?.id) localById.set(ins.id, ins)
268
+ }
269
+ for (const id of base) if (!localById.has(id)) merged.delete(id)
270
+ for (const [id, ins] of localById) {
271
+ const prev = merged.get(id)
272
+ if (!prev) {
273
+ if (!base.has(id)) merged.set(id, ins)
274
+ continue
275
+ }
276
+ if (newerIso(ins.updatedAt, prev.updatedAt) >= 0) merged.set(id, ins)
277
+ }
278
+ return [...merged.values()]
279
+ }
280
+
281
+ /**
282
+ * 落盘的 entry 只保留**不可推导的事实**,两个派生字段永不写盘:`linkedSymbols` 是跨实体
283
+ * 派生(取决于符号表当前状态,读取期由 src/link.js 解算),`searchText` 是自派生(只依赖
284
+ * 本 entry,由 `allEntries()` 在内存里物化)。旧 store 的这两个字段加载时剥掉,下次写盘自然压实。
274
285
  */
275
286
  const PERSISTED_DERIVED = ['linkedSymbols', 'searchText', 'typeSig']
276
287
  const PERSISTED_DERIVED_SET = new Set(PERSISTED_DERIVED)
@@ -282,14 +293,10 @@ function hasPersistedDerived(entry) {
282
293
  }
283
294
 
284
295
  /**
285
- * 按**非派生键重建**一个对象。
286
- *
287
- * 不用 `delete`:删除属性会把 entry 推进 V8 的字典模式,之后每个属性都变成哈希表项。
288
- * 本仓库真实条目形状实测 —— `delete` 后 **1196 B/条**,重建后 **436 B/条**(20k 条 / --expose-gc)。
289
- * 加载路径上这是常驻内存(`storeCache` 里所有 store 都算),写盘路径上同款浪费。
290
- *
291
- * `undefined` 值的键也不复制:`typeSig: undefined` 是 enhancer 的实现细节(见 src/enhancer.js),
292
- * JSON 里本来就不存在,留在内存对象里只会占一个属性槽。
296
+ * 按**非派生键重建**一个对象。不用 `delete`:删除属性会把 entry 推进 V8 字典模式,
297
+ * 之后每个属性都变成哈希表项。本仓库真实条目形状实测 `delete` 后 1196 B/条、重建后
298
+ * 436 B/条(20k 条 / --expose-gc)。`undefined` 值的键也不复制(`typeSig` 是 enhancer
299
+ * 的实现细节,JSON 里本就不存在)。
293
300
  */
294
301
  function rebuildWithoutDerived(entry) {
295
302
  const out = {}
@@ -297,7 +304,7 @@ function rebuildWithoutDerived(entry) {
297
304
  if (PERSISTED_DERIVED_SET.has(key)) continue
298
305
  const value = entry[key]
299
306
  if (value === undefined) continue
300
- // JSON.parse 可以把 `__proto__` 变成自有属性,而 `out[key] = value` 会走去改原型 —— 显式定义。
307
+ // JSON.parse 可以把 `__proto__` 变成自有属性,而赋值会去改原型 —— 显式定义。
301
308
  if (key === '__proto__') Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true })
302
309
  else out[key] = value
303
310
  }
@@ -314,10 +321,7 @@ function stripPersistedDerived(entry) {
314
321
  return rebuildWithoutDerived(entry)
315
322
  }
316
323
 
317
- /**
318
- * 返回不含派生字段的条目(写盘路径用,不能动内存里的对象)。
319
- * 同样重建而不是 spread+delete —— 两个路径的字典模式代价是一样的。
320
- */
324
+ /** 返回不含派生字段的条目(写盘路径用,不能动内存里的对象)。 */
321
325
  function withoutPersistedDerived(entry) {
322
326
  if (!entry || typeof entry !== 'object') return entry
323
327
  if (!hasPersistedDerived(entry)) return entry
@@ -336,8 +340,7 @@ function loadJson(filePath, fallback, counter) {
336
340
  } catch {
337
341
  return fallback
338
342
  }
339
- // 可选:累计读盘文本的字符数。只用于 `residentBoundBytes`(要不要做精确计量的上界),
340
- // 不参与精确估算本身——后者数的是内存里的对象图。
343
+ // 累计读盘文本字符数,只供 `residentBoundBytes` 判断要不要精确计量。
341
344
  if (counter) counter.chars += raw.length
342
345
  try {
343
346
  return JSON.parse(raw)
@@ -378,6 +381,21 @@ export class ProjectMemoryStore {
378
381
  this._removedWatch = new Set()
379
382
  /** 上次落盘/加载时的 insight id 集合:原地 splice 的删除也要能被合并逻辑看见。 */
380
383
  this._baseInsightIds = new Set()
384
+ /** task.id → 上次落盘/加载时该任务的 insight id 集合(任务级条目的合并基线,见 mergeTaskInsights)。 */
385
+ this._baseTaskInsightIds = new Map()
386
+ /**
387
+ * 本进程**新建**的条目。"磁盘没有但内存有"可能是新建(要补写)也可能是**对方删了**
388
+ * (不能写回);没有这个集合,后者会被复活。
389
+ */
390
+ this._createdInsightIds = new Set()
391
+ this._createdTaskIds = new Set()
392
+ /** 上一次 save 是否真的落到盘上(锁竞争/权限失败时为 false)。 */
393
+ this.lastSaveOk = true
394
+ /** `shards/` 的 `.tmp` 清扫节流:NTFS 上 readdir(数千分片) 不便宜,不能每次 save 都扫。 */
395
+ this._lastShardTmpSweep = 0
396
+ /** store 目录 / shards 目录已确认存在:首次写之后不再每次 save 都 mkdir(9p 上每次 ~4ms)。 */
397
+ this._storeDirReady = false
398
+ this._shardsDirReady = false
381
399
  this._lockWarned = false
382
400
  this._conflictWarned = new Set()
383
401
  /** 锁竞争跳过落盘后的有限次延迟重试;unref,避免拖住进程退出。 */
@@ -397,20 +415,20 @@ export class ProjectMemoryStore {
397
415
  this._residentBytes = 0
398
416
  this._residentStamp = ''
399
417
  /**
400
- * entries 的文本字符数累计(读盘分片 + 写条目 + 物化 `searchText`),按文件**替换式**记。
401
- * **只**用于 `residentBoundBytes` 判断"要不要做精确计量";精确估算数的是对象图,不碰它。
418
+ * entries 的文本字符数累计(读盘 + 写条目 + 物化 `searchText`),按文件**替换式**记。
419
+ * **只**供 `residentBoundBytes` 判断要不要精确计量;精确估算数的是对象图。
402
420
  */
403
421
  this._textChars = 0
404
422
  /** 每个文件当前的文本字符数,写入时按文件替换,避免重写同一文件被算两遍。 */
405
423
  this._fileTextChars = new Map()
406
424
  /**
407
- * `searchText` 的物化计数。它和 `_entriesVersion` 一起构成驻留估算的失效键:
408
- * 物化只改 entry 对象本身,不改 entries 的构成,所以不会 bump `_entriesVersion`。
425
+ * `searchText` 的物化计数:物化只改 entry 对象、不改 entries 构成,不 bump
426
+ * `_entriesVersion`,所以驻留估算的失效键要单独带上它。
409
427
  */
410
428
  this._materializeVersion = 0
411
429
  /**
412
430
  * 辅助集合(experience / insights / tasks / binding / watch)的内容版本:它们不在 entries
413
- * 的记账面里,靠它让精确估算失效、并让 `auxCharsOf` 重算。每个改到它们的写口都要 bump。
431
+ * 的记账面里,靠它让精确估算失效、`auxCharsOf` 重算。每个改到它们的写口都要 bump。
414
432
  */
415
433
  this._auxVersion = 0
416
434
  this._auxChars = 0
@@ -418,10 +436,11 @@ export class ProjectMemoryStore {
418
436
  }
419
437
 
420
438
  load() {
421
- const key = path.resolve(this.dir)
439
+ // 大小写归一(仅用于命中缓存):Windows/macOS 上同一个物理目录可能有多种写法,
440
+ // 不归一就会并存两个实例;缓存键本身保持真实解析路径(见 `cacheKeyFor`)。
441
+ const { resolved, key } = cacheKeyFor(this.dir)
422
442
  const hot = storeCache.get(key)
423
- // 缓存命中即返回:`hot === this` 时再读一遍盘会静默丢弃本实例尚未 save() 的变更
424
- // (_loadSharded/_loadInsights 会重新赋值 experience/tasks/insights…)。
443
+ // 缓存命中即返回:`hot === this` 时再读一遍盘会静默丢弃本实例尚未 save 的变更。
425
444
  if (hot) {
426
445
  // LRU:命中挪到队尾,避免"热的先被逐出、冷的常驻"。
427
446
  storeCache.delete(key)
@@ -432,11 +451,12 @@ export class ProjectMemoryStore {
432
451
  this._loadSharded()
433
452
  this._loadInsights()
434
453
  this._pruneBindings()
454
+ this._resetTaskInsightBases()
435
455
  this._removeLegacyTypeCache()
436
- // 有些路径只读不写(审计 jsonl 直接写在 store 目录里),所以这里也补一次自我忽略,
437
- // 让老版本建出来的 store 在第一次 load 就补上。
456
+ // 有些路径只读不写(审计 jsonl 直接写在 store 目录里),这里补一次自我忽略兜底。
438
457
  this.ensureSelfIgnore()
439
458
  storeCache.set(key, this)
459
+ storeCacheAlias.set(storeKey(resolved), key)
440
460
  evictStoreCache(key)
441
461
  return this
442
462
  }
@@ -477,9 +497,8 @@ export class ProjectMemoryStore {
477
497
  }
478
498
  return
479
499
  }
480
- // index.json 是 entries.json → rel 的唯一映射。它缺失或损坏时继续迁移,会写出 0 个
481
- // shard、打上 v2 标记、再把**完好的** entries.json 删掉——等于一次静默的数据清空。
482
- // 保留现场,不写 format 标记,等 index.json 修好后再迁(每次进程只提示一次)。
500
+ // index.json 是 entries.json → rel 的唯一映射;它缺失时继续迁移会写出 0 个 shard 再删掉
501
+ // 完好的 entries.json,等于静默清空。保留现场,不写 format 标记,等修好后再迁。
483
502
  if (!migrationWarned.has(this.dir)) {
484
503
  migrationWarned.add(this.dir)
485
504
  console.error(`[dsh-project-memory] legacy store at ${this.dir} has ${ENTRIES_FILE} but no readable ${INDEX_FILE}; migration skipped to protect it`)
@@ -509,10 +528,8 @@ export class ProjectMemoryStore {
509
528
  }
510
529
 
511
530
  /**
512
- * 读一个辅助集合文件(experience / tasks / insights / binding / watch)。
513
- *
514
- * 它们的文本量**不进** `_textChars`:那份账只跟 entries(按文件替换),辅助集合交给
515
- * `auxCharsOf` 按对象图直接算——同一个集合由两个口径各记一半,迟早会漂。
531
+ * 读一个辅助集合文件(experience / tasks / insights / binding / watch)。它们的文本量
532
+ * **不进** `_textChars`(那份账只跟 entries),交给 `auxCharsOf` 按对象图直接算。
516
533
  */
517
534
  _loadJson(filePath, fallback) {
518
535
  return loadJson(filePath, fallback)
@@ -527,9 +544,8 @@ export class ProjectMemoryStore {
527
544
  }
528
545
 
529
546
  /**
530
- * 绑定只对“还能续做”的任务有意义:任务已删除或已归档时清掉对应会话绑定。
531
- * 否则 binding.json 会永久留着指向归档任务的条目,下一次 todo 写入又会建新任务。
532
- * 只标脏、不立刻落盘——读路径不应为了清理额外写一次盘。
547
+ * 清掉指向已删除/已归档任务的会话绑定,否则 binding.json 会永久留着条目(下一次 todo
548
+ * 写入又会建新任务)。只标脏、不立刻落盘——读路径不应为清理额外写一次盘。
533
549
  */
534
550
  _pruneBindings() {
535
551
  // 旧 store/手工损坏的 JSON 可能不是期望形状;读路径不能因此抛错。
@@ -565,8 +581,7 @@ export class ProjectMemoryStore {
565
581
  this._setFileTextChars(shard.relPath, counter.chars)
566
582
  this.files[shard.relPath] = shard.record
567
583
  this._baseFileSha.set(shard.relPath, shard.record.sha256 ?? null)
568
- // 畸形 shard(entries 被写成对象/null)不能让 allEntries() 在 `for…of` 上抛错,
569
- // 否则一个坏文件会拖垮整个进程的每一次读取。
584
+ // 畸形 shard(entries 不是数组)不能让 `for…of` 抛错,否则一个坏文件会拖垮每次读取。
570
585
  const list = Array.isArray(shard.entries) ? shard.entries.filter(isRecord) : []
571
586
  // 老分片带着派生字段:内存里立刻剥掉,并排队等 save() 把磁盘上也压实。
572
587
  if (list.some((e) => PERSISTED_DERIVED.some((k) => k in e))) this._compactQueue.add(shard.relPath)
@@ -583,12 +598,8 @@ export class ProjectMemoryStore {
583
598
  }
584
599
 
585
600
  /**
586
- * 清掉 ≤0.5.10 留下的 `type-cache/` 目录。
587
- *
588
- * 它按内容哈希缓存 TS 增强结果,但三个增强入口(lazy 的 `fs/observed`、watch 轮询、
589
- * `index_repo`)**都只在"文件已变更并重新索引"之后**才触发,此时内容哈希必然是新值——
590
- * 这个缓存永远命中不了。实测本仓库残留 9827 个文件(`du` 41MB,内容其实 9.2MB,约 31MB
591
- * 是 4KB 块开销)。这里做一次自愈清理;删的是纯缓存,不丢任何事实。
601
+ * 清掉 ≤0.5.10 留下的 `type-cache/`:三个增强入口都只在文件重新索引后触发,内容哈希
602
+ * 必然是新值,缓存永远命中不了。实测本仓库残留 9827 个文件、`du` 41MB。
592
603
  */
593
604
  _removeLegacyTypeCache() {
594
605
  const dir = path.join(this.dir, LEGACY_TYPE_CACHE_DIR)
@@ -601,13 +612,9 @@ export class ProjectMemoryStore {
601
612
  }
602
613
 
603
614
  // ---- v0.5 insights:project 级 insight 文档(任务级在 task.insights[]) ----
604
- // 统一语义(本版起):insight 是**唯一**的记忆实体,`kind:'experience'` 就是 v0.4 的经验笔记。
605
- // 旧版 store 的兼容策略:把 experience.json 的内容**导入** insights.json 一次,随后把旧文件改名成
606
- // `experience.json.migrated` 只读归档——不删(升级后想人工比对还有原文),但不再读写它。
607
- //
608
- // 归档那一步必须与"导入"分开判:0.5.x/0.6.x 用户的 store 里 `migratedAt` 早就写上了(那时导入的是
609
- // 影子副本),可旧文件还留在磁盘上。只看 migratedAt 的话,老用户永远收不走它,
610
- // `store.experience` 也永远留着第二份内容——正是"散"的来源。
615
+ // insight 是**唯一**的记忆实体,`kind:'experience'` 就是 v0.4 的经验笔记。旧 store 的
616
+ // experience.json 只导入一次,随后改名成 `experience.json.migrated` 只读归档(不删)。
617
+ // 归档与导入必须分开判:老用户的 `migratedAt` 早已写上,只看它会让旧文件永远收不走。
611
618
  _loadInsights() {
612
619
  const doc = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
613
620
  this.insights = isRecord(doc) && Array.isArray(doc.items)
@@ -615,7 +622,7 @@ export class ProjectMemoryStore {
615
622
  ? { ...doc, items: doc.items.filter(isRecord) }
616
623
  : { version: 1, migratedAt: null, items: [] }
617
624
  this._migrateExperienceToInsights()
618
- // PR3:v1 → v2 懒回填派生 trigger(纯确定性、幂等;不调用模型,不改写已有字段)
625
+ // 懒回填派生 trigger(纯确定性、幂等;不调用模型,不改写已有字段)
619
626
  if (backfillDerivedTriggers(this.insights)) this._dirtyInsights = true
620
627
  // 迁移与回填都会改 items;换掉整个文档后让 auxCharsOf/精确估算重算。
621
628
  this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
@@ -631,11 +638,8 @@ export class ProjectMemoryStore {
631
638
  return
632
639
  }
633
640
  let imported = 0
634
- // 导入 + 落盘这条支路必须有"值得写"的输入才走:`migratedAt` 为空 + 旧文件不在 + 内存里也没有
635
- // 旧条目(全新根)时直接跳过。否则 `load()` 会在一个从没被索引过的空目录里 mkdir + 写
636
- // insights.json —— 那会让 `audit.js` 的 auditDirReady("目录已存在")与 auto-inject 的
637
- // `if (store.hasContent) store.save()` 双双失效,容器目录被当成项目根(issue #5 同类)。
638
- // 归档旧文件是**另一支**(下面单独判 legacyOnDisk),所以跳过这里不影响真升级。
641
+ // 只有值得写的输入(`migratedAt` 为空 + 旧文件在或有旧条目)才导入:否则 `load()` 会在空目录里
642
+ // mkdir + 写 insights.json,让调用方"目录已存在/有内容"的判断失真(容器目录被当成项目根)。
639
643
  if (!this.insights.migratedAt && (legacyOnDisk || legacy.length > 0)) {
640
644
  const now = new Date().toISOString()
641
645
  const known = new Set(this.insights.items.map((it) => it.id))
@@ -663,7 +667,7 @@ export class ProjectMemoryStore {
663
667
  this.insights.migratedAt = now
664
668
  try {
665
669
  mkdirSync(this.dir, { recursive: true })
666
- writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
670
+ writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights, { ensureDir: false })
667
671
  } catch (err) {
668
672
  // 没写进 insights.json 就**不能**把旧文件收走:那会真的丢数据。
669
673
  console.error(`[dsh-project-memory] insights migration write failed, keeping ${EXPERIENCE_FILE}: ${err.message}`)
@@ -692,7 +696,10 @@ export class ProjectMemoryStore {
692
696
  const next = new Set((items || []).map((it) => it?.id).filter(Boolean))
693
697
  // 与上次落盘的基线比,而不是与当前数组比:调用方经常先原地 splice 再调用这里。
694
698
  for (const id of this._baseInsightIds) if (!next.has(id)) this._deletedInsightIds.add(id)
695
- for (const id of next) this._deletedInsightIds.delete(id)
699
+ for (const id of next) {
700
+ this._deletedInsightIds.delete(id)
701
+ if (!this._baseInsightIds.has(id)) this._createdInsightIds.add(id)
702
+ }
696
703
  this.insights.items = items
697
704
  this._baseInsightIds = next
698
705
  this._dirtyInsights = true
@@ -700,17 +707,23 @@ export class ProjectMemoryStore {
700
707
  }
701
708
 
702
709
  /**
703
- * 调用方**直接改过** task 内容(包括 task 内的条目)后的标脏入口。任务树不在 `addTask` /
704
- * `updateTask` 那几条写口里,所以这里也要 bump 内容版本,否则精确估算停在前一水位。
710
+ * 调用方**直接改过** task 内容(含 task 内条目)后的标脏入口:任务树不走 `addTask` /
711
+ * `updateTask`,这里不 bump 内容版本的话精确估算会停在前一水位。
705
712
  */
706
713
  markTasksDirty() {
707
714
  this._dirtyTasks = true
708
715
  this._auxVersion++
709
716
  }
710
717
 
711
- cleanStaleTmp() {
712
- const scanDirs = [this.dir, path.join(this.dir, SHARDS_DIR)]
718
+ cleanStaleTmp({ force = false } = {}) {
719
+ // store 根目录只有几个文件,每次扫很便宜;`shards/` 是 O(N)(12k 分片时在 NTFS 上会卡),
720
+ // 60s 扫一次足够,`force` 给测试/诊断用。
713
721
  const now = Date.now()
722
+ const scanDirs = [this.dir]
723
+ if (force || now - this._lastShardTmpSweep >= 60_000) {
724
+ this._lastShardTmpSweep = now
725
+ scanDirs.push(path.join(this.dir, SHARDS_DIR))
726
+ }
714
727
  for (const dir of scanDirs) {
715
728
  let entries
716
729
  try {
@@ -730,15 +743,12 @@ export class ProjectMemoryStore {
730
743
  }
731
744
 
732
745
  /**
733
- * store 目录**自我忽略**:在目录里放一个内容为 `*` 的 `.gitignore`。
734
- *
735
- * 为什么不写进用户的 `.gitignore`:那是用户的文件,插件不该改;而且"忘了加"的代价
736
- * 是一次误提交。为什么这样就够:git 会读取工作区里**任意**目录下的 `.gitignore`,
737
- * 而 `*` 连这个 `.gitignore` 自己一起命中,于是 `git status` / `git add -A` 里整棵树
738
- * 都不出现,用户一个字都不用写(`git check-ignore -v` 可复核)。
746
+ * store 目录**自我忽略**:放一个内容为 `*` 的 `.gitignore`。不改用户的 `.gitignore`
747
+ * (那是用户的文件,且"忘了加"的代价是误提交);git 会读取任意子目录下的 `.gitignore`,
748
+ * `*` 连它自己一起命中,整棵树不会进 `git status`。要随仓库提交用 `git add -f`。
739
749
  *
740
- * 顺带的好处:被忽略的文件不会被 `git clean -fd` 删除(未跟踪且未忽略的会被删)。
741
- * 想把记忆跟着仓库提交:`git add -f .dsh-project-memory`——已跟踪的文件不受忽略规则影响。
750
+ * **不缓存"文件已存在"**:只省一次 stat,却会把外部删除(`git clean -fdx`)变成
751
+ * 本进程剩余生命周期都不再自我忽略,store 可能被下一次 `git add` 带进提交。
742
752
  */
743
753
  ensureSelfIgnore() {
744
754
  if (!existsSafe(this.dir)) return
@@ -751,6 +761,16 @@ export class ProjectMemoryStore {
751
761
  }
752
762
  }
753
763
 
764
+ /** 重新记下每个任务当前可见的 insight id:只在加载成功 / 整份 tasks 落盘成功后调用。 */
765
+ _resetTaskInsightBases() {
766
+ this._baseTaskInsightIds = new Map()
767
+ for (const task of Array.isArray(this.tasks) ? this.tasks : []) {
768
+ if (!task?.id) continue
769
+ const ids = Array.isArray(task.insights) ? task.insights.map((it) => it?.id).filter(Boolean) : []
770
+ this._baseTaskInsightIds.set(task.id, new Set(ids))
771
+ }
772
+ }
773
+
754
774
  /** 是否有待落盘的变更;逐出缓存前用它避免为干净 store 触发 save 的旁路副作用。 */
755
775
  hasDirty() {
756
776
  return this._compactQueue.size > 0
@@ -762,10 +782,14 @@ export class ProjectMemoryStore {
762
782
  || this._dirtyWatch
763
783
  }
764
784
 
765
- save() {
766
- // 没有脏数据就不落盘。watch 每轮对每个根都无条件 commit → save;照旧执行的话,
767
- // 末尾的 ID 缓存失效会打在跨实例共享的 store 上,等于每轮清空一次 IDF 复用(v0.3.4 的 20x)。
768
- // 待压实队列不算"脏数据",但它需要有界推进,所以也走这条落盘路径。
785
+ /**
786
+ * @param {{ timeoutMs?: number }} [options] 等锁上限,默认 15s:写路径的正确性靠**同步等待**,
787
+ * 用户结束对话就会关 dsh,不等后台重试;重试只是长驻进程的兜底。
788
+ * @returns {boolean} 是否真的落盘(无脏数据也算成功)
789
+ */
790
+ save(options = {}) {
791
+ // 没有脏数据就不落盘:watch 每轮对每个根都无条件 commit → save,否则末尾的 IDF 缓存失效
792
+ // 会打在跨实例共享的 store 上,等于每轮清空一次复用。待压实队列不算脏,但也要有界推进。
769
793
  const compacting = this._compactQueue.size > 0
770
794
  const dirty =
771
795
  compacting ||
@@ -776,32 +800,68 @@ export class ProjectMemoryStore {
776
800
  this._dirtyBinding ||
777
801
  this._dirtyWatch ||
778
802
  !this._formatWritten
779
- if (dirty) mkdirSync(this.dir, { recursive: true })
803
+ if (dirty) {
804
+ // 目录可能在 load 之后被外部删掉:`_storeDirReady` 只当"上次写过"的快路径,命中时补一次
805
+ // stat;失配就重建目录,并让分片/格式/忽略三处的已就绪状态一起失效。
806
+ let dirReady = this._storeDirReady
807
+ if (dirReady) {
808
+ try {
809
+ statSync(this.dir)
810
+ } catch (err) {
811
+ // 只有 ENOENT 才重建;EACCES / ENOTDIR 交给锁走原来的静默失败路径,不升级成抛错。
812
+ if (err?.code === 'ENOENT') dirReady = false
813
+ }
814
+ }
815
+ if (!dirReady) {
816
+ try {
817
+ mkdirSync(this.dir, { recursive: true })
818
+ } catch {
819
+ this.lastSaveOk = false
820
+ trackDirty(this)
821
+ this._scheduleSaveRetry()
822
+ return false
823
+ }
824
+ this._storeDirReady = true
825
+ this._shardsDirReady = false
826
+ this._formatWritten = false
827
+ }
828
+ }
780
829
  // 崩溃遗留的 *.tmp 无论有没有脏数据都顺手清掉(两次 readdir,自带 try/catch)
781
830
  this.cleanStaleTmp()
782
- // 自我忽略也在无脏数据时执行:老版本建出来的 store 会在下一次 save 时补上。
831
+ // 无脏数据也要补自我忽略:老版本建出来的 store 会在下一次 save 时补上。
783
832
  this.ensureSelfIgnore()
784
- if (!dirty) return
785
- // 跨进程:整段读改写放进目录锁;拿不到锁就保持脏状态,等下一次写重试(不静默丢数据)。
786
- const release = acquireDirLock(this.dir)
833
+ if (!dirty) {
834
+ this.lastSaveOk = true
835
+ untrackDirty(this)
836
+ return true
837
+ }
838
+ // 跨进程:整段读改写放进目录锁,默认同步等 15s。拿不到锁就保持脏状态并登记退出 flush,
839
+ // 默认静默,不向用户/模型抛提示。
840
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 15000
841
+ // `maxHoldMs`:同一次启动内 pid 被别的进程复用后,残留锁会一直被当成"活锁"(Windows 上
842
+ // 没有 /proc,看不出 pid 复用)。一次写盘只在毫秒级持锁,超过 10 分钟就不可能是"正在写"。
843
+ const release = acquireDirLock(this.dir, { timeoutMs, ensureDir: false, maxHoldMs: 10 * 60_000 })
787
844
  if (!release) {
845
+ this.lastSaveOk = false
846
+ trackDirty(this)
788
847
  if (!this._lockWarned) {
789
848
  this._lockWarned = true
790
- console.error(`[dsh-project-memory] store ${this.dir} is busy (another dsh process is writing); this save was skipped and will retry shortly.`)
849
+ debugPersistence(`[dsh-project-memory] store ${this.dir} is busy (another dsh process is writing); this write is pending.`)
791
850
  }
792
851
  this._scheduleSaveRetry()
793
- return
852
+ return false
794
853
  }
854
+ let wroteInsights = false
855
+ let wroteTasks = false
795
856
  try {
796
857
  // 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
797
858
  this._mergeAuxFromDisk()
798
859
  if (!this._formatWritten) {
799
- writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' })
860
+ writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' }, { ensureDir: false })
800
861
  this._formatWritten = true
801
862
  }
802
- // 存量压实:≤0.5.10 的分片带着派生字段,而那些字段只在分片被重写时才会从磁盘消失。
803
- // 每轮最多补写 COMPACT_BATCH 个,让升级后的 store 在后续任意一次 save(watch 轮询、
804
- // 索引、写入)里自动收敛,而不是永远停在旧体积。
863
+ // 存量压实:≤0.5.10 的分片带派生字段,只有重写才消失。每轮最多 COMPACT_BATCH 个,
864
+ // 让升级后的 store 在后续任意一次 save 里自动收敛。
805
865
  let compactBudget = COMPACT_BATCH
806
866
  for (const rel of this._compactQueue) {
807
867
  if (compactBudget <= 0) break
@@ -814,13 +874,13 @@ export class ProjectMemoryStore {
814
874
  const nextSha = this.files[rel].sha256 ?? null
815
875
  const base = this._baseFileSha.get(rel) ?? null
816
876
  const disk = this._shardDiskRecord(rel)
817
- // 磁盘分片在加载后被别的进程改过,且不是我们这一版:按 indexedAt 收敛,
818
- // 本地更新则覆盖(否则显式 index 的结果会静默丢掉),对方更新则把对方读回内存。
877
+ // 磁盘分片加载后被别的进程改过:按 indexedAt 收敛,本地更新则覆盖,对方更新则读回内存。
819
878
  if (disk.exists && disk.sha !== base && disk.sha !== nextSha) {
820
879
  const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
821
880
  const diskAt = Date.parse(disk.record?.indexedAt || '') || 0
822
881
  if (localAt > diskAt) {
823
- writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) })
882
+ this._ensureShardsDir()
883
+ writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
824
884
  this._baseFileSha.set(rel, nextSha)
825
885
  continue
826
886
  }
@@ -828,8 +888,8 @@ export class ProjectMemoryStore {
828
888
  this._warnConflict(rel)
829
889
  continue
830
890
  }
831
- // 父目录由 writeJsonAtomic 保证
832
- writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) })
891
+ this._ensureShardsDir()
892
+ writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
833
893
  this._baseFileSha.set(rel, nextSha)
834
894
  } else {
835
895
  this._removedShards.add(rel)
@@ -840,8 +900,7 @@ export class ProjectMemoryStore {
840
900
  const base = this._baseFileSha.get(rel) ?? null
841
901
  const disk = this._shardDiskRecord(rel)
842
902
  if (disk.exists && disk.sha !== base) {
843
- // 删除与另一进程的更新撞车:没有删除时间戳可比,保守采用对方版本,
844
- // 至少让内存与磁盘一致(旧实现只跳过写,内存仍认为已删)。
903
+ // 删除与另一进程的更新撞车:没有删除时间戳可比,保守采用对方版本,让内存与磁盘一致。
845
904
  this._adoptDiskShard(rel, disk)
846
905
  this._warnConflict(rel)
847
906
  continue
@@ -854,34 +913,53 @@ export class ProjectMemoryStore {
854
913
  this._baseFileSha.delete(rel)
855
914
  }
856
915
  this._removedShards.clear()
857
- if (this._dirtyInsights) {
858
- // v2 → v3 是纯语义升级(`kind:'experience'` 从"影子副本"变成一等实体),形状不变;
859
- // 落盘即把版本推上去,老版本读到 v3 也照样按 v2 的字段解析(它只是排除 experience 影子)。
916
+ wroteInsights = this._dirtyInsights
917
+ wroteTasks = this._dirtyTasks
918
+ if (wroteInsights) {
919
+ // v2 → v3 是纯语义升级,形状不变;老版本读到 v3 仍按 v2 字段解析。
860
920
  if (this.insights && this.insights.version !== 3) this.insights.version = 3
861
- writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
921
+ writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights, { ensureDir: false })
862
922
  this._dirtyInsights = false
863
923
  }
864
924
  if (this._dirtyTasks) {
865
- writeJsonAtomic(path.join(this.dir, TASKS_FILE), this.tasks)
925
+ writeJsonAtomic(path.join(this.dir, TASKS_FILE), this.tasks, { ensureDir: false })
866
926
  this._dirtyTasks = false
867
927
  }
868
928
  if (this._dirtyBinding) {
869
- writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding)
929
+ writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding, { ensureDir: false })
870
930
  this._dirtyBinding = false
871
931
  }
872
932
  if (this._dirtyWatch) {
873
- writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist)
933
+ writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist, { ensureDir: false })
874
934
  this._dirtyWatch = false
875
935
  }
936
+ } catch (err) {
937
+ // 非锁原因的写失败(ENOSPC / EISDIR / 只读挂载)也要置 lastSaveOk=false 并登记 flush。
938
+ this.lastSaveOk = false
939
+ trackDirty(this)
940
+ throw err
876
941
  } finally {
877
942
  release()
878
943
  }
879
944
  this._saveRetryAttempts = 0
945
+ this.lastSaveOk = true
946
+ untrackDirty(this)
947
+ // 落盘成功才推进基线:失败时保持"本进程新建"的标记,下一次 save 仍要补写。
948
+ if (wroteInsights) {
949
+ this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
950
+ this._createdInsightIds.clear()
951
+ }
952
+ if (wroteTasks) {
953
+ // 只有真的落盘成功才推进任务条目的合并基线;失败时保留旧基线,重试仍能识别本地新增/删除。
954
+ this._createdTaskIds.clear()
955
+ this._resetTaskInsightBases()
956
+ }
957
+ return true
880
958
  }
881
959
 
882
960
  /**
883
- * 冲突时采用另一进程的分片:内存里的 record/entries 与磁盘对齐,并让 IDF/驻留账失效。
884
- * 磁盘 entries 可能来自旧版本或损坏文件,和 `_loadSharded` 一样只收 record。
961
+ * 冲突时采用另一进程的分片:内存 record/entries 与磁盘对齐,并让 IDF/驻留账失效。
962
+ * 磁盘 entries 可能损坏或来自旧版本,和 `_loadSharded` 一样只收合法项。
885
963
  */
886
964
  _adoptDiskShard(rel, disk) {
887
965
  const entries = (disk.entries || []).filter(isRecord).map(stripPersistedDerived)
@@ -910,18 +988,32 @@ export class ProjectMemoryStore {
910
988
  }
911
989
  }
912
990
 
991
+ /** 首次写分片前建一次 shards/;之后每次 save 都省掉一次 mkdir。 */
992
+ _ensureShardsDir() {
993
+ if (this._shardsDirReady) return
994
+ mkdirSync(path.join(this.dir, SHARDS_DIR), { recursive: true })
995
+ this._shardsDirReady = true
996
+ }
997
+
998
+ /** 退出/卸载路径的同步兜底(见 util/flush.js)。 */
999
+ flushPending(timeoutMs = 1500) {
1000
+ return this.save({ timeoutMs })
1001
+ }
1002
+
913
1003
  /** 锁竞争后的有限次延迟重试;失败仍保持脏状态,下一次写继续尝试。 */
914
1004
  _scheduleSaveRetry() {
915
- if (this._saveRetryTimer || this._saveRetryAttempts >= 3) return
916
- this._saveRetryAttempts++
1005
+ // 重试总时长必须超过 staleMs=10s(同机崩溃锁由 pid 判活立即回收,这里只兜跨机 stale 锁)。
1006
+ const delays = [100, 500, 2000, 6000, 12000]
1007
+ if (this._saveRetryTimer || this._saveRetryAttempts >= delays.length) return
1008
+ const delay = delays[this._saveRetryAttempts++]
917
1009
  this._saveRetryTimer = setTimeout(() => {
918
1010
  this._saveRetryTimer = null
919
1011
  try {
920
- this.save()
1012
+ this.save({ timeoutMs: 2000 })
921
1013
  } catch (err) {
922
1014
  console.error(`[dsh-project-memory] deferred save failed: ${err?.message || err}`)
923
1015
  }
924
- }, 100)
1016
+ }, delay)
925
1017
  this._saveRetryTimer.unref?.()
926
1018
  }
927
1019
 
@@ -933,10 +1025,8 @@ export class ProjectMemoryStore {
933
1025
  }
934
1026
 
935
1027
  /**
936
- * 写盘前把另一进程已落盘的小文档合并进来。
937
- *
938
- * 只合并不覆盖:同 id 取 `updatedAt` 更新的一侧;本进程删掉的 id 用墓碑挡住,
939
- * 避免“删了又被对方的旧副本复活”。分片不走这里(按 hash 冲突检测)。
1028
+ * 写盘前把另一进程已落盘的小文档合并进来:同 id 取 `updatedAt` 新的一侧,本进程删掉的 id
1029
+ * 用墓碑挡住,避免"删了又被对方的旧副本复活"。分片不走这里(按 hash 冲突检测)。
940
1030
  */
941
1031
  _mergeAuxFromDisk() {
942
1032
  if (this._dirtyInsights) {
@@ -955,7 +1045,12 @@ export class ProjectMemoryStore {
955
1045
  continue
956
1046
  }
957
1047
  const prev = byId.get(it.id)
958
- if (!prev || newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
1048
+ if (!prev) {
1049
+ // 磁盘没有:本进程新建的才补写;否则是**对方删了**,丢掉内存里的旧副本。
1050
+ if (this._createdInsightIds.has(it.id)) byId.set(it.id, it)
1051
+ continue
1052
+ }
1053
+ if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
959
1054
  }
960
1055
  for (const id of this._deletedInsightIds) byId.delete(id)
961
1056
  this.insights = { ...this.insights, items: [...byId.values()] }
@@ -974,8 +1069,20 @@ export class ProjectMemoryStore {
974
1069
  continue
975
1070
  }
976
1071
  const prev = byId.get(t.id)
977
- if (!prev || newerIso(t.updatedAt || t.lastActiveAt, prev.updatedAt || prev.lastActiveAt) >= 0) byId.set(t.id, t)
1072
+ if (!prev) {
1073
+ // 同 insights:磁盘缺失 = 对方删了,只有本进程新建的任务才补写。
1074
+ if (this._createdTaskIds.has(t.id)) byId.set(t.id, t)
1075
+ continue
1076
+ }
1077
+ // 任务级条目单独合并:两边都可能新增/删除,按整条任务的时间戳选一侧会静默丢一边。
1078
+ const base = this._baseTaskInsightIds.get(t.id) || new Set()
1079
+ const mergedInsights = mergeTaskInsights(t, prev, base)
1080
+ const winner = newerIso(t.updatedAt || t.lastActiveAt, prev.updatedAt || prev.lastActiveAt) >= 0 ? t : prev
1081
+ winner.insights = mergedInsights
1082
+ byId.set(t.id, winner)
978
1083
  }
1084
+ // `removeTask` 已把它从内存数组移除,上面循环看不到;不在这里剔除会在同一次 save 里被写回。
1085
+ for (const id of this._deletedTaskIds) byId.delete(id)
979
1086
  this.tasks = [...byId.values()]
980
1087
  this._auxVersion++
981
1088
  }
@@ -1002,8 +1109,7 @@ export class ProjectMemoryStore {
1002
1109
  }
1003
1110
 
1004
1111
  getIdfCache() {
1005
- // IDF 只依赖 entries(title/keywords/summary),所以按 entries 的变更计数失效:
1006
- // 只写经验/insight 或只做存量压实的 save 不会再无谓地重建 IDF。
1112
+ // IDF 只依赖 entries,按 entries 变更计数失效:只写经验/insight 或只做压实不会重建 IDF。
1007
1113
  if (this._idfCache && this._idfCache.version === this._entriesVersion) {
1008
1114
  return this._idfCache.idf
1009
1115
  }
@@ -1018,10 +1124,8 @@ export class ProjectMemoryStore {
1018
1124
  if (N === 0) return {}
1019
1125
  const df = {}
1020
1126
  for (const entry of entries) {
1021
- // 语料必须与**检索**同源:检索走 search.js 的 weightedFieldText = title×5 + keywords
1022
- // + summary + **terms** + sourcePath。此前这里手抄了一份少了 `terms`/`sourcePath` 的
1023
- // 副本,于是只出现在 `terms` 里的词 df=0 → 被当成极稀有词拿虚高 IDF(而 `terms` 正是
1024
- // 0.5.x 为修"只有前 300 字符可检索"加的主检索面)。直接调 makeSearchText,权重自动对齐。
1127
+ // 语料必须与**检索**同源(search.js 的 weightedFieldText 含 title×5、keywords、summary、
1128
+ // terms、sourcePath);手抄副本曾漏掉 terms/sourcePath,让只出现在 terms 里的词拿到虚高 IDF。
1025
1129
  const terms = tokenizeRaw(makeSearchText(entry))
1026
1130
  const seen = new Set(terms)
1027
1131
  for (const t of seen) {
@@ -1103,10 +1207,8 @@ export class ProjectMemoryStore {
1103
1207
  }
1104
1208
 
1105
1209
  /**
1106
- * 这个 store 里有没有任何"事实"。
1107
- *
1108
- * 用于判断"值不值得为一条记账把它落盘":一个从没被索引过、也没写过任何东西的根,
1109
- * 不该因为一次**全局** insight 命中就被建出一个 store 目录(审计侧同理,见 audit.js)。
1210
+ * 这个 store 里有没有任何"事实"。用于判断"值不值得为一条记账把它落盘":从没被索引过、
1211
+ * 也没写过任何东西的根,不该因一次**全局** insight 命中就被建出目录(审计侧同理)。
1110
1212
  * 刻意不调 `stats()`——那个会 `allEntries()` 物化 `searchText`。
1111
1213
  */
1112
1214
  get hasContent() {
@@ -1139,20 +1241,16 @@ export class ProjectMemoryStore {
1139
1241
  }
1140
1242
  out.push(entry)
1141
1243
  }
1142
- // 物化是实打实的内存增量(70119 条目实测 +34MB),必须进上界——按文件替换,
1143
- // 与写路径同一套语义:之后重写 / 删掉这个文件时会连这笔一起替换掉。
1244
+ // 物化是实打实的内存增量(70119 条目实测 +34MB),必须进上界——按文件替换,与写路径同语义。
1144
1245
  if (addedChars) this._setFileTextChars(relPath, (this._fileTextChars.get(relPath) || 0) + addedChars)
1145
1246
  }
1146
- // 物化只改 entry 对象、不改 entries 的构成,所以 `_entriesVersion` 不会动;但驻留会实打实
1147
- // 增加。这里是它的第二个失效键——漏了它,估算就停在物化前的水位。
1247
+ // 物化只改 entry 对象、不改 entries 构成,`_entriesVersion` 不动,所以要单独的失效键。
1148
1248
  if (materialized) this._materializeVersion++
1149
1249
  return out
1150
1250
  }
1151
1251
 
1152
- // v0.4 的 experience 读写入口(addExperience / pruneExperience / findSupersede / removeExperience)
1153
- // 已随统一存储删除:经验笔记现在是 `kind:'experience'` 的 insight,写入走 `src/tools/remember.js`
1154
- // → `saveInsight`,删除走 `removeMemory`,容量归 insight 层的 maxProject。
1155
- // `experience.json` 只剩一个角色:`_migrateExperienceToInsights` 的导入源。
1252
+ // v0.4 的 experience 读写入口已随统一存储删除:经验笔记现在是 `kind:'experience'` 的 insight,
1253
+ // `experience.json` 只剩 `_migrateExperienceToInsights` 的导入源这一个角色。
1156
1254
 
1157
1255
  stats() {
1158
1256
  return {
@@ -1178,7 +1276,10 @@ export class ProjectMemoryStore {
1178
1276
 
1179
1277
  addTask(task) {
1180
1278
  this.tasks.push(task)
1181
- if (task?.id) this._deletedTaskIds.delete(task.id)
1279
+ if (task?.id) {
1280
+ this._deletedTaskIds.delete(task.id)
1281
+ this._createdTaskIds.add(task.id)
1282
+ }
1182
1283
  this._dirtyTasks = true
1183
1284
  this._auxVersion++
1184
1285
  }
@@ -1204,8 +1305,8 @@ export class ProjectMemoryStore {
1204
1305
  }
1205
1306
 
1206
1307
  /**
1207
- * 清掉所有指向该任务的会话绑定。归档/删除任务时调用:任务已停用,绑定再留着
1208
- * 只会在下一次 todo 写入时被当成"没有任务"再建一条新任务,旧条目却永远占着 binding.json。
1308
+ * 清掉所有指向该任务的会话绑定。任务已停用时绑定再留着,只会在下一次 todo 写入时被
1309
+ * 当成"没有任务"再建一条,旧条目却永远占着 binding.json。
1209
1310
  * @param {string} taskId
1210
1311
  * @returns {boolean} 是否真的删掉了绑定
1211
1312
  */
@@ -1247,14 +1348,10 @@ export class ProjectMemoryStore {
1247
1348
 
1248
1349
  /**
1249
1350
  * 每项目任务数上限随项目体积自适应;超限按 lastActiveAt 归档最旧(只统计非归档)。
1250
- *
1251
- * **仍被会话绑定的任务不参与裁剪**(这条是修 bug,不是放宽上限):
1252
- * 绑定 = "这个任务还没结束,某个会话随时会回来接着干"。旧实现按 `lastActiveAt` 一刀切,
1253
- * 一个长期挂着的绑定任务会被更新的任务挤到最旧、被静默归档;会话回来写 todo 时,
1254
- * `taskbridge` 把"归档"按"停止同步"处理(那是归档的文档语义),于是**另建一条新任务**——
1255
- * 同一个会话的历史被静默拆成两条记录,原条目变成归档孤儿。
1256
- * 代价是活跃列表可能比上限多出"绑定任务数"条;这是刻意取舍:上限只是启发式,
1257
- * 而"别把用户正在做的任务从脚底下抽走"是正确性。想真正停掉一个任务,先解绑或显式归档。
1351
+ * **仍被会话绑定的任务不参与裁剪**:绑定意味着"任务还没结束,某个会话随时会回来接着干"。
1352
+ * 一刀切会把长期挂着的绑定任务静默归档,会话回来写 todo 时会另建一条新任务,历史被拆成
1353
+ * 两条、原条目成归档孤儿。代价是活跃列表可能多出绑定任务数条——这是刻意取舍;想真正
1354
+ * 停掉一个任务,先解绑或显式归档。
1258
1355
  * @returns {number} 本轮归档的条数
1259
1356
  */
1260
1357
  pruneTasks() {
@@ -1276,8 +1373,8 @@ export class ProjectMemoryStore {
1276
1373
 
1277
1374
  /**
1278
1375
  * @param {(store: ProjectMemoryStore) => any} fn 变更函数
1279
- * @param {{save?: boolean}} [options] save=false 时只标脏,由调用方在回合结束统一 flush。
1280
- * 文件工具每读一次都会更新任务热点,逐次落盘会把 tasks.json 写成每工具调用一次。
1376
+ * @param {{save?: boolean}} [options] save=false 时只标脏,由调用方在回合结束统一 flush
1377
+ * (文件工具每读一次都会更新任务热点,逐次落盘会把 tasks.json 写成每工具调用一次)。
1281
1378
  */
1282
1379
  commit(fn, options = {}) {
1283
1380
  const result = fn(this)