@yolk_vat-y/dsh-project-memory 0.6.11 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +104 -120
  2. package/README.md +14 -105
  3. package/README.zh-CN.md +14 -105
  4. package/client/client.js +228 -95
  5. package/client/client.js.map +1 -1
  6. package/package.json +2 -2
  7. package/scripts/file-peak.mjs +1 -1
  8. package/scripts/tool-schema-size.mjs +1 -1
  9. package/skills/project-memory/SKILL.md +1 -1
  10. package/skills/project-memory/scripts/pm-digest.mjs +20 -6
  11. package/src/audit.js +10 -2
  12. package/src/auto-inject.js +124 -38
  13. package/src/client/MemoryView.tsx +119 -40
  14. package/src/client/TaskCommandNode.tsx +6 -4
  15. package/src/client/TaskComponents.tsx +13 -16
  16. package/src/client/TaskPanel.tsx +41 -15
  17. package/src/client/client.ts +4 -7
  18. package/src/client/paging.js +1 -14
  19. package/src/client/settings-card.tsx +9 -0
  20. package/src/client/task-data-store.ts +57 -7
  21. package/src/client/task-hooks.ts +0 -2
  22. package/src/client/task-scope.js +16 -1
  23. package/src/client/task-ui-store.ts +1 -1
  24. package/src/commands/insight-actions.js +91 -94
  25. package/src/commands/task-actions.js +7 -5
  26. package/src/commands/tasks.js +34 -10
  27. package/src/doc-index.js +3 -1
  28. package/src/enhancer.js +0 -12
  29. package/src/index-failures.js +1 -1
  30. package/src/index-pipeline.js +11 -2
  31. package/src/index.js +60 -14
  32. package/src/inject-visible.js +282 -0
  33. package/src/insight-store.js +133 -68
  34. package/src/lazy.js +29 -23
  35. package/src/llm-route.js +1 -1
  36. package/src/llm.js +1 -8
  37. package/src/ops.js +18 -5
  38. package/src/parsers/pdfjs-parser.js +3 -33
  39. package/src/project-memory-service.js +195 -0
  40. package/src/project-profile.js +0 -4
  41. package/src/setup/taskbridge.js +38 -6
  42. package/src/store.js +639 -147
  43. package/src/symbols.js +2 -4
  44. package/src/tools/context.js +14 -0
  45. package/src/tools/forget.js +7 -17
  46. package/src/tools/index-doc.js +62 -21
  47. package/src/tools/index-repo.js +17 -15
  48. package/src/tools/lesson-tools.js +10 -13
  49. package/src/tools/output.js +33 -0
  50. package/src/tools/query-memory.js +7 -12
  51. package/src/tools/remember.js +8 -18
  52. package/src/tools/stats.js +4 -9
  53. package/src/tools/task-tools.js +23 -22
  54. package/src/tools/watch-repo.js +16 -15
  55. package/src/util/flush.js +1 -1
  56. package/src/util/fs.js +135 -20
  57. package/src/util/insight-fields.js +22 -0
  58. package/src/util/message-source.js +20 -0
  59. package/src/util/relative-time.js +24 -0
  60. package/src/util/search.js +0 -1
  61. package/src/util/task-view.js +8 -15
  62. package/src/util/value.js +16 -0
  63. package/src/vector-index.js +2 -2
  64. package/src/watch.js +25 -8
  65. package/client/client.d.ts +0 -27
  66. package/client/client.d.ts.map +0 -1
  67. package/client/style.css +0 -395
package/src/store.js CHANGED
@@ -2,10 +2,11 @@ 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, storeKey, unlinkWithRetry, writeJsonAtomic } from './util/fs.js'
5
+ import { acquireDirLock, ensureSelfIgnoreDir, storeKey, unlinkWithRetry, writeJsonAtomic } from './util/fs.js'
6
6
  import { debugPersistence } from './util/persist.js'
7
7
  import { trackDirty, untrackDirty } from './util/flush.js'
8
8
  import { backfillDerivedTriggers } from './readiness.js'
9
+ import { isRecord, newerIso } from './util/value.js'
9
10
 
10
11
  const FORMAT_FILE = 'format.json'
11
12
  const INDEX_FILE = 'index.json'
@@ -16,7 +17,6 @@ const BINDING_FILE = 'binding.json'
16
17
  const WATCH_FILE = 'watch.json'
17
18
  const INSIGHTS_FILE = 'insights.json'
18
19
  const SHARDS_DIR = 'shards'
19
- const GITIGNORE_FILE = '.gitignore'
20
20
  /** ≤0.5.10 的 TS 增强结果缓存目录;0.5.11 起废弃并自愈清理。 */
21
21
  const LEGACY_TYPE_CACHE_DIR = 'type-cache'
22
22
 
@@ -158,7 +158,7 @@ function auxCharsOf(store) {
158
158
  /**
159
159
  * 单个 store 的驻留估算:数**内存里留下的对象图**,按版本记忆化。不用读盘文本量换算——
160
160
  * `searchText` 要到 `allEntries()` 才物化,前后估出两个数(实测 76MB → 107MB),且被
161
- * `stripPersistedDerived` 删掉的字段也会被算进去。`_entriesVersion` 与 `_materializeVersion`
161
+ * `withoutPersistedDerived` 删掉的字段也会被算进去。`_entriesVersion` 与 `_materializeVersion`
162
162
  * 都参与失效;一次全量遍历 70119 条目 ~40ms,逐出又会遍历整个缓存,所以必须记忆化。
163
163
  */
164
164
  export function _estimateResidentBytes(store) {
@@ -233,20 +233,14 @@ export function _storeCacheKeysForTest() {
233
233
  return [...storeCache.keys()]
234
234
  }
235
235
 
236
- /** 已就"无法迁移的旧 store"告警过的目录:避免每次 load() 都刷一行。 */
237
- const migrationWarned = new Set()
238
-
239
- /** 纯对象判定(排除 null / 数组):磁盘读入的 JSON 形状校验统一走它。 */
240
- function isRecord(value) {
241
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
236
+ /** 仅供测试:清空进程内 store 缓存,让下一次 load 真的走磁盘。 */
237
+ export function _clearStoreCacheForTest() {
238
+ storeCache.clear()
239
+ storeCacheAlias.clear()
242
240
  }
243
241
 
244
- /** 两个 ISO 时间戳的先后;缺失/非法一律 0,保证可比较。 */
245
- function newerIso(a, b) {
246
- const ta = Date.parse(a || '') || 0
247
- const tb = Date.parse(b || '') || 0
248
- return ta - tb
249
- }
242
+ /** 已就"无法迁移的旧 store"告警过的目录:避免每次 load() 都刷一行。 */
243
+ const migrationWarned = new Set()
250
244
 
251
245
  /**
252
246
  * 合并同一任务在两份快照里的 `insights`:以**上次落盘的 id 基线**做三方判断,基线没有、
@@ -257,6 +251,54 @@ function newerIso(a, b) {
257
251
  * @param {Set<string>} base
258
252
  * @returns {object[]}
259
253
  */
254
+ /**
255
+ * 跨进程任务合并时的文件热点并集:两侧各自累加计数,整条任务二选一会把另一侧新增的文件静默回滚。
256
+ * 计数取 max(同一文件两边各加一次时无法区分重试与真实两次,宁可少记不可回滚),时间取最新。
257
+ */
258
+ function mergeTaskFileState(a, b) {
259
+ const meta = {}
260
+ for (const task of [a, b]) {
261
+ if (!task || !isRecord(task)) continue
262
+ const src = isRecord(task.fileMeta) ? task.fileMeta : {}
263
+ for (const rel of Array.isArray(task.files) ? task.files : []) {
264
+ if (typeof rel !== 'string' || !rel) continue
265
+ const prev = meta[rel] || { n: 0, writes: 0, reads: 0 }
266
+ const cur = isRecord(src[rel]) ? src[rel] : {}
267
+ const next = {
268
+ ...prev,
269
+ ...cur,
270
+ n: Math.max(prev.n || 0, cur.n || 0),
271
+ writes: Math.max(prev.writes || 0, cur.writes || 0),
272
+ reads: Math.max(prev.reads || 0, cur.reads || 0),
273
+ }
274
+ // 不能先 `...cur` 再条件覆盖:条件为假时留下的正是 cur 的旧时间。时间取最新必须显式计算。
275
+ const writeAt = newerIso(cur.lastWriteAt, prev.lastWriteAt) >= 0
276
+ ? (cur.lastWriteAt || prev.lastWriteAt)
277
+ : (prev.lastWriteAt || cur.lastWriteAt)
278
+ const readAt = newerIso(cur.lastReadAt, prev.lastReadAt) >= 0
279
+ ? (cur.lastReadAt || prev.lastReadAt)
280
+ : (prev.lastReadAt || cur.lastReadAt)
281
+ if (writeAt) next.lastWriteAt = writeAt
282
+ else delete next.lastWriteAt
283
+ if (readAt) next.lastReadAt = readAt
284
+ else delete next.lastReadAt
285
+ meta[rel] = next
286
+ }
287
+ }
288
+ const files = Object.keys(meta).sort((x, y) => {
289
+ const A = meta[x]
290
+ const B = meta[y]
291
+ const aw = A.lastWriteAt ? 1 : 0
292
+ const bw = B.lastWriteAt ? 1 : 0
293
+ if (aw !== bw) return bw - aw
294
+ if (aw) return String(B.lastWriteAt).localeCompare(String(A.lastWriteAt))
295
+ return String(B.lastReadAt || '').localeCompare(String(A.lastReadAt || ''))
296
+ }).slice(0, 100)
297
+ const trimmed = {}
298
+ for (const rel of files) trimmed[rel] = meta[rel]
299
+ return { files, fileMeta: trimmed }
300
+ }
301
+
260
302
  function mergeTaskInsights(local, disk, base) {
261
303
  const merged = new Map()
262
304
  for (const ins of Array.isArray(disk?.insights) ? disk.insights : []) {
@@ -279,9 +321,10 @@ function mergeTaskInsights(local, disk, base) {
279
321
  }
280
322
 
281
323
  /**
282
- * 落盘的 entry 只保留**不可推导的事实**,两个派生字段永不写盘:`linkedSymbols` 是跨实体
324
+ * 落盘的 entry 只保留**不可推导的事实**,三个派生字段永不写盘:`linkedSymbols` 是跨实体
283
325
  * 派生(取决于符号表当前状态,读取期由 src/link.js 解算),`searchText` 是自派生(只依赖
284
- * 本 entry,由 `allEntries()` 在内存里物化)。旧 store 的这两个字段加载时剥掉,下次写盘自然压实。
326
+ * 本 entry,由 `allEntries()` 在内存里物化),`typeSig` 是增强器的实现细节。旧 store 的
327
+ * 这些字段加载时剥掉,下次写盘自然压实。
285
328
  */
286
329
  const PERSISTED_DERIVED = ['linkedSymbols', 'searchText', 'typeSig']
287
330
  const PERSISTED_DERIVED_SET = new Set(PERSISTED_DERIVED)
@@ -312,16 +355,10 @@ function rebuildWithoutDerived(entry) {
312
355
  }
313
356
 
314
357
  /**
315
- * 剥掉派生字段(加载路径用)。没有派生字段时**原对象返回**(零分配热路径)。
316
- * @returns {object} 不含派生字段的条目(可能是同一个对象)
358
+ * 返回不含派生字段的条目(加载/写盘共用)。没有派生字段时**原对象返回**(零分配热路径),
359
+ * 有派生字段时重建而不是 `delete`(避免 V8 字典模式)。加载路径复用返回值即可,写盘路径
360
+ * 不能动内存对象。
317
361
  */
318
- function stripPersistedDerived(entry) {
319
- if (!entry || typeof entry !== 'object') return entry
320
- if (!hasPersistedDerived(entry)) return entry
321
- return rebuildWithoutDerived(entry)
322
- }
323
-
324
- /** 返回不含派生字段的条目(写盘路径用,不能动内存里的对象)。 */
325
362
  function withoutPersistedDerived(entry) {
326
363
  if (!entry || typeof entry !== 'object') return entry
327
364
  if (!hasPersistedDerived(entry)) return entry
@@ -330,14 +367,19 @@ function withoutPersistedDerived(entry) {
330
367
 
331
368
  /** 仅供测试:加载/写盘路径的剥离实现(内存形状由测试用 --expose-gc 度量)。 */
332
369
  export function _stripPersistedDerivedForTest(entry) {
333
- return stripPersistedDerived(entry)
370
+ return withoutPersistedDerived(entry)
334
371
  }
335
372
 
336
- function loadJson(filePath, fallback, counter) {
373
+ function loadJson(filePath, fallback, counter, errorSink) {
337
374
  let raw
338
375
  try {
339
376
  raw = readFileSync(filePath, 'utf8')
340
- } catch {
377
+ } catch (err) {
378
+ // ENOENT 才是“真的没有”;EACCES/EISDIR/EIO/EMFILE 是读失败,不能当成删除。
379
+ if (err?.code !== 'ENOENT') {
380
+ errorSink?.add(filePath)
381
+ debugPersistence(`[dsh-project-memory] cannot read ${filePath}: ${err?.code || err?.message || err}`)
382
+ }
341
383
  return fallback
342
384
  }
343
385
  // 累计读盘文本字符数,只供 `residentBoundBytes` 判断要不要精确计量。
@@ -360,6 +402,35 @@ function shardRelPath(dir, rel) {
360
402
  return path.join(dir, SHARDS_DIR, createHash('sha256').update(rel).digest('hex') + '.json')
361
403
  }
362
404
 
405
+ const BUCKET_TARGET_BYTES = 32 * 1024
406
+ const BUCKET_COUNT_MAX = 4096
407
+
408
+ /** 目标尺寸桶的路径;`bucketCount` 变化时索引会整体重排。 */
409
+ function bucketRelPath(dir, index) {
410
+ return path.join(dir, SHARDS_DIR, `bucket-${String(index).padStart(5, '0')}.json`)
411
+ }
412
+
413
+ /** 源文件 → 唯一桶:sha256(relPath) 前 4 字节 mod bucketCount。 */
414
+ function bucketIndexOf(rel, count) {
415
+ if (count <= 1) return 0
416
+ const digest = createHash('sha256').update(rel).digest()
417
+ return digest.readUInt32BE(0) % count
418
+ }
419
+
420
+ function chooseBucketCount(bytes) {
421
+ return Math.max(1, Math.min(BUCKET_COUNT_MAX, Math.ceil(bytes / BUCKET_TARGET_BYTES)))
422
+ }
423
+
424
+ /** 全量重排时的体积估计(只在迁移/扩容时跑一次,不进出日常 save)。 */
425
+ function estimateShardBytes(files, entries) {
426
+ let total = 0
427
+ for (const rel of Object.keys(files)) {
428
+ total += 96 + rel.length + JSON.stringify(files[rel]).length
429
+ total += JSON.stringify((entries[rel] || []).map(withoutPersistedDerived)).length
430
+ }
431
+ return total
432
+ }
433
+
363
434
  /**
364
435
  * watch.json 去重:Windows/macOS 上 `D:\proj` 与 `d:\PROJ` 是同一个物理目录,字符串却不同。
365
436
  * 同一目录写两条会让 watch 每轮扫两遍、`watch_repo({watch:false})` 也只删掉其中一条(另一条
@@ -401,17 +472,34 @@ export class ProjectMemoryStore {
401
472
  this.watchlist = []
402
473
  this._dirtyShards = new Set()
403
474
  this._removedShards = new Set()
475
+ /** 分片布局:v3 = 目标尺寸哈希桶;v2 = 一文件一 shard(迁移期)。 */
476
+ this._layout = 'v3'
477
+ this._bucketCount = 0
478
+ this._bucketSize = BUCKET_TARGET_BYTES
479
+ this._needsShardRewrite = false
480
+ this._formatDoc = null
481
+ this._formatDirty = false
482
+ /** 非 ENOENT 读失败:整库置只读,任何 save 都不写,避免把“读不到”当空库覆盖。 */
483
+ this._readErrors = new Set()
484
+ this._readOnly = false
485
+ this._readOnlyWarned = false
486
+ /** 距上次桶数校准累计的 shard 变更数:避免每次 save 都做 O(N) 体积估算。 */
487
+ this._shardOpsSinceResize = 0
404
488
  /** 加载时的分片 hash:跨进程写冲突检测的基准。 */
405
489
  this._baseFileSha = new Map()
406
490
  /** 本地删除留痕:合并另一进程的磁盘状态时不能把它们复活。 */
407
491
  this._deletedInsightIds = new Set()
408
492
  this._deletedTaskIds = new Set()
409
493
  this._deletedBindings = new Set()
494
+ /** 加载/上次成功落盘时的会话绑定:跨进程合并时区分“本地改过”与“只是旧快照”。 */
495
+ this._baseBinding = new Map()
410
496
  this._removedWatch = new Set()
411
497
  /** 上次落盘/加载时的 insight id 集合:原地 splice 的删除也要能被合并逻辑看见。 */
412
498
  this._baseInsightIds = new Set()
413
499
  /** task.id → 上次落盘/加载时该任务的 insight id 集合(任务级条目的合并基线,见 mergeTaskInsights)。 */
414
500
  this._baseTaskInsightIds = new Map()
501
+ /** task.id → 加载/上次落盘时的 archived:只看 updatedAt 会把显式归档/解归档回滚。 */
502
+ this._baseTaskArchived = new Map()
415
503
  /**
416
504
  * 本进程**新建**的条目。"磁盘没有但内存有"可能是新建(要补写)也可能是**对方删了**
417
505
  * (不能写回);没有这个集合,后者会被复活。
@@ -503,6 +591,15 @@ export class ProjectMemoryStore {
503
591
  console.error(`[dsh-project-memory] ${message}`)
504
592
  }
505
593
 
594
+ _warnReadOnly() {
595
+ if (this._readOnlyWarned) return
596
+ this._readOnlyWarned = true
597
+ console.error(
598
+ `[dsh-project-memory] store ${this.dir} has unreadable files; writes are disabled until permissions are fixed and dsh restarts. ` +
599
+ 'Nothing was overwritten.',
600
+ )
601
+ }
602
+
506
603
  _migrateLegacyIfNeeded() {
507
604
  const formatPath = path.join(this.dir, FORMAT_FILE)
508
605
  const formatDoc = loadJson(formatPath, null)
@@ -608,7 +705,10 @@ export class ProjectMemoryStore {
608
705
  * **不进** `_textChars`(那份账只跟 entries),交给 `auxCharsOf` 按对象图直接算。
609
706
  */
610
707
  _loadJson(filePath, fallback) {
611
- return loadJson(filePath, fallback)
708
+ const before = this._readErrors.size
709
+ const value = loadJson(filePath, fallback, undefined, this._readErrors)
710
+ if (this._readErrors.size > before) this._readOnly = true
711
+ return value
612
712
  }
613
713
 
614
714
  /** 按文件记文本量:替换而不是累加,重写同一个文件不会算两遍。 */
@@ -644,24 +744,62 @@ export class ProjectMemoryStore {
644
744
  }
645
745
 
646
746
  _loadSharded() {
747
+ const formatDoc = loadJson(path.join(this.dir, FORMAT_FILE), null, undefined, this._readErrors)
748
+ this._formatDoc = formatDoc
749
+ if (formatDoc && typeof formatDoc.version === 'number' && formatDoc.version >= 3) {
750
+ this._layout = 'v3'
751
+ this._bucketCount = Number.isFinite(formatDoc.bucketCount)
752
+ ? Math.max(1, Math.min(BUCKET_COUNT_MAX, Math.floor(formatDoc.bucketCount)))
753
+ : 0
754
+ this._bucketSize = Number.isFinite(formatDoc.bucketSize) ? formatDoc.bucketSize : BUCKET_TARGET_BYTES
755
+ } else {
756
+ this._layout = formatDoc ? 'v2' : 'v3'
757
+ this._bucketCount = 0
758
+ this._needsShardRewrite = formatDoc !== null
759
+ }
647
760
  let shardNames = []
648
761
  try {
649
762
  shardNames = readdirSync(path.join(this.dir, SHARDS_DIR)).filter((n) => n.endsWith('.json'))
650
763
  } catch {
651
764
  shardNames = []
652
765
  }
766
+ let sawLegacy = false
767
+ const sourceRank = new Map()
653
768
  for (const name of shardNames) {
769
+ // v3 只认当前 bucketCount 内的桶:越界桶是缩桶后 cleanup 失败/崩溃的残留,
770
+ // 读它会让已删除条目复活(cleanup 修复前尤其常见)。
771
+ const bucketMatch = /^bucket-(\d{5})\.json$/.exec(name)
772
+ if (bucketMatch && this._layout === 'v3' && this._bucketCount > 0
773
+ && Number(bucketMatch[1]) >= this._bucketCount) continue
654
774
  const counter = { chars: 0 }
655
- const shard = loadJson(path.join(this.dir, SHARDS_DIR, name), null, counter)
656
- if (!shard || typeof shard.relPath !== 'string' || !isRecord(shard.record)) continue
657
- this._setFileTextChars(shard.relPath, counter.chars)
658
- this.files[shard.relPath] = shard.record
659
- this._baseFileSha.set(shard.relPath, shard.record.sha256 ?? null)
660
- // 畸形 shard(entries 不是数组)不能让 `for…of` 抛错,否则一个坏文件会拖垮每次读取。
661
- const list = Array.isArray(shard.entries) ? shard.entries.filter(isRecord) : []
662
- // 老分片带着派生字段:内存里立刻剥掉,并排队等 save() 把磁盘上也压实。
663
- if (list.some((e) => PERSISTED_DERIVED.some((k) => k in e))) this._compactQueue.add(shard.relPath)
664
- this.entries[shard.relPath] = list.map(stripPersistedDerived)
775
+ const doc = loadJson(path.join(this.dir, SHARDS_DIR, name), null, counter, this._readErrors)
776
+ if (!doc) continue
777
+ // v3 是 { items: [...] };v2 是一文件一 shard 的 { relPath, record, entries }。
778
+ const isBucket = Array.isArray(doc.items)
779
+ const items = isBucket ? doc.items : [doc]
780
+ for (const item of items) {
781
+ if (!item || typeof item.relPath !== 'string' || !isRecord(item.record)) continue
782
+ // 迁移崩溃窗口里同一 rel 可能同时出现在旧分片与新桶:取 indexedAt 更新的一份;
783
+ // 时间相同优先 v3 桶(新布局)。
784
+ const prev = this.files[item.relPath]
785
+ const prevAt = prev ? (Date.parse(prev.indexedAt || '') || 0) : -1
786
+ const nextAt = Date.parse(item.record.indexedAt || '') || 0
787
+ if (prev && prevAt > nextAt) continue
788
+ if (prev && prevAt === nextAt && !isBucket && sourceRank.get(item.relPath) === 1) continue
789
+ sourceRank.set(item.relPath, isBucket ? 1 : 0)
790
+ this.files[item.relPath] = item.record
791
+ this._baseFileSha.set(item.relPath, item.record.sha256 ?? null)
792
+ // 畸形 shard(entries 不是数组)不能让 `for…of` 抛错,否则一个坏文件会拖垮每次读取。
793
+ const list = Array.isArray(item.entries) ? item.entries.filter(isRecord) : []
794
+ this._setFileTextChars(item.relPath, Array.isArray(doc.items) ? JSON.stringify(item).length : counter.chars)
795
+ if (list.some((e) => PERSISTED_DERIVED.some((k) => k in e))) this._compactQueue.add(item.relPath)
796
+ this.entries[item.relPath] = list.map(withoutPersistedDerived)
797
+ }
798
+ if (!isBucket) sawLegacy = true
799
+ }
800
+ // v2/混合布局/桶数缺失:下一次 save 做一次全量重排。
801
+ if (sawLegacy || this._layout !== 'v3' || this._bucketCount === 0) {
802
+ if (Object.keys(this.files).length > 0) this._needsShardRewrite = true
665
803
  }
666
804
  this._entriesVersion++
667
805
  this.experience = this._loadJson(path.join(this.dir, EXPERIENCE_FILE), [])
@@ -694,6 +832,7 @@ export class ProjectMemoryStore {
694
832
  }
695
833
  const bindingDoc = this._loadJson(path.join(this.dir, BINDING_FILE), {})
696
834
  this.binding = isRecord(bindingDoc) ? bindingDoc : {}
835
+ this._baseBinding = new Map(Object.entries(this.binding))
697
836
  const watchDoc = this._loadJson(path.join(this.dir, WATCH_FILE), [])
698
837
  const rawWatch = Array.isArray(watchDoc) ? watchDoc.filter((r) => typeof r === 'string' && r) : []
699
838
  // 老版本可能把同一个物理目录按不同大小写写了两条(Windows/macOS 大小写不敏感):
@@ -706,6 +845,8 @@ export class ProjectMemoryStore {
706
845
  // 这四个集合的内容刚刚被换掉,让 auxCharsOf/精确估算重算(而不是沿用上一份实例的账)。
707
846
  this._auxVersion++
708
847
  this._formatWritten = existsSafe(path.join(this.dir, FORMAT_FILE))
848
+ this._readOnly = this._readErrors.size > 0
849
+ if (this._readOnly) this._warnReadOnly()
709
850
  }
710
851
 
711
852
  /**
@@ -897,29 +1038,25 @@ export class ProjectMemoryStore {
897
1038
  * 本进程剩余生命周期都不再自我忽略,store 可能被下一次 `git add` 带进提交。
898
1039
  */
899
1040
  ensureSelfIgnore() {
900
- if (!existsSafe(this.dir)) return
901
- const file = path.join(this.dir, GITIGNORE_FILE)
902
- if (existsSafe(file)) return
903
- try {
904
- writeFileSync(file, '# dsh-project-memory: local by default. `git add -f` to commit it.\n*\n')
905
- } catch {
906
- // 旁路:写不进去不影响存储本身
907
- }
1041
+ ensureSelfIgnoreDir(this.dir)
908
1042
  }
909
1043
 
910
1044
  /** 重新记下每个任务当前可见的 insight id:只在加载成功 / 整份 tasks 落盘成功后调用。 */
911
1045
  _resetTaskInsightBases() {
912
1046
  this._baseTaskInsightIds = new Map()
1047
+ this._baseTaskArchived = new Map()
913
1048
  for (const task of Array.isArray(this.tasks) ? this.tasks : []) {
914
1049
  if (!task?.id) continue
915
1050
  const ids = Array.isArray(task.insights) ? task.insights.map((it) => it?.id).filter(Boolean) : []
916
1051
  this._baseTaskInsightIds.set(task.id, new Set(ids))
1052
+ this._baseTaskArchived.set(task.id, task.archived === true)
917
1053
  }
918
1054
  }
919
1055
 
920
1056
  /** 是否有待落盘的变更;逐出缓存前用它避免为干净 store 触发 save 的旁路副作用。 */
921
1057
  hasDirty() {
922
1058
  return this._compactQueue.size > 0
1059
+ || this._needsShardRewrite
923
1060
  || this._dirtyShards.size > 0
924
1061
  || this._removedShards.size > 0
925
1062
  || this._dirtyInsights
@@ -943,6 +1080,7 @@ export class ProjectMemoryStore {
943
1080
  const hasContent = this.hasContent
944
1081
  const dirty =
945
1082
  compacting ||
1083
+ this._needsShardRewrite ||
946
1084
  this._dirtyShards.size > 0 ||
947
1085
  this._removedShards.size > 0 ||
948
1086
  this._dirtyInsights ||
@@ -950,6 +1088,29 @@ export class ProjectMemoryStore {
950
1088
  this._dirtyBinding ||
951
1089
  this._dirtyWatch ||
952
1090
  (!this._formatWritten && !this._legacyBlocked && hasContent)
1091
+ if (this._readOnly) {
1092
+ // 权限/瞬时占用修好后允许同一进程重试;只有全部读错误消失才解除只读。
1093
+ let recovered = true
1094
+ for (const file of this._readErrors) {
1095
+ try {
1096
+ readFileSync(file)
1097
+ } catch (err) {
1098
+ if (err?.code !== 'ENOENT') {
1099
+ recovered = false
1100
+ break
1101
+ }
1102
+ }
1103
+ }
1104
+ if (recovered) {
1105
+ this._readErrors.clear()
1106
+ this._readOnly = false
1107
+ } else {
1108
+ this.lastSaveOk = false
1109
+ trackDirty(this)
1110
+ this._warnReadOnly()
1111
+ return false
1112
+ }
1113
+ }
953
1114
  if (dirty) {
954
1115
  // 目录可能在 load 之后被外部删掉:`_storeDirReady` 只当"上次写过"的快路径,命中时补一次
955
1116
  // stat;失配就重建目录,并让分片/格式/忽略三处的已就绪状态一起失效。
@@ -1004,73 +1165,22 @@ export class ProjectMemoryStore {
1004
1165
  let removalFailed = false
1005
1166
  try {
1006
1167
  // 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
1007
- this._mergeAuxFromDisk()
1008
- if (!this._formatWritten && !this._legacyBlocked) {
1009
- writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' }, { ensureDir: false })
1010
- this._formatWritten = true
1011
- }
1012
- // 存量压实:≤0.5.10 的分片带派生字段,只有重写才消失。每轮最多 COMPACT_BATCH 个,
1013
- // 让升级后的 store 在后续任意一次 save 里自动收敛。
1014
- let compactBudget = COMPACT_BATCH
1015
- for (const rel of this._compactQueue) {
1016
- if (compactBudget <= 0) break
1017
- compactBudget--
1018
- this._compactQueue.delete(rel)
1019
- if (this.files[rel]) this._dirtyShards.add(rel)
1020
- }
1021
- for (const rel of this._dirtyShards) {
1022
- if (this.files[rel]) {
1023
- const nextSha = this.files[rel].sha256 ?? null
1024
- const base = this._baseFileSha.get(rel) ?? null
1025
- const disk = this._shardDiskRecord(rel)
1026
- // 磁盘分片加载后被别的进程改过:按 indexedAt 收敛,本地更新则覆盖,对方更新则读回内存。
1027
- if (disk.exists && disk.sha !== base && disk.sha !== nextSha) {
1028
- const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
1029
- const diskAt = Date.parse(disk.record?.indexedAt || '') || 0
1030
- if (localAt > diskAt) {
1031
- this._ensureShardsDir()
1032
- writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
1033
- this._baseFileSha.set(rel, nextSha)
1034
- continue
1035
- }
1036
- this._adoptDiskShard(rel, disk)
1037
- this._warnConflict(rel)
1038
- continue
1039
- }
1040
- this._ensureShardsDir()
1041
- writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
1042
- this._baseFileSha.set(rel, nextSha)
1043
- } else {
1044
- this._removedShards.add(rel)
1045
- }
1046
- }
1047
- this._dirtyShards.clear()
1048
- for (const rel of this._removedShards) {
1049
- const base = this._baseFileSha.get(rel) ?? null
1050
- const disk = this._shardDiskRecord(rel)
1051
- if (disk.exists && disk.sha !== base) {
1052
- // 删除与另一进程的更新撞车:没有删除时间戳可比,保守采用对方版本,让内存与磁盘一致。
1053
- this._adoptDiskShard(rel, disk)
1054
- this._warnConflict(rel)
1055
- this._removedShards.delete(rel)
1056
- continue
1057
- }
1058
- try {
1059
- // 删除也要对 Windows 瞬时占用重试;失败时**保留删除意图**,否则下一次 load 会把
1060
- // 这个 shard 里的旧条目复活(`unlinkSync` 的 EPERM 曾经被 catch 成"已经没了")。
1061
- unlinkWithRetry(shardRelPath(this.dir, rel))
1062
- } catch (err) {
1063
- if (err?.code !== 'ENOENT') {
1064
- removalFailed = true
1065
- console.error(
1066
- `[dsh-project-memory] could not delete shard for ${rel}: ${err?.message || err}; will retry`,
1067
- )
1068
- continue
1069
- }
1070
- }
1071
- this._removedShards.delete(rel)
1072
- this._baseFileSha.delete(rel)
1168
+ // 合并中读到坏文件(EACCES/EISDIR)时绝不能继续写:那会用本进程旧快照覆盖读不出来的
1169
+ // 文件,恰好丢掉另一进程刚写的条目。
1170
+ if (!this._mergeAuxFromDisk()) {
1171
+ this.lastSaveOk = false
1172
+ trackDirty(this)
1173
+ this._warnReadOnly()
1174
+ this._scheduleSaveRetry()
1175
+ return false
1073
1176
  }
1177
+ const shardWork = this._dirtyShards.size > 0
1178
+ || this._removedShards.size > 0
1179
+ || this._needsShardRewrite
1180
+ || this._compactQueue.size > 0
1181
+ || !this._formatWritten
1182
+ || this._formatDirty
1183
+ if (shardWork && !this._saveShards()) removalFailed = true
1074
1184
  if (this._dirtyInsights) {
1075
1185
  // v2 → v3 是纯语义升级,形状不变;老版本读到 v3 仍按 v2 字段解析。
1076
1186
  if (this.insights && this.insights.version !== 3) this.insights.version = 3
@@ -1090,6 +1200,9 @@ export class ProjectMemoryStore {
1090
1200
  if (this._dirtyBinding) {
1091
1201
  writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding, { ensureDir: false })
1092
1202
  this._dirtyBinding = false
1203
+ // 这份内容已经落盘:基线推进、tombstone 清空,否则旧墓碑会误杀对方之后的新绑定。
1204
+ this._baseBinding = new Map(Object.entries(this.binding))
1205
+ this._deletedBindings.clear()
1093
1206
  }
1094
1207
  if (this._dirtyWatch) {
1095
1208
  writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist, { ensureDir: false })
@@ -1116,42 +1229,389 @@ export class ProjectMemoryStore {
1116
1229
  return !removalFailed
1117
1230
  }
1118
1231
 
1119
- /**
1120
- * 冲突时采用另一进程的分片:内存 record/entries 与磁盘对齐,并让 IDF/驻留账失效。
1121
- * 磁盘 entries 可能损坏或来自旧版本,和 `_loadSharded` 一样只收合法项。
1122
- */
1123
- _adoptDiskShard(rel, disk) {
1124
- const entries = (disk.entries || []).filter(isRecord).map(stripPersistedDerived)
1125
- this.files[rel] = disk.record
1126
- this.entries[rel] = entries
1127
- this._setFileTextChars(rel, entryTextChars(entries))
1128
- this._entriesVersion++
1129
- this._baseFileSha.set(rel, disk.sha)
1232
+ /** 首次写分片前建一次 shards/;之后每次 save 都省掉一次 mkdir。 */
1233
+ _ensureShardsDir() {
1234
+ if (this._shardsDirReady) return
1235
+ mkdirSync(path.join(this.dir, SHARDS_DIR), { recursive: true })
1236
+ this._shardsDirReady = true
1130
1237
  }
1131
1238
 
1132
- /** 读磁盘分片(不存在/损坏都返回 exists:false)。 */
1133
- _shardDiskRecord(rel) {
1239
+ /** 锁内刷新磁盘布局:另一进程可能已迁移/扩桶,按持久化的 count 重排,避免写回旧桶号。 */
1240
+ _refreshLayoutFromDisk() {
1241
+ const before = this._readErrors.size
1242
+ const doc = loadJson(path.join(this.dir, FORMAT_FILE), null, undefined, this._readErrors)
1243
+ if (this._readErrors.size > before) {
1244
+ this._readOnly = true
1245
+ return false
1246
+ }
1247
+ if (!doc) return true
1248
+ const count = Number.isFinite(doc.bucketCount) ? Math.max(1, Math.min(BUCKET_COUNT_MAX, Math.floor(doc.bucketCount))) : 0
1249
+ if (doc.version >= 3 && count > 0) {
1250
+ if (this._layout !== 'v3' || count !== this._bucketCount) {
1251
+ this._bucketCount = count
1252
+ this._bucketSize = Number.isFinite(doc.bucketSize) ? doc.bucketSize : BUCKET_TARGET_BYTES
1253
+ this._layout = 'v3'
1254
+ this._needsShardRewrite = true
1255
+ }
1256
+ // 崩溃/并发迁移遗留的旧分片或越界桶:必须全量重排,否则 cleanup 会删掉尚未入桶的条目。
1257
+ let names = []
1258
+ try {
1259
+ names = readdirSync(path.join(this.dir, SHARDS_DIR))
1260
+ } catch {
1261
+ names = []
1262
+ }
1263
+ for (const name of names) {
1264
+ if (!name.endsWith('.json')) continue
1265
+ const match = /^bucket-(\d{5})\.json$/.exec(name)
1266
+ if (!match) {
1267
+ this._needsShardRewrite = true
1268
+ break
1269
+ }
1270
+ if (Number(match[1]) >= count) {
1271
+ this._needsShardRewrite = true
1272
+ break
1273
+ }
1274
+ }
1275
+ } else if (this._layout === 'v3') {
1276
+ // 迁移保护态下 format 仍是 v2(_writeFormat 拒绝写)。此时不要翻回 v2 触发全量重排:
1277
+ // 那会让每一次 save 都重写整库,直到用户手工修好旧文件。
1278
+ if (this._legacyBlocked) return true
1279
+ this._layout = 'v2'
1280
+ this._needsShardRewrite = true
1281
+ }
1282
+ return true
1283
+ }
1284
+
1285
+ /** 清掉旧布局/越界/崩溃遗留的 shard 文件(当前 bucketCount 之外的 bucket-* 与 v2 的 64 位 hash 文件)。 */
1286
+ _cleanupShardFiles(writtenNames = null) {
1287
+ let names = []
1134
1288
  try {
1135
- const doc = JSON.parse(readFileSync(shardRelPath(this.dir, rel), 'utf8'))
1136
- if (!isRecord(doc) || typeof doc.relPath !== 'string' || !isRecord(doc.record)) {
1137
- return { exists: false, sha: null, record: null, entries: [] }
1289
+ names = readdirSync(path.join(this.dir, SHARDS_DIR))
1290
+ } catch {
1291
+ return
1292
+ }
1293
+ // 全量重排必须用“实际写过的桶名”做 keep:缩桶后新下标收到 0 条目的同名旧桶不会被重写,
1294
+ // 按范围保留会让它活下来并在下次 load 把已删条目读回来。
1295
+ const keep = writtenNames || new Set(Array.from({ length: this._bucketCount }, (_, i) => `bucket-${String(i).padStart(5, '0')}.json`))
1296
+ for (const name of names) {
1297
+ if (!name.endsWith('.json') || keep.has(name)) continue
1298
+ try {
1299
+ unlinkWithRetry(path.join(this.dir, SHARDS_DIR, name))
1300
+ } catch (err) {
1301
+ if (err?.code !== 'ENOENT') console.error(`[dsh-project-memory] stale shard ${name} could not be removed: ${err?.message || err}`)
1138
1302
  }
1139
- return {
1140
- exists: true,
1141
- sha: doc.record.sha256 ?? null,
1142
- record: doc.record,
1143
- entries: Array.isArray(doc.entries) ? doc.entries : [],
1303
+ }
1304
+ }
1305
+
1306
+ _readBucket(index) {
1307
+ const map = new Map()
1308
+ const file = bucketRelPath(this.dir, index)
1309
+ if (!existsSafe(file)) return map
1310
+ const before = this._readErrors.size
1311
+ const doc = loadJson(file, null, undefined, this._readErrors)
1312
+ if (this._readErrors.size > before) {
1313
+ this._readOnly = true
1314
+ return null
1315
+ }
1316
+ if (!doc || !Array.isArray(doc.items)) return map
1317
+ for (const item of doc.items) {
1318
+ if (!item || typeof item.relPath !== 'string' || !isRecord(item.record)) continue
1319
+ map.set(item.relPath, { record: item.record, entries: Array.isArray(item.entries) ? item.entries : [] })
1320
+ }
1321
+ return map
1322
+ }
1323
+
1324
+ _writeBucket(index, map, { keepEmpty = false } = {}) {
1325
+ if (!map.size && !keepEmpty) {
1326
+ try {
1327
+ unlinkWithRetry(bucketRelPath(this.dir, index))
1328
+ } catch (err) {
1329
+ if (err?.code !== 'ENOENT') throw err
1144
1330
  }
1331
+ return
1332
+ }
1333
+ this._ensureShardsDir()
1334
+ const items = [...map.entries()]
1335
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
1336
+ .map(([relPath, item]) => ({ relPath, record: item.record, entries: (item.entries || []).map(withoutPersistedDerived) }))
1337
+ writeJsonAtomic(bucketRelPath(this.dir, index), {
1338
+ version: 3,
1339
+ bucket: index,
1340
+ bucketSize: this._bucketSize,
1341
+ items,
1342
+ }, { ensureDir: false })
1343
+ }
1344
+
1345
+ _writeFormat() {
1346
+ if (this._legacyBlocked) return
1347
+ const doc = {
1348
+ version: 3,
1349
+ layout: 'bucket',
1350
+ bucketSize: this._bucketSize,
1351
+ bucketCount: this._bucketCount,
1352
+ }
1353
+ if (this._formatDoc?.migratedFrom) doc.migratedFrom = this._formatDoc.migratedFrom
1354
+ writeJsonAtomic(path.join(this.dir, FORMAT_FILE), doc, { ensureDir: false })
1355
+ this._formatDoc = doc
1356
+ this._formatWritten = true
1357
+ this._formatDirty = false
1358
+ }
1359
+
1360
+ _adoptBucketItem(rel, item) {
1361
+ this.files[rel] = item.record
1362
+ this.entries[rel] = (item.entries || []).filter(isRecord).map(withoutPersistedDerived)
1363
+ this._setFileTextChars(rel, JSON.stringify({ record: item.record, entries: this.entries[rel] }).length)
1364
+ this._entriesVersion++
1365
+ this._baseFileSha.set(rel, item.record?.sha256 ?? null)
1366
+ }
1367
+
1368
+ /** 全量重写前合并磁盘:按 (indexedAt, bucket) 选最新副本;磁盘已消失的旧文件不能被内存复活。 */
1369
+ _mergeShardDiskForRewrite() {
1370
+ if (this._readOnly) return false
1371
+ let names = []
1372
+ try {
1373
+ names = readdirSync(path.join(this.dir, SHARDS_DIR)).filter((n) => n.endsWith('.json'))
1145
1374
  } catch {
1146
- return { exists: false, sha: null, record: null, entries: [] }
1375
+ return true
1147
1376
  }
1377
+ const disk = new Map()
1378
+ let complete = true
1379
+ for (const name of names) {
1380
+ const before = this._readErrors.size
1381
+ const doc = loadJson(path.join(this.dir, SHARDS_DIR, name), null, undefined, this._readErrors)
1382
+ if (this._readErrors.size > before) {
1383
+ this._readOnly = true
1384
+ return false
1385
+ }
1386
+ if (!doc) {
1387
+ complete = false
1388
+ continue
1389
+ }
1390
+ const isBucket = Array.isArray(doc.items)
1391
+ for (const item of isBucket ? doc.items : [doc]) {
1392
+ if (!item || typeof item.relPath !== 'string' || !isRecord(item.record)) continue
1393
+ const at = Date.parse(item.record.indexedAt || '') || 0
1394
+ const prev = disk.get(item.relPath)
1395
+ // 同 rel 多副本(崩溃/降级):时间新者胜;同时间优先 v3 桶。
1396
+ if (!prev || at > prev.at || (at === prev.at && isBucket && !prev.bucket)) {
1397
+ disk.set(item.relPath, { item, at, sha: item.record.sha256 ?? null, bucket: isBucket })
1398
+ }
1399
+ }
1400
+ }
1401
+ if (!complete) return false
1402
+ for (const [rel, entry] of disk) {
1403
+ const base = this._baseFileSha.get(rel) ?? null
1404
+ if (this._removedShards.has(rel)) {
1405
+ if (entry.sha !== base) {
1406
+ this._adoptBucketItem(rel, entry.item)
1407
+ this._removedShards.delete(rel)
1408
+ }
1409
+ continue
1410
+ }
1411
+ if (this._dirtyShards.has(rel)) {
1412
+ const local = this.files[rel]
1413
+ if (!local) continue
1414
+ const localSha = local.sha256 ?? null
1415
+ if (entry.sha === base || entry.sha === localSha) continue
1416
+ const localAt = Date.parse(local.indexedAt || '') || 0
1417
+ if (localAt > entry.at) continue
1418
+ this._adoptBucketItem(rel, entry.item)
1419
+ this._dirtyShards.delete(rel)
1420
+ this._warnConflict(rel)
1421
+ continue
1422
+ }
1423
+ if (!(rel in this.files)) {
1424
+ this._adoptBucketItem(rel, entry.item)
1425
+ continue
1426
+ }
1427
+ if (entry.sha === base) continue
1428
+ const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
1429
+ if (entry.at >= localAt) this._adoptBucketItem(rel, entry.item)
1430
+ }
1431
+ // 另一进程已删除、本地未删除且不是本进程新建的文件:从内存移除,避免 rewrite 复活。
1432
+ for (const rel of Object.keys(this.files)) {
1433
+ if (this._dirtyShards.has(rel) || this._removedShards.has(rel) || !this._baseFileSha.has(rel)) continue
1434
+ if (disk.has(rel)) continue
1435
+ delete this.files[rel]
1436
+ delete this.entries[rel]
1437
+ this._setFileTextChars(rel, 0)
1438
+ this._baseFileSha.delete(rel)
1439
+ this._entriesVersion++
1440
+ }
1441
+ return true
1148
1442
  }
1149
1443
 
1150
- /** 首次写分片前建一次 shards/;之后每次 save 都省掉一次 mkdir。 */
1151
- _ensureShardsDir() {
1152
- if (this._shardsDirReady) return
1153
- mkdirSync(path.join(this.dir, SHARDS_DIR), { recursive: true })
1154
- this._shardsDirReady = true
1444
+ _rewriteAllBuckets() {
1445
+ const groups = new Map()
1446
+ for (const rel of Object.keys(this.files)) {
1447
+ const index = bucketIndexOf(rel, this._bucketCount)
1448
+ let map = groups.get(index)
1449
+ if (!map) {
1450
+ map = new Map()
1451
+ groups.set(index, map)
1452
+ }
1453
+ map.set(rel, { record: this.files[rel], entries: this.entries[rel] || [] })
1454
+ }
1455
+ // 缩桶时“新布局下应为空”的桶也必须落成空文件:只写非空桶再删旧桶,一旦 unlink
1456
+ // 失败/进程在窗口内退出,同名旧桶会活下来;它的下标仍在新 bucketCount 内,
1457
+ // 范围检查发现不了,下一次 load 就把已删条目读回来。先把所有现存 in-range 桶清空,
1458
+ // 再写 format(顺序不能反)。
1459
+ try {
1460
+ for (const name of readdirSync(path.join(this.dir, SHARDS_DIR))) {
1461
+ const match = /^bucket-(\d{5})\.json$/.exec(name)
1462
+ if (!match) continue
1463
+ const index = Number(match[1])
1464
+ if (index < this._bucketCount && !groups.has(index)) groups.set(index, new Map())
1465
+ }
1466
+ } catch {
1467
+ // shards/ 还不存在:groups 里的桶会在下面建目录
1468
+ }
1469
+ const written = new Set()
1470
+ for (const [index, map] of groups) {
1471
+ this._writeBucket(index, map, { keepEmpty: true })
1472
+ written.add(`bucket-${String(index).padStart(5, '0')}.json`)
1473
+ }
1474
+ // 全量重排后重建冲突基线:否则后续 removeFile 会拿不到 base、误判成"对方更新"。
1475
+ this._baseFileSha = new Map(Object.keys(this.files).map((rel) => [rel, this.files[rel].sha256 ?? null]))
1476
+ return written
1477
+ }
1478
+
1479
+ /** 写分片。返回 false 表示删除/写入有失败(保持脏状态,留给重试)。 */
1480
+ _saveShards() {
1481
+ if (this._readOnly) return false
1482
+ if (!this._refreshLayoutFromDisk()) return false
1483
+ // 存量压实:≤0.5.10 的分片带派生字段,每轮有界地把它们标脏重写。
1484
+ let compactBudget = COMPACT_BATCH
1485
+ for (const rel of this._compactQueue) {
1486
+ if (compactBudget-- <= 0) break
1487
+ this._compactQueue.delete(rel)
1488
+ if (this.files[rel]) this._dirtyShards.add(rel)
1489
+ }
1490
+ const hasFiles = Object.keys(this.files).length > 0
1491
+ let rewrite = this._needsShardRewrite || this._layout !== 'v3' || this._bucketCount === 0 || (!this._formatWritten && hasFiles)
1492
+ const ops = this._dirtyShards.size + this._removedShards.size
1493
+ this._shardOpsSinceResize += ops
1494
+ if (!rewrite && this._layout === 'v3') {
1495
+ // 批量变更每 2048 个文件校准一次;逐文件增量每 64 次校准一次,避免每次 save 做全库估算。
1496
+ const threshold = ops > 32 ? 2048 : 64
1497
+ if (this._shardOpsSinceResize >= threshold) {
1498
+ this._shardOpsSinceResize = 0
1499
+ const bytes = estimateShardBytes(this.files, this.entries)
1500
+ const target = this._bucketCount * this._bucketSize
1501
+ if (bytes > target * 1.5) {
1502
+ const next = Math.max(chooseBucketCount(bytes), Math.ceil(this._bucketCount * 1.5))
1503
+ if (next > this._bucketCount) {
1504
+ this._bucketCount = next
1505
+ rewrite = true
1506
+ }
1507
+ } else if (bytes < target * 0.5) {
1508
+ const next = chooseBucketCount(bytes)
1509
+ if (next < this._bucketCount) {
1510
+ this._bucketCount = next
1511
+ rewrite = true
1512
+ }
1513
+ }
1514
+ }
1515
+ }
1516
+ const needsFormat = (!this._formatWritten || this._formatDirty) && !this._legacyBlocked
1517
+ if (!rewrite && !hasFiles && this._dirtyShards.size === 0 && this._removedShards.size === 0) {
1518
+ if (needsFormat) {
1519
+ if (this._bucketCount === 0) this._bucketCount = 1
1520
+ this._writeFormat()
1521
+ }
1522
+ return true
1523
+ }
1524
+ if (rewrite) {
1525
+ if (!this._mergeShardDiskForRewrite()) return false
1526
+ if (this._layout !== 'v3' || this._bucketCount === 0) {
1527
+ this._bucketCount = chooseBucketCount(estimateShardBytes(this.files, this.entries))
1528
+ }
1529
+ const written = this._rewriteAllBuckets()
1530
+ this._writeFormat()
1531
+ this._layout = 'v3'
1532
+ this._needsShardRewrite = false
1533
+ this._compactQueue.clear()
1534
+ this._dirtyShards.clear()
1535
+ this._removedShards.clear()
1536
+ this._shardOpsSinceResize = 0
1537
+ this._cleanupShardFiles(written)
1538
+ return true
1539
+ }
1540
+
1541
+ const touched = new Map()
1542
+ const add = (rel, kind) => {
1543
+ const index = bucketIndexOf(rel, this._bucketCount)
1544
+ let group = touched.get(index)
1545
+ if (!group) {
1546
+ group = { dirty: new Set(), removed: new Set() }
1547
+ touched.set(index, group)
1548
+ }
1549
+ group[kind].add(rel)
1550
+ }
1551
+ for (const rel of this._removedShards) add(rel, 'removed')
1552
+ for (const rel of this._dirtyShards) if (!this._removedShards.has(rel)) add(rel, 'dirty')
1553
+
1554
+ let ok = true
1555
+ for (const [index, group] of touched) {
1556
+ const disk = this._readBucket(index)
1557
+ if (!disk) {
1558
+ ok = false
1559
+ continue
1560
+ }
1561
+ // 先采用磁盘上其他进程对“未触碰文件”的更新,避免整桶重写把它们覆盖掉。
1562
+ for (const [rel, item] of disk) {
1563
+ if (group.dirty.has(rel) || group.removed.has(rel)) continue
1564
+ const base = this._baseFileSha.get(rel) ?? null
1565
+ const diskSha = item.record?.sha256 ?? null
1566
+ if (diskSha !== base || !(rel in this.files)) this._adoptBucketItem(rel, item)
1567
+ }
1568
+ for (const rel of group.dirty) {
1569
+ const local = this.files[rel]
1570
+ if (!local) continue
1571
+ const diskItem = disk.get(rel)
1572
+ const base = this._baseFileSha.get(rel) ?? null
1573
+ const nextSha = local.sha256 ?? null
1574
+ const diskSha = diskItem?.record?.sha256 ?? null
1575
+ if (diskItem && diskSha !== base && diskSha !== nextSha) {
1576
+ const localAt = Date.parse(local.indexedAt || '') || 0
1577
+ const diskAt = Date.parse(diskItem.record?.indexedAt || '') || 0
1578
+ if (localAt <= diskAt) {
1579
+ this._adoptBucketItem(rel, diskItem)
1580
+ this._warnConflict(rel)
1581
+ disk.set(rel, diskItem)
1582
+ continue
1583
+ }
1584
+ }
1585
+ disk.set(rel, { record: local, entries: this.entries[rel] || [] })
1586
+ this._baseFileSha.set(rel, nextSha)
1587
+ }
1588
+ for (const rel of group.removed) {
1589
+ const diskItem = disk.get(rel)
1590
+ const base = this._baseFileSha.get(rel) ?? null
1591
+ if (diskItem && (diskItem.record?.sha256 ?? null) !== base) {
1592
+ this._adoptBucketItem(rel, diskItem)
1593
+ this._warnConflict(rel)
1594
+ continue
1595
+ }
1596
+ disk.delete(rel)
1597
+ this._baseFileSha.delete(rel)
1598
+ }
1599
+ try {
1600
+ this._writeBucket(index, disk)
1601
+ } catch (err) {
1602
+ ok = false
1603
+ console.error(`[dsh-project-memory] bucket ${index} write failed: ${err?.message || err}`)
1604
+ continue
1605
+ }
1606
+ for (const rel of group.dirty) this._dirtyShards.delete(rel)
1607
+ for (const rel of group.removed) this._removedShards.delete(rel)
1608
+ }
1609
+ if ((!this._formatWritten || this._formatDirty) && !this._legacyBlocked) {
1610
+ if (this._bucketCount === 0) this._bucketCount = 1
1611
+ this._writeFormat()
1612
+ }
1613
+ if (ok) this._cleanupShardFiles()
1614
+ return ok
1155
1615
  }
1156
1616
 
1157
1617
  /** 退出/卸载路径的同步兜底(见 util/flush.js)。 */
@@ -1188,6 +1648,7 @@ export class ProjectMemoryStore {
1188
1648
  * 用墓碑挡住,避免"删了又被对方的旧副本复活"。分片不走这里(按 hash 冲突检测)。
1189
1649
  */
1190
1650
  _mergeAuxFromDisk() {
1651
+ const before = this._readErrors.size
1191
1652
  if (this._dirtyInsights) {
1192
1653
  // 先按“上次落盘基线”记墓碑:prune/applyDecay 等原地 splice 不经过 replaceInsightItems。
1193
1654
  const current = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
@@ -1236,9 +1697,23 @@ export class ProjectMemoryStore {
1236
1697
  // 任务级条目单独合并:两边都可能新增/删除,按整条任务的时间戳选一侧会静默丢一边。
1237
1698
  const base = this._baseTaskInsightIds.get(t.id) || new Set()
1238
1699
  const mergedInsights = mergeTaskInsights(t, prev, base)
1239
- const winner = newerIso(t.updatedAt || t.lastActiveAt, prev.updatedAt || prev.lastActiveAt) >= 0 ? t : prev
1240
- winner.insights = mergedInsights
1241
- byId.set(t.id, winner)
1700
+ // 步骤/标题以 `updatedAt` 为准(todo/write 与显式编辑都会刷新它);文件热点只刷新
1701
+ // `lastActiveAt`,不能让它把另一进程刚写的步骤盖回旧值。
1702
+ const semanticLocal = newerIso(t.updatedAt, prev.updatedAt) >= 0
1703
+ const semantic = semanticLocal ? t : prev
1704
+ // 归档是语义状态,不能靠 updatedAt 猜:普通步骤/热点写也会刷新 updatedAt。
1705
+ // 只有本地相对基线**显式改过** archived 时才取本地,否则一律取磁盘。
1706
+ const baseArchived = this._baseTaskArchived.get(t.id)
1707
+ const archived = (t.archived === true) === baseArchived ? prev.archived === true : t.archived === true
1708
+ const merged = {
1709
+ ...semantic,
1710
+ archived,
1711
+ insights: mergedInsights,
1712
+ ...mergeTaskFileState(t, prev),
1713
+ updatedAt: newerIso(t.updatedAt, prev.updatedAt) >= 0 ? t.updatedAt : prev.updatedAt,
1714
+ lastActiveAt: newerIso(t.lastActiveAt, prev.lastActiveAt) >= 0 ? t.lastActiveAt : prev.lastActiveAt,
1715
+ }
1716
+ byId.set(t.id, merged)
1242
1717
  }
1243
1718
  // `removeTask` 已把它从内存数组移除,上面循环看不到;不在这里剔除会在同一次 save 里被写回。
1244
1719
  for (const id of this._deletedTaskIds) byId.delete(id)
@@ -1249,9 +1724,22 @@ export class ProjectMemoryStore {
1249
1724
  if (this._dirtyBinding) {
1250
1725
  const disk = this._loadJson(path.join(this.dir, BINDING_FILE), {})
1251
1726
  if (isRecord(disk)) {
1727
+ // 只回写“相对加载基线有变化”的本地项。整份本地快照覆盖会把另一进程刚改的
1728
+ // 绑定回退成旧任务,也会让本地旧内存把对方刚删的会话复活。
1252
1729
  const merged = { ...disk }
1253
- for (const [sid, tid] of Object.entries(this.binding)) merged[sid] = tid
1254
- for (const sid of this._deletedBindings) delete merged[sid]
1730
+ const sids = new Set([...Object.keys(this.binding), ...this._baseBinding.keys(), ...Object.keys(disk)])
1731
+ for (const sid of sids) {
1732
+ const localVal = this.binding[sid]
1733
+ const baseVal = this._baseBinding.get(sid)
1734
+ if (localVal !== baseVal) {
1735
+ if (localVal === undefined) delete merged[sid]
1736
+ else merged[sid] = localVal
1737
+ } else if (disk[sid] === undefined) {
1738
+ delete merged[sid]
1739
+ } else {
1740
+ merged[sid] = disk[sid]
1741
+ }
1742
+ }
1255
1743
  this.binding = merged
1256
1744
  this._auxVersion++
1257
1745
  }
@@ -1266,6 +1754,7 @@ export class ProjectMemoryStore {
1266
1754
  this._auxVersion++
1267
1755
  }
1268
1756
  }
1757
+ return this._readErrors.size === before
1269
1758
  }
1270
1759
 
1271
1760
  getIdfCache() {
@@ -1340,7 +1829,7 @@ export class ProjectMemoryStore {
1340
1829
  if (entries.length) {
1341
1830
  // searchText 在内存里物化(写入/检索都靠它),但 save() 不会把它写盘。
1342
1831
  const enriched = entries.map((e) => {
1343
- const out = stripPersistedDerived({ ...e })
1832
+ const out = withoutPersistedDerived({ ...e })
1344
1833
  out.searchText = makeSearchText(out)
1345
1834
  return out
1346
1835
  })
@@ -1545,6 +2034,9 @@ export class ProjectMemoryStore {
1545
2034
  const result = fn(this)
1546
2035
  this.pruneTasks()
1547
2036
  if (options.save !== false) this.save()
2037
+ // save:false 只推迟落盘,不能丢掉"还有脏数据"——否则回合结束前 cd 到无根目录或进程常驻,
2038
+ // 这次热点更新就永远只在内存里。
2039
+ else if (this.hasDirty()) trackDirty(this)
1548
2040
  return result
1549
2041
  }
1550
2042