@yolk_vat-y/dsh-project-memory 0.6.12 → 0.7.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/CHANGELOG.md +68 -20
- package/README.md +14 -105
- package/README.zh-CN.md +14 -105
- package/client/client.js +311 -163
- package/client/client.js.map +1 -1
- package/package.json +8 -8
- package/scripts/file-peak.mjs +1 -1
- package/scripts/tool-schema-size.mjs +1 -1
- package/skills/project-memory/SKILL.md +1 -1
- package/skills/project-memory/scripts/pm-digest.mjs +20 -6
- package/src/audit.js +10 -2
- package/src/auto-inject.js +124 -38
- package/src/client/MemoryView.tsx +121 -51
- package/src/client/TaskCommandNode.tsx +6 -4
- package/src/client/TaskComponents.tsx +14 -26
- package/src/client/TaskPanel.tsx +44 -23
- package/src/client/client.ts +4 -7
- package/src/client/i18n.ts +29 -0
- package/src/client/kind-label.js +38 -0
- package/src/client/paging.js +1 -14
- package/src/client/settings-card.tsx +9 -0
- package/src/client/slash.ts +4 -15
- package/src/client/task-data-store.ts +57 -7
- package/src/client/task-hooks.ts +0 -2
- package/src/client/task-scope.js +16 -1
- package/src/client/task-ui-store.ts +1 -1
- package/src/commands/insight-actions.js +85 -60
- package/src/commands/task-actions.js +7 -5
- package/src/commands/tasks.js +34 -10
- package/src/doc-index.js +3 -1
- package/src/enhancer.js +0 -12
- package/src/index-failures.js +1 -1
- package/src/index-pipeline.js +11 -2
- package/src/index.js +60 -14
- package/src/inject-visible.js +282 -0
- package/src/insight-store.js +129 -32
- package/src/lazy.js +29 -23
- package/src/llm-route.js +1 -1
- package/src/ops.js +18 -5
- package/src/parsers/pdfjs-parser.js +3 -33
- package/src/project-memory-service.js +195 -0
- package/src/project-profile.js +0 -4
- package/src/setup/taskbridge.js +38 -6
- package/src/store.js +638 -135
- package/src/symbols.js +2 -4
- package/src/tools/forget.js +3 -6
- package/src/tools/index-doc.js +61 -18
- package/src/tools/index-repo.js +16 -12
- package/src/tools/lesson-tools.js +5 -5
- package/src/tools/output.js +28 -0
- package/src/tools/query-memory.js +6 -9
- package/src/tools/remember.js +3 -6
- package/src/tools/stats.js +3 -6
- package/src/tools/task-tools.js +15 -8
- package/src/tools/watch-repo.js +15 -12
- package/src/util/flush.js +1 -1
- package/src/util/fs.js +135 -20
- package/src/util/message-source.js +20 -0
- package/src/util/relative-time.js +24 -0
- package/src/util/search.js +0 -1
- package/src/util/task-view.js +8 -15
- package/src/vector-index.js +2 -2
- package/src/watch.js +25 -8
- package/client/client.d.ts +0 -27
- package/client/client.d.ts.map +0 -1
- package/client/style.css +0 -395
package/src/store.js
CHANGED
|
@@ -2,7 +2,7 @@ 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'
|
|
@@ -17,7 +17,6 @@ const BINDING_FILE = 'binding.json'
|
|
|
17
17
|
const WATCH_FILE = 'watch.json'
|
|
18
18
|
const INSIGHTS_FILE = 'insights.json'
|
|
19
19
|
const SHARDS_DIR = 'shards'
|
|
20
|
-
const GITIGNORE_FILE = '.gitignore'
|
|
21
20
|
/** ≤0.5.10 的 TS 增强结果缓存目录;0.5.11 起废弃并自愈清理。 */
|
|
22
21
|
const LEGACY_TYPE_CACHE_DIR = 'type-cache'
|
|
23
22
|
|
|
@@ -159,7 +158,7 @@ function auxCharsOf(store) {
|
|
|
159
158
|
/**
|
|
160
159
|
* 单个 store 的驻留估算:数**内存里留下的对象图**,按版本记忆化。不用读盘文本量换算——
|
|
161
160
|
* `searchText` 要到 `allEntries()` 才物化,前后估出两个数(实测 76MB → 107MB),且被
|
|
162
|
-
* `
|
|
161
|
+
* `withoutPersistedDerived` 删掉的字段也会被算进去。`_entriesVersion` 与 `_materializeVersion`
|
|
163
162
|
* 都参与失效;一次全量遍历 70119 条目 ~40ms,逐出又会遍历整个缓存,所以必须记忆化。
|
|
164
163
|
*/
|
|
165
164
|
export function _estimateResidentBytes(store) {
|
|
@@ -234,6 +233,12 @@ export function _storeCacheKeysForTest() {
|
|
|
234
233
|
return [...storeCache.keys()]
|
|
235
234
|
}
|
|
236
235
|
|
|
236
|
+
/** 仅供测试:清空进程内 store 缓存,让下一次 load 真的走磁盘。 */
|
|
237
|
+
export function _clearStoreCacheForTest() {
|
|
238
|
+
storeCache.clear()
|
|
239
|
+
storeCacheAlias.clear()
|
|
240
|
+
}
|
|
241
|
+
|
|
237
242
|
/** 已就"无法迁移的旧 store"告警过的目录:避免每次 load() 都刷一行。 */
|
|
238
243
|
const migrationWarned = new Set()
|
|
239
244
|
|
|
@@ -246,6 +251,54 @@ const migrationWarned = new Set()
|
|
|
246
251
|
* @param {Set<string>} base
|
|
247
252
|
* @returns {object[]}
|
|
248
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
|
+
|
|
249
302
|
function mergeTaskInsights(local, disk, base) {
|
|
250
303
|
const merged = new Map()
|
|
251
304
|
for (const ins of Array.isArray(disk?.insights) ? disk.insights : []) {
|
|
@@ -268,9 +321,10 @@ function mergeTaskInsights(local, disk, base) {
|
|
|
268
321
|
}
|
|
269
322
|
|
|
270
323
|
/**
|
|
271
|
-
* 落盘的 entry
|
|
324
|
+
* 落盘的 entry 只保留**不可推导的事实**,三个派生字段永不写盘:`linkedSymbols` 是跨实体
|
|
272
325
|
* 派生(取决于符号表当前状态,读取期由 src/link.js 解算),`searchText` 是自派生(只依赖
|
|
273
|
-
* 本 entry,由 `allEntries()`
|
|
326
|
+
* 本 entry,由 `allEntries()` 在内存里物化),`typeSig` 是增强器的实现细节。旧 store 的
|
|
327
|
+
* 这些字段加载时剥掉,下次写盘自然压实。
|
|
274
328
|
*/
|
|
275
329
|
const PERSISTED_DERIVED = ['linkedSymbols', 'searchText', 'typeSig']
|
|
276
330
|
const PERSISTED_DERIVED_SET = new Set(PERSISTED_DERIVED)
|
|
@@ -301,16 +355,10 @@ function rebuildWithoutDerived(entry) {
|
|
|
301
355
|
}
|
|
302
356
|
|
|
303
357
|
/**
|
|
304
|
-
*
|
|
305
|
-
*
|
|
358
|
+
* 返回不含派生字段的条目(加载/写盘共用)。没有派生字段时**原对象返回**(零分配热路径),
|
|
359
|
+
* 有派生字段时重建而不是 `delete`(避免 V8 字典模式)。加载路径复用返回值即可,写盘路径
|
|
360
|
+
* 不能动内存对象。
|
|
306
361
|
*/
|
|
307
|
-
function stripPersistedDerived(entry) {
|
|
308
|
-
if (!entry || typeof entry !== 'object') return entry
|
|
309
|
-
if (!hasPersistedDerived(entry)) return entry
|
|
310
|
-
return rebuildWithoutDerived(entry)
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/** 返回不含派生字段的条目(写盘路径用,不能动内存里的对象)。 */
|
|
314
362
|
function withoutPersistedDerived(entry) {
|
|
315
363
|
if (!entry || typeof entry !== 'object') return entry
|
|
316
364
|
if (!hasPersistedDerived(entry)) return entry
|
|
@@ -319,14 +367,19 @@ function withoutPersistedDerived(entry) {
|
|
|
319
367
|
|
|
320
368
|
/** 仅供测试:加载/写盘路径的剥离实现(内存形状由测试用 --expose-gc 度量)。 */
|
|
321
369
|
export function _stripPersistedDerivedForTest(entry) {
|
|
322
|
-
return
|
|
370
|
+
return withoutPersistedDerived(entry)
|
|
323
371
|
}
|
|
324
372
|
|
|
325
|
-
function loadJson(filePath, fallback, counter) {
|
|
373
|
+
function loadJson(filePath, fallback, counter, errorSink) {
|
|
326
374
|
let raw
|
|
327
375
|
try {
|
|
328
376
|
raw = readFileSync(filePath, 'utf8')
|
|
329
|
-
} 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
|
+
}
|
|
330
383
|
return fallback
|
|
331
384
|
}
|
|
332
385
|
// 累计读盘文本字符数,只供 `residentBoundBytes` 判断要不要精确计量。
|
|
@@ -349,6 +402,35 @@ function shardRelPath(dir, rel) {
|
|
|
349
402
|
return path.join(dir, SHARDS_DIR, createHash('sha256').update(rel).digest('hex') + '.json')
|
|
350
403
|
}
|
|
351
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
|
+
|
|
352
434
|
/**
|
|
353
435
|
* watch.json 去重:Windows/macOS 上 `D:\proj` 与 `d:\PROJ` 是同一个物理目录,字符串却不同。
|
|
354
436
|
* 同一目录写两条会让 watch 每轮扫两遍、`watch_repo({watch:false})` 也只删掉其中一条(另一条
|
|
@@ -390,17 +472,34 @@ export class ProjectMemoryStore {
|
|
|
390
472
|
this.watchlist = []
|
|
391
473
|
this._dirtyShards = new Set()
|
|
392
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
|
|
393
488
|
/** 加载时的分片 hash:跨进程写冲突检测的基准。 */
|
|
394
489
|
this._baseFileSha = new Map()
|
|
395
490
|
/** 本地删除留痕:合并另一进程的磁盘状态时不能把它们复活。 */
|
|
396
491
|
this._deletedInsightIds = new Set()
|
|
397
492
|
this._deletedTaskIds = new Set()
|
|
398
493
|
this._deletedBindings = new Set()
|
|
494
|
+
/** 加载/上次成功落盘时的会话绑定:跨进程合并时区分“本地改过”与“只是旧快照”。 */
|
|
495
|
+
this._baseBinding = new Map()
|
|
399
496
|
this._removedWatch = new Set()
|
|
400
497
|
/** 上次落盘/加载时的 insight id 集合:原地 splice 的删除也要能被合并逻辑看见。 */
|
|
401
498
|
this._baseInsightIds = new Set()
|
|
402
499
|
/** task.id → 上次落盘/加载时该任务的 insight id 集合(任务级条目的合并基线,见 mergeTaskInsights)。 */
|
|
403
500
|
this._baseTaskInsightIds = new Map()
|
|
501
|
+
/** task.id → 加载/上次落盘时的 archived:只看 updatedAt 会把显式归档/解归档回滚。 */
|
|
502
|
+
this._baseTaskArchived = new Map()
|
|
404
503
|
/**
|
|
405
504
|
* 本进程**新建**的条目。"磁盘没有但内存有"可能是新建(要补写)也可能是**对方删了**
|
|
406
505
|
* (不能写回);没有这个集合,后者会被复活。
|
|
@@ -492,6 +591,15 @@ export class ProjectMemoryStore {
|
|
|
492
591
|
console.error(`[dsh-project-memory] ${message}`)
|
|
493
592
|
}
|
|
494
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
|
+
|
|
495
603
|
_migrateLegacyIfNeeded() {
|
|
496
604
|
const formatPath = path.join(this.dir, FORMAT_FILE)
|
|
497
605
|
const formatDoc = loadJson(formatPath, null)
|
|
@@ -597,7 +705,10 @@ export class ProjectMemoryStore {
|
|
|
597
705
|
* **不进** `_textChars`(那份账只跟 entries),交给 `auxCharsOf` 按对象图直接算。
|
|
598
706
|
*/
|
|
599
707
|
_loadJson(filePath, fallback) {
|
|
600
|
-
|
|
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
|
|
601
712
|
}
|
|
602
713
|
|
|
603
714
|
/** 按文件记文本量:替换而不是累加,重写同一个文件不会算两遍。 */
|
|
@@ -633,24 +744,62 @@ export class ProjectMemoryStore {
|
|
|
633
744
|
}
|
|
634
745
|
|
|
635
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
|
+
}
|
|
636
760
|
let shardNames = []
|
|
637
761
|
try {
|
|
638
762
|
shardNames = readdirSync(path.join(this.dir, SHARDS_DIR)).filter((n) => n.endsWith('.json'))
|
|
639
763
|
} catch {
|
|
640
764
|
shardNames = []
|
|
641
765
|
}
|
|
766
|
+
let sawLegacy = false
|
|
767
|
+
const sourceRank = new Map()
|
|
642
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
|
|
643
774
|
const counter = { chars: 0 }
|
|
644
|
-
const
|
|
645
|
-
if (!
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
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
|
|
654
803
|
}
|
|
655
804
|
this._entriesVersion++
|
|
656
805
|
this.experience = this._loadJson(path.join(this.dir, EXPERIENCE_FILE), [])
|
|
@@ -683,6 +832,7 @@ export class ProjectMemoryStore {
|
|
|
683
832
|
}
|
|
684
833
|
const bindingDoc = this._loadJson(path.join(this.dir, BINDING_FILE), {})
|
|
685
834
|
this.binding = isRecord(bindingDoc) ? bindingDoc : {}
|
|
835
|
+
this._baseBinding = new Map(Object.entries(this.binding))
|
|
686
836
|
const watchDoc = this._loadJson(path.join(this.dir, WATCH_FILE), [])
|
|
687
837
|
const rawWatch = Array.isArray(watchDoc) ? watchDoc.filter((r) => typeof r === 'string' && r) : []
|
|
688
838
|
// 老版本可能把同一个物理目录按不同大小写写了两条(Windows/macOS 大小写不敏感):
|
|
@@ -695,6 +845,8 @@ export class ProjectMemoryStore {
|
|
|
695
845
|
// 这四个集合的内容刚刚被换掉,让 auxCharsOf/精确估算重算(而不是沿用上一份实例的账)。
|
|
696
846
|
this._auxVersion++
|
|
697
847
|
this._formatWritten = existsSafe(path.join(this.dir, FORMAT_FILE))
|
|
848
|
+
this._readOnly = this._readErrors.size > 0
|
|
849
|
+
if (this._readOnly) this._warnReadOnly()
|
|
698
850
|
}
|
|
699
851
|
|
|
700
852
|
/**
|
|
@@ -886,29 +1038,25 @@ export class ProjectMemoryStore {
|
|
|
886
1038
|
* 本进程剩余生命周期都不再自我忽略,store 可能被下一次 `git add` 带进提交。
|
|
887
1039
|
*/
|
|
888
1040
|
ensureSelfIgnore() {
|
|
889
|
-
|
|
890
|
-
const file = path.join(this.dir, GITIGNORE_FILE)
|
|
891
|
-
if (existsSafe(file)) return
|
|
892
|
-
try {
|
|
893
|
-
writeFileSync(file, '# dsh-project-memory: local by default. `git add -f` to commit it.\n*\n')
|
|
894
|
-
} catch {
|
|
895
|
-
// 旁路:写不进去不影响存储本身
|
|
896
|
-
}
|
|
1041
|
+
ensureSelfIgnoreDir(this.dir)
|
|
897
1042
|
}
|
|
898
1043
|
|
|
899
1044
|
/** 重新记下每个任务当前可见的 insight id:只在加载成功 / 整份 tasks 落盘成功后调用。 */
|
|
900
1045
|
_resetTaskInsightBases() {
|
|
901
1046
|
this._baseTaskInsightIds = new Map()
|
|
1047
|
+
this._baseTaskArchived = new Map()
|
|
902
1048
|
for (const task of Array.isArray(this.tasks) ? this.tasks : []) {
|
|
903
1049
|
if (!task?.id) continue
|
|
904
1050
|
const ids = Array.isArray(task.insights) ? task.insights.map((it) => it?.id).filter(Boolean) : []
|
|
905
1051
|
this._baseTaskInsightIds.set(task.id, new Set(ids))
|
|
1052
|
+
this._baseTaskArchived.set(task.id, task.archived === true)
|
|
906
1053
|
}
|
|
907
1054
|
}
|
|
908
1055
|
|
|
909
1056
|
/** 是否有待落盘的变更;逐出缓存前用它避免为干净 store 触发 save 的旁路副作用。 */
|
|
910
1057
|
hasDirty() {
|
|
911
1058
|
return this._compactQueue.size > 0
|
|
1059
|
+
|| this._needsShardRewrite
|
|
912
1060
|
|| this._dirtyShards.size > 0
|
|
913
1061
|
|| this._removedShards.size > 0
|
|
914
1062
|
|| this._dirtyInsights
|
|
@@ -932,6 +1080,7 @@ export class ProjectMemoryStore {
|
|
|
932
1080
|
const hasContent = this.hasContent
|
|
933
1081
|
const dirty =
|
|
934
1082
|
compacting ||
|
|
1083
|
+
this._needsShardRewrite ||
|
|
935
1084
|
this._dirtyShards.size > 0 ||
|
|
936
1085
|
this._removedShards.size > 0 ||
|
|
937
1086
|
this._dirtyInsights ||
|
|
@@ -939,6 +1088,29 @@ export class ProjectMemoryStore {
|
|
|
939
1088
|
this._dirtyBinding ||
|
|
940
1089
|
this._dirtyWatch ||
|
|
941
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
|
+
}
|
|
942
1114
|
if (dirty) {
|
|
943
1115
|
// 目录可能在 load 之后被外部删掉:`_storeDirReady` 只当"上次写过"的快路径,命中时补一次
|
|
944
1116
|
// stat;失配就重建目录,并让分片/格式/忽略三处的已就绪状态一起失效。
|
|
@@ -993,73 +1165,22 @@ export class ProjectMemoryStore {
|
|
|
993
1165
|
let removalFailed = false
|
|
994
1166
|
try {
|
|
995
1167
|
// 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
this.
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
for (const rel of this._compactQueue) {
|
|
1005
|
-
if (compactBudget <= 0) break
|
|
1006
|
-
compactBudget--
|
|
1007
|
-
this._compactQueue.delete(rel)
|
|
1008
|
-
if (this.files[rel]) this._dirtyShards.add(rel)
|
|
1009
|
-
}
|
|
1010
|
-
for (const rel of this._dirtyShards) {
|
|
1011
|
-
if (this.files[rel]) {
|
|
1012
|
-
const nextSha = this.files[rel].sha256 ?? null
|
|
1013
|
-
const base = this._baseFileSha.get(rel) ?? null
|
|
1014
|
-
const disk = this._shardDiskRecord(rel)
|
|
1015
|
-
// 磁盘分片加载后被别的进程改过:按 indexedAt 收敛,本地更新则覆盖,对方更新则读回内存。
|
|
1016
|
-
if (disk.exists && disk.sha !== base && disk.sha !== nextSha) {
|
|
1017
|
-
const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
|
|
1018
|
-
const diskAt = Date.parse(disk.record?.indexedAt || '') || 0
|
|
1019
|
-
if (localAt > diskAt) {
|
|
1020
|
-
this._ensureShardsDir()
|
|
1021
|
-
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
|
|
1022
|
-
this._baseFileSha.set(rel, nextSha)
|
|
1023
|
-
continue
|
|
1024
|
-
}
|
|
1025
|
-
this._adoptDiskShard(rel, disk)
|
|
1026
|
-
this._warnConflict(rel)
|
|
1027
|
-
continue
|
|
1028
|
-
}
|
|
1029
|
-
this._ensureShardsDir()
|
|
1030
|
-
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) }, { ensureDir: false })
|
|
1031
|
-
this._baseFileSha.set(rel, nextSha)
|
|
1032
|
-
} else {
|
|
1033
|
-
this._removedShards.add(rel)
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
this._dirtyShards.clear()
|
|
1037
|
-
for (const rel of this._removedShards) {
|
|
1038
|
-
const base = this._baseFileSha.get(rel) ?? null
|
|
1039
|
-
const disk = this._shardDiskRecord(rel)
|
|
1040
|
-
if (disk.exists && disk.sha !== base) {
|
|
1041
|
-
// 删除与另一进程的更新撞车:没有删除时间戳可比,保守采用对方版本,让内存与磁盘一致。
|
|
1042
|
-
this._adoptDiskShard(rel, disk)
|
|
1043
|
-
this._warnConflict(rel)
|
|
1044
|
-
this._removedShards.delete(rel)
|
|
1045
|
-
continue
|
|
1046
|
-
}
|
|
1047
|
-
try {
|
|
1048
|
-
// 删除也要对 Windows 瞬时占用重试;失败时**保留删除意图**,否则下一次 load 会把
|
|
1049
|
-
// 这个 shard 里的旧条目复活(`unlinkSync` 的 EPERM 曾经被 catch 成"已经没了")。
|
|
1050
|
-
unlinkWithRetry(shardRelPath(this.dir, rel))
|
|
1051
|
-
} catch (err) {
|
|
1052
|
-
if (err?.code !== 'ENOENT') {
|
|
1053
|
-
removalFailed = true
|
|
1054
|
-
console.error(
|
|
1055
|
-
`[dsh-project-memory] could not delete shard for ${rel}: ${err?.message || err}; will retry`,
|
|
1056
|
-
)
|
|
1057
|
-
continue
|
|
1058
|
-
}
|
|
1059
|
-
}
|
|
1060
|
-
this._removedShards.delete(rel)
|
|
1061
|
-
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
|
|
1062
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
|
|
1063
1184
|
if (this._dirtyInsights) {
|
|
1064
1185
|
// v2 → v3 是纯语义升级,形状不变;老版本读到 v3 仍按 v2 字段解析。
|
|
1065
1186
|
if (this.insights && this.insights.version !== 3) this.insights.version = 3
|
|
@@ -1079,6 +1200,9 @@ export class ProjectMemoryStore {
|
|
|
1079
1200
|
if (this._dirtyBinding) {
|
|
1080
1201
|
writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding, { ensureDir: false })
|
|
1081
1202
|
this._dirtyBinding = false
|
|
1203
|
+
// 这份内容已经落盘:基线推进、tombstone 清空,否则旧墓碑会误杀对方之后的新绑定。
|
|
1204
|
+
this._baseBinding = new Map(Object.entries(this.binding))
|
|
1205
|
+
this._deletedBindings.clear()
|
|
1082
1206
|
}
|
|
1083
1207
|
if (this._dirtyWatch) {
|
|
1084
1208
|
writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist, { ensureDir: false })
|
|
@@ -1105,42 +1229,389 @@ export class ProjectMemoryStore {
|
|
|
1105
1229
|
return !removalFailed
|
|
1106
1230
|
}
|
|
1107
1231
|
|
|
1108
|
-
/**
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
const entries = (disk.entries || []).filter(isRecord).map(stripPersistedDerived)
|
|
1114
|
-
this.files[rel] = disk.record
|
|
1115
|
-
this.entries[rel] = entries
|
|
1116
|
-
this._setFileTextChars(rel, entryTextChars(entries))
|
|
1117
|
-
this._entriesVersion++
|
|
1118
|
-
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
|
|
1119
1237
|
}
|
|
1120
1238
|
|
|
1121
|
-
/**
|
|
1122
|
-
|
|
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 = []
|
|
1123
1288
|
try {
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
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}`)
|
|
1127
1302
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
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
|
|
1133
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'))
|
|
1134
1374
|
} catch {
|
|
1135
|
-
return
|
|
1375
|
+
return true
|
|
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)
|
|
1136
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
|
|
1137
1442
|
}
|
|
1138
1443
|
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
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
|
|
1144
1615
|
}
|
|
1145
1616
|
|
|
1146
1617
|
/** 退出/卸载路径的同步兜底(见 util/flush.js)。 */
|
|
@@ -1177,6 +1648,7 @@ export class ProjectMemoryStore {
|
|
|
1177
1648
|
* 用墓碑挡住,避免"删了又被对方的旧副本复活"。分片不走这里(按 hash 冲突检测)。
|
|
1178
1649
|
*/
|
|
1179
1650
|
_mergeAuxFromDisk() {
|
|
1651
|
+
const before = this._readErrors.size
|
|
1180
1652
|
if (this._dirtyInsights) {
|
|
1181
1653
|
// 先按“上次落盘基线”记墓碑:prune/applyDecay 等原地 splice 不经过 replaceInsightItems。
|
|
1182
1654
|
const current = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
|
|
@@ -1225,9 +1697,23 @@ export class ProjectMemoryStore {
|
|
|
1225
1697
|
// 任务级条目单独合并:两边都可能新增/删除,按整条任务的时间戳选一侧会静默丢一边。
|
|
1226
1698
|
const base = this._baseTaskInsightIds.get(t.id) || new Set()
|
|
1227
1699
|
const mergedInsights = mergeTaskInsights(t, prev, base)
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
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)
|
|
1231
1717
|
}
|
|
1232
1718
|
// `removeTask` 已把它从内存数组移除,上面循环看不到;不在这里剔除会在同一次 save 里被写回。
|
|
1233
1719
|
for (const id of this._deletedTaskIds) byId.delete(id)
|
|
@@ -1238,9 +1724,22 @@ export class ProjectMemoryStore {
|
|
|
1238
1724
|
if (this._dirtyBinding) {
|
|
1239
1725
|
const disk = this._loadJson(path.join(this.dir, BINDING_FILE), {})
|
|
1240
1726
|
if (isRecord(disk)) {
|
|
1727
|
+
// 只回写“相对加载基线有变化”的本地项。整份本地快照覆盖会把另一进程刚改的
|
|
1728
|
+
// 绑定回退成旧任务,也会让本地旧内存把对方刚删的会话复活。
|
|
1241
1729
|
const merged = { ...disk }
|
|
1242
|
-
|
|
1243
|
-
for (const sid of
|
|
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
|
+
}
|
|
1244
1743
|
this.binding = merged
|
|
1245
1744
|
this._auxVersion++
|
|
1246
1745
|
}
|
|
@@ -1255,6 +1754,7 @@ export class ProjectMemoryStore {
|
|
|
1255
1754
|
this._auxVersion++
|
|
1256
1755
|
}
|
|
1257
1756
|
}
|
|
1757
|
+
return this._readErrors.size === before
|
|
1258
1758
|
}
|
|
1259
1759
|
|
|
1260
1760
|
getIdfCache() {
|
|
@@ -1329,7 +1829,7 @@ export class ProjectMemoryStore {
|
|
|
1329
1829
|
if (entries.length) {
|
|
1330
1830
|
// searchText 在内存里物化(写入/检索都靠它),但 save() 不会把它写盘。
|
|
1331
1831
|
const enriched = entries.map((e) => {
|
|
1332
|
-
const out =
|
|
1832
|
+
const out = withoutPersistedDerived({ ...e })
|
|
1333
1833
|
out.searchText = makeSearchText(out)
|
|
1334
1834
|
return out
|
|
1335
1835
|
})
|
|
@@ -1534,6 +2034,9 @@ export class ProjectMemoryStore {
|
|
|
1534
2034
|
const result = fn(this)
|
|
1535
2035
|
this.pruneTasks()
|
|
1536
2036
|
if (options.save !== false) this.save()
|
|
2037
|
+
// save:false 只推迟落盘,不能丢掉"还有脏数据"——否则回合结束前 cd 到无根目录或进程常驻,
|
|
2038
|
+
// 这次热点更新就永远只在内存里。
|
|
2039
|
+
else if (this.hasDirty()) trackDirty(this)
|
|
1537
2040
|
return result
|
|
1538
2041
|
}
|
|
1539
2042
|
|