@yolk_vat-y/dsh-project-memory 0.6.3 → 0.6.4
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 +140 -8
- package/README.md +26 -23
- package/README.zh-CN.md +24 -21
- package/client/client.js +272 -138
- package/client/client.js.map +1 -1
- package/package.json +3 -2
- package/scripts/bench-synthetic.mjs +22 -11
- package/src/audit.js +36 -32
- package/src/auto-inject.js +44 -23
- package/src/client/MemoryView.tsx +72 -4
- package/src/client/ShowTaskPanelNode.tsx +8 -5
- package/src/client/TaskCommandNode.tsx +22 -17
- package/src/client/TaskComponents.tsx +18 -3
- package/src/client/TaskPanel.tsx +50 -85
- package/src/client/client.ts +26 -6
- package/src/client/commands.ts +67 -0
- package/src/client/task-ui-store.ts +15 -2
- package/src/commands/task-actions.js +56 -2
- package/src/index.js +12 -0
- package/src/insight-store.js +200 -78
- package/src/lazy.js +3 -1
- package/src/ops.js +1 -1
- package/src/readiness.js +1 -1
- package/src/recall.js +76 -30
- package/src/setup/taskbridge.js +34 -3
- package/src/store.js +315 -44
- package/src/tools/forget.js +11 -8
- package/src/tools/index-doc.js +3 -5
- package/src/tools/index-repo.js +10 -11
- package/src/tools/lesson-tools.js +25 -35
- package/src/tools/query-memory.js +81 -28
- package/src/tools/remember.js +14 -11
- package/src/tools/stats.js +26 -3
- package/src/tools/task-tools.js +11 -12
- package/src/tools/watch-repo.js +3 -5
- package/src/types.js +9 -4
- package/src/util/fs.js +128 -1
- package/src/util/search.js +6 -27
- package/src/vector-index.js +175 -22
- package/src/watch.js +2 -2
package/src/setup/taskbridge.js
CHANGED
|
@@ -6,6 +6,7 @@ import { createHash, randomUUID } from 'node:crypto'
|
|
|
6
6
|
import { memoryRootFor, resolveProjectMemoryRoot } from '../util/fs.js'
|
|
7
7
|
import { sessionWorkingDir } from '../util/session-dir.js'
|
|
8
8
|
import { ProjectMemoryStore } from '../store.js'
|
|
9
|
+
import { BoundedMap } from '../util/session-cache.js'
|
|
9
10
|
import { stepContent, stepStatus } from '../util/task-view.js'
|
|
10
11
|
|
|
11
12
|
const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image'])
|
|
@@ -201,7 +202,7 @@ export function onSessionEvent(config, session, event, meta, ctx) {
|
|
|
201
202
|
// 直接改了 task 内容就必须走标脏入口:只手置 _dirtyTasks 会漏掉驻留估算的新版本维。
|
|
202
203
|
s.markTasksDirty()
|
|
203
204
|
}
|
|
204
|
-
})
|
|
205
|
+
}, { save: false })
|
|
205
206
|
} catch {
|
|
206
207
|
/* 人类消息戳记失败不影响主流程 */
|
|
207
208
|
}
|
|
@@ -268,26 +269,56 @@ export function onSessionEvent(config, session, event, meta, ctx) {
|
|
|
268
269
|
if (!rel) return
|
|
269
270
|
const kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
|
|
270
271
|
if (!kind) return
|
|
272
|
+
// 文件工具调用是最高频的写口:每次 commit 都落盘会把 tasks.json 写成“每读一个文件一次”。
|
|
273
|
+
// 这里只改内存 + 标脏,回合结束(turn/end)或会话销毁时统一 flush。
|
|
271
274
|
store.commit((s) => {
|
|
272
275
|
const task = s.getTask(taskId)
|
|
273
276
|
if (!task || task.archived) return
|
|
274
277
|
touchTaskFile(task, rel, kind, now)
|
|
275
278
|
task.lastActiveAt = now
|
|
276
279
|
s.markTasksDirty()
|
|
277
|
-
})
|
|
280
|
+
}, { save: false })
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** 把延迟写的任务变更落盘;没有脏数据时 save() 自身早退。 */
|
|
285
|
+
export function flushTaskStore(cwd, config) {
|
|
286
|
+
if (!cwd) return
|
|
287
|
+
try {
|
|
288
|
+
const { store } = taskStoreFor(cwd, config)
|
|
289
|
+
if (store) store.save()
|
|
290
|
+
} catch (err) {
|
|
291
|
+
console.error('[dsh-project-memory] taskbridge flush:', err?.message || err)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function flushSessionTaskStore(session, config, ctx) {
|
|
296
|
+
try {
|
|
297
|
+
flushTaskStore(sessionWorkingDir(session, { ctx }), config)
|
|
298
|
+
} catch (err) {
|
|
299
|
+
console.error('[dsh-project-memory] taskbridge flush:', err?.message || err)
|
|
278
300
|
}
|
|
279
301
|
}
|
|
280
302
|
|
|
281
303
|
/** 插件接线:订阅 session/event;卸载时清会话元数据。 */
|
|
282
304
|
export function setupTaskbridge(ctx, config) {
|
|
283
305
|
if (config.tasklist?.enabled === false) return
|
|
284
|
-
|
|
306
|
+
// 会话元数据按会话封顶:旧实现用无界 Map,长期运行的 web 进程里每个会话都会永久留一条。
|
|
307
|
+
const meta = new BoundedMap(200)
|
|
285
308
|
ctx.on('session/event', (session, event) => {
|
|
286
309
|
try {
|
|
287
310
|
onSessionEvent(config, session, event, meta, ctx)
|
|
288
311
|
} catch (err) {
|
|
289
312
|
console.error('[dsh-project-memory] taskbridge:', err?.message)
|
|
290
313
|
}
|
|
314
|
+
// 文件热点/人类消息戳记是延迟写:回合结束补一次落盘,崩溃时最多丢一个回合的计数。
|
|
315
|
+
if (event?.type === 'turn/end') {
|
|
316
|
+
flushSessionTaskStore(session, config, ctx)
|
|
317
|
+
}
|
|
318
|
+
})
|
|
319
|
+
ctx.on('session/disposed', (session) => {
|
|
320
|
+
flushSessionTaskStore(session, config, ctx)
|
|
321
|
+
if (session?.id) meta.delete(session.id)
|
|
291
322
|
})
|
|
292
323
|
ctx.effect(() => () => meta.clear())
|
|
293
324
|
}
|
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 { writeJsonAtomic } from './util/fs.js'
|
|
5
|
+
import { acquireDirLock, writeJsonAtomic } from './util/fs.js'
|
|
6
6
|
import { backfillDerivedTriggers } from './readiness.js'
|
|
7
7
|
|
|
8
8
|
const FORMAT_FILE = 'format.json'
|
|
@@ -38,7 +38,7 @@ const COMPACT_BATCH = 200
|
|
|
38
38
|
*
|
|
39
39
|
* 用 `Buffer.byteLength()` 而不是 `String.length`:CJK 在 UTF-8 里 3 字节/字符,而 V8
|
|
40
40
|
* 双字节串 2 字节/字符——UTF-8 对非 ASCII 是偏高的代理指标,对纯 ASCII 精确。缓存预算
|
|
41
|
-
* 容得下这个误差(实测两端 ±13%,见 `test/store-cache.test.mjs`
|
|
41
|
+
* 容得下这个误差(实测两端 ±13%,见 `test/store-cache.test.mjs` 与内部设计笔记)。
|
|
42
42
|
*
|
|
43
43
|
* 递归用深度上限而不是 `Set` 去环:store 的对象图来自 `JSON.parse`,本就无环;深度上限
|
|
44
44
|
* 既挡畸形数据,又比逐对象 `Set` 查重快 ~30%(70119 条目实测 36ms vs 52ms)。
|
|
@@ -208,6 +208,16 @@ function evictStoreCache(keepKey) {
|
|
|
208
208
|
const oldest = storeCache.keys().next().value
|
|
209
209
|
if (oldest === undefined || oldest === keepKey) break
|
|
210
210
|
if (exact) total -= _estimateResidentBytes(storeCache.get(oldest))
|
|
211
|
+
// 逐出前先落盘:任务热点/人类消息是延迟写的(turn/end 才 flush),
|
|
212
|
+
// 若这里直接丢实例,还没到回合结束的变更就再也回不来了。save() 无脏数据时自己早退。
|
|
213
|
+
const evicted = storeCache.get(oldest)
|
|
214
|
+
if (evicted && evicted.hasDirty()) {
|
|
215
|
+
try {
|
|
216
|
+
evicted.save()
|
|
217
|
+
} catch (err) {
|
|
218
|
+
console.error(`[dsh-project-memory] evicted store save failed: ${err?.message || err}`)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
211
221
|
storeCache.delete(oldest)
|
|
212
222
|
}
|
|
213
223
|
// 没做过精确计量就不报"单实例超预算":算都没算,报出来的数是估的。真超预算时
|
|
@@ -248,6 +258,13 @@ function isRecord(value) {
|
|
|
248
258
|
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
249
259
|
}
|
|
250
260
|
|
|
261
|
+
/** 两个 ISO 时间戳的先后;缺失/非法一律 0,保证可比较。 */
|
|
262
|
+
function newerIso(a, b) {
|
|
263
|
+
const ta = Date.parse(a || '') || 0
|
|
264
|
+
const tb = Date.parse(b || '') || 0
|
|
265
|
+
return ta - tb
|
|
266
|
+
}
|
|
267
|
+
|
|
251
268
|
/**
|
|
252
269
|
* 落盘的 entry 只保留**不可推导的事实**。两个派生字段永远不写盘:
|
|
253
270
|
* - `linkedSymbols`:跨实体派生(取决于符号表当前状态),读取期由 src/link.js 解算;
|
|
@@ -352,6 +369,20 @@ export class ProjectMemoryStore {
|
|
|
352
369
|
this.watchlist = []
|
|
353
370
|
this._dirtyShards = new Set()
|
|
354
371
|
this._removedShards = new Set()
|
|
372
|
+
/** 加载时的分片 hash:跨进程写冲突检测的基准。 */
|
|
373
|
+
this._baseFileSha = new Map()
|
|
374
|
+
/** 本地删除留痕:合并另一进程的磁盘状态时不能把它们复活。 */
|
|
375
|
+
this._deletedInsightIds = new Set()
|
|
376
|
+
this._deletedTaskIds = new Set()
|
|
377
|
+
this._deletedBindings = new Set()
|
|
378
|
+
this._removedWatch = new Set()
|
|
379
|
+
/** 上次落盘/加载时的 insight id 集合:原地 splice 的删除也要能被合并逻辑看见。 */
|
|
380
|
+
this._baseInsightIds = new Set()
|
|
381
|
+
this._lockWarned = false
|
|
382
|
+
this._conflictWarned = new Set()
|
|
383
|
+
/** 锁竞争跳过落盘后的有限次延迟重试;unref,避免拖住进程退出。 */
|
|
384
|
+
this._saveRetryTimer = null
|
|
385
|
+
this._saveRetryAttempts = 0
|
|
355
386
|
this._dirtyInsights = false
|
|
356
387
|
this._dirtyTasks = false
|
|
357
388
|
this._dirtyBinding = false
|
|
@@ -400,6 +431,7 @@ export class ProjectMemoryStore {
|
|
|
400
431
|
this._migrateLegacyIfNeeded()
|
|
401
432
|
this._loadSharded()
|
|
402
433
|
this._loadInsights()
|
|
434
|
+
this._pruneBindings()
|
|
403
435
|
this._removeLegacyTypeCache()
|
|
404
436
|
// 有些路径只读不写(审计 jsonl 直接写在 store 目录里),所以这里也补一次自我忽略,
|
|
405
437
|
// 让老版本建出来的 store 在第一次 load 就补上。
|
|
@@ -494,6 +526,31 @@ export class ProjectMemoryStore {
|
|
|
494
526
|
this._textChars += chars - prev
|
|
495
527
|
}
|
|
496
528
|
|
|
529
|
+
/**
|
|
530
|
+
* 绑定只对“还能续做”的任务有意义:任务已删除或已归档时清掉对应会话绑定。
|
|
531
|
+
* 否则 binding.json 会永久留着指向归档任务的条目,下一次 todo 写入又会建新任务。
|
|
532
|
+
* 只标脏、不立刻落盘——读路径不应为了清理额外写一次盘。
|
|
533
|
+
*/
|
|
534
|
+
_pruneBindings() {
|
|
535
|
+
// 旧 store/手工损坏的 JSON 可能不是期望形状;读路径不能因此抛错。
|
|
536
|
+
const tasks = Array.isArray(this.tasks) ? this.tasks : []
|
|
537
|
+
const binding = this.binding
|
|
538
|
+
if (!binding || typeof binding !== 'object' || Array.isArray(binding)) return
|
|
539
|
+
const byId = new Map(tasks.filter((t) => t && t.id).map((t) => [t.id, t]))
|
|
540
|
+
let changed = false
|
|
541
|
+
for (const sid of Object.keys(binding)) {
|
|
542
|
+
const task = byId.get(binding[sid])
|
|
543
|
+
if (task && !task.archived) continue
|
|
544
|
+
delete binding[sid]
|
|
545
|
+
this._deletedBindings.add(sid)
|
|
546
|
+
changed = true
|
|
547
|
+
}
|
|
548
|
+
if (changed) {
|
|
549
|
+
this._dirtyBinding = true
|
|
550
|
+
this._auxVersion++
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
497
554
|
_loadSharded() {
|
|
498
555
|
let shardNames = []
|
|
499
556
|
try {
|
|
@@ -507,6 +564,7 @@ export class ProjectMemoryStore {
|
|
|
507
564
|
if (!shard || typeof shard.relPath !== 'string' || !isRecord(shard.record)) continue
|
|
508
565
|
this._setFileTextChars(shard.relPath, counter.chars)
|
|
509
566
|
this.files[shard.relPath] = shard.record
|
|
567
|
+
this._baseFileSha.set(shard.relPath, shard.record.sha256 ?? null)
|
|
510
568
|
// 畸形 shard(entries 被写成对象/null)不能让 allEntries() 在 `for…of` 上抛错,
|
|
511
569
|
// 否则一个坏文件会拖垮整个进程的每一次读取。
|
|
512
570
|
const list = Array.isArray(shard.entries) ? shard.entries.filter(isRecord) : []
|
|
@@ -560,6 +618,7 @@ export class ProjectMemoryStore {
|
|
|
560
618
|
// PR3:v1 → v2 懒回填派生 trigger(纯确定性、幂等;不调用模型,不改写已有字段)
|
|
561
619
|
if (backfillDerivedTriggers(this.insights)) this._dirtyInsights = true
|
|
562
620
|
// 迁移与回填都会改 items;换掉整个文档后让 auxCharsOf/精确估算重算。
|
|
621
|
+
this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
|
|
563
622
|
this._auxVersion++
|
|
564
623
|
}
|
|
565
624
|
|
|
@@ -630,7 +689,12 @@ export class ProjectMemoryStore {
|
|
|
630
689
|
}
|
|
631
690
|
|
|
632
691
|
replaceInsightItems(items) {
|
|
692
|
+
const next = new Set((items || []).map((it) => it?.id).filter(Boolean))
|
|
693
|
+
// 与上次落盘的基线比,而不是与当前数组比:调用方经常先原地 splice 再调用这里。
|
|
694
|
+
for (const id of this._baseInsightIds) if (!next.has(id)) this._deletedInsightIds.add(id)
|
|
695
|
+
for (const id of next) this._deletedInsightIds.delete(id)
|
|
633
696
|
this.insights.items = items
|
|
697
|
+
this._baseInsightIds = next
|
|
634
698
|
this._dirtyInsights = true
|
|
635
699
|
this._auxVersion++
|
|
636
700
|
}
|
|
@@ -687,6 +751,17 @@ export class ProjectMemoryStore {
|
|
|
687
751
|
}
|
|
688
752
|
}
|
|
689
753
|
|
|
754
|
+
/** 是否有待落盘的变更;逐出缓存前用它避免为干净 store 触发 save 的旁路副作用。 */
|
|
755
|
+
hasDirty() {
|
|
756
|
+
return this._compactQueue.size > 0
|
|
757
|
+
|| this._dirtyShards.size > 0
|
|
758
|
+
|| this._removedShards.size > 0
|
|
759
|
+
|| this._dirtyInsights
|
|
760
|
+
|| this._dirtyTasks
|
|
761
|
+
|| this._dirtyBinding
|
|
762
|
+
|| this._dirtyWatch
|
|
763
|
+
}
|
|
764
|
+
|
|
690
765
|
save() {
|
|
691
766
|
// 没有脏数据就不落盘。watch 每轮对每个根都无条件 commit → save;照旧执行的话,
|
|
692
767
|
// 末尾的 ID 缓存失效会打在跨实例共享的 store 上,等于每轮清空一次 IDF 复用(v0.3.4 的 20x)。
|
|
@@ -707,55 +782,222 @@ export class ProjectMemoryStore {
|
|
|
707
782
|
// 自我忽略也在无脏数据时执行:老版本建出来的 store 会在下一次 save 时补上。
|
|
708
783
|
this.ensureSelfIgnore()
|
|
709
784
|
if (!dirty) return
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
785
|
+
// 跨进程:整段读改写放进目录锁;拿不到锁就保持脏状态,等下一次写重试(不静默丢数据)。
|
|
786
|
+
const release = acquireDirLock(this.dir)
|
|
787
|
+
if (!release) {
|
|
788
|
+
if (!this._lockWarned) {
|
|
789
|
+
this._lockWarned = true
|
|
790
|
+
console.error(`[dsh-project-memory] store ${this.dir} is busy (another dsh process is writing); this save was skipped and will retry shortly.`)
|
|
791
|
+
}
|
|
792
|
+
this._scheduleSaveRetry()
|
|
793
|
+
return
|
|
713
794
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
795
|
+
try {
|
|
796
|
+
// 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
|
|
797
|
+
this._mergeAuxFromDisk()
|
|
798
|
+
if (!this._formatWritten) {
|
|
799
|
+
writeJsonAtomic(path.join(this.dir, FORMAT_FILE), { version: 2, layout: 'sharded' })
|
|
800
|
+
this._formatWritten = true
|
|
801
|
+
}
|
|
802
|
+
// 存量压实:≤0.5.10 的分片带着派生字段,而那些字段只在分片被重写时才会从磁盘消失。
|
|
803
|
+
// 每轮最多补写 COMPACT_BATCH 个,让升级后的 store 在后续任意一次 save(watch 轮询、
|
|
804
|
+
// 索引、写入)里自动收敛,而不是永远停在旧体积。
|
|
805
|
+
let compactBudget = COMPACT_BATCH
|
|
806
|
+
for (const rel of this._compactQueue) {
|
|
807
|
+
if (compactBudget <= 0) break
|
|
808
|
+
compactBudget--
|
|
809
|
+
this._compactQueue.delete(rel)
|
|
810
|
+
if (this.files[rel]) this._dirtyShards.add(rel)
|
|
811
|
+
}
|
|
812
|
+
for (const rel of this._dirtyShards) {
|
|
813
|
+
if (this.files[rel]) {
|
|
814
|
+
const nextSha = this.files[rel].sha256 ?? null
|
|
815
|
+
const base = this._baseFileSha.get(rel) ?? null
|
|
816
|
+
const disk = this._shardDiskRecord(rel)
|
|
817
|
+
// 磁盘分片在加载后被别的进程改过,且不是我们这一版:按 indexedAt 收敛,
|
|
818
|
+
// 本地更新则覆盖(否则显式 index 的结果会静默丢掉),对方更新则把对方读回内存。
|
|
819
|
+
if (disk.exists && disk.sha !== base && disk.sha !== nextSha) {
|
|
820
|
+
const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
|
|
821
|
+
const diskAt = Date.parse(disk.record?.indexedAt || '') || 0
|
|
822
|
+
if (localAt > diskAt) {
|
|
823
|
+
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) })
|
|
824
|
+
this._baseFileSha.set(rel, nextSha)
|
|
825
|
+
continue
|
|
826
|
+
}
|
|
827
|
+
this._adoptDiskShard(rel, disk)
|
|
828
|
+
this._warnConflict(rel)
|
|
829
|
+
continue
|
|
830
|
+
}
|
|
831
|
+
// 父目录由 writeJsonAtomic 保证
|
|
832
|
+
writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) })
|
|
833
|
+
this._baseFileSha.set(rel, nextSha)
|
|
834
|
+
} else {
|
|
835
|
+
this._removedShards.add(rel)
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
this._dirtyShards.clear()
|
|
839
|
+
for (const rel of this._removedShards) {
|
|
840
|
+
const base = this._baseFileSha.get(rel) ?? null
|
|
841
|
+
const disk = this._shardDiskRecord(rel)
|
|
842
|
+
if (disk.exists && disk.sha !== base) {
|
|
843
|
+
// 删除与另一进程的更新撞车:没有删除时间戳可比,保守采用对方版本,
|
|
844
|
+
// 至少让内存与磁盘一致(旧实现只跳过写,内存仍认为已删)。
|
|
845
|
+
this._adoptDiskShard(rel, disk)
|
|
846
|
+
this._warnConflict(rel)
|
|
847
|
+
continue
|
|
848
|
+
}
|
|
849
|
+
try {
|
|
850
|
+
unlinkSync(shardRelPath(this.dir, rel))
|
|
851
|
+
} catch {
|
|
852
|
+
// shard file already gone; nothing to do
|
|
853
|
+
}
|
|
854
|
+
this._baseFileSha.delete(rel)
|
|
855
|
+
}
|
|
856
|
+
this._removedShards.clear()
|
|
857
|
+
if (this._dirtyInsights) {
|
|
858
|
+
// v2 → v3 是纯语义升级(`kind:'experience'` 从"影子副本"变成一等实体),形状不变;
|
|
859
|
+
// 落盘即把版本推上去,老版本读到 v3 也照样按 v2 的字段解析(它只是排除 experience 影子)。
|
|
860
|
+
if (this.insights && this.insights.version !== 3) this.insights.version = 3
|
|
861
|
+
writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
|
|
862
|
+
this._dirtyInsights = false
|
|
863
|
+
}
|
|
864
|
+
if (this._dirtyTasks) {
|
|
865
|
+
writeJsonAtomic(path.join(this.dir, TASKS_FILE), this.tasks)
|
|
866
|
+
this._dirtyTasks = false
|
|
867
|
+
}
|
|
868
|
+
if (this._dirtyBinding) {
|
|
869
|
+
writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding)
|
|
870
|
+
this._dirtyBinding = false
|
|
871
|
+
}
|
|
872
|
+
if (this._dirtyWatch) {
|
|
873
|
+
writeJsonAtomic(path.join(this.dir, WATCH_FILE), this.watchlist)
|
|
874
|
+
this._dirtyWatch = false
|
|
875
|
+
}
|
|
876
|
+
} finally {
|
|
877
|
+
release()
|
|
723
878
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
879
|
+
this._saveRetryAttempts = 0
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/**
|
|
883
|
+
* 冲突时采用另一进程的分片:内存里的 record/entries 与磁盘对齐,并让 IDF/驻留账失效。
|
|
884
|
+
* 磁盘 entries 可能来自旧版本或损坏文件,和 `_loadSharded` 一样只收 record。
|
|
885
|
+
*/
|
|
886
|
+
_adoptDiskShard(rel, disk) {
|
|
887
|
+
const entries = (disk.entries || []).filter(isRecord).map(stripPersistedDerived)
|
|
888
|
+
this.files[rel] = disk.record
|
|
889
|
+
this.entries[rel] = entries
|
|
890
|
+
this._setFileTextChars(rel, entryTextChars(entries))
|
|
891
|
+
this._entriesVersion++
|
|
892
|
+
this._baseFileSha.set(rel, disk.sha)
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** 读磁盘分片(不存在/损坏都返回 exists:false)。 */
|
|
896
|
+
_shardDiskRecord(rel) {
|
|
897
|
+
try {
|
|
898
|
+
const doc = JSON.parse(readFileSync(shardRelPath(this.dir, rel), 'utf8'))
|
|
899
|
+
if (!isRecord(doc) || typeof doc.relPath !== 'string' || !isRecord(doc.record)) {
|
|
900
|
+
return { exists: false, sha: null, record: null, entries: [] }
|
|
730
901
|
}
|
|
902
|
+
return {
|
|
903
|
+
exists: true,
|
|
904
|
+
sha: doc.record.sha256 ?? null,
|
|
905
|
+
record: doc.record,
|
|
906
|
+
entries: Array.isArray(doc.entries) ? doc.entries : [],
|
|
907
|
+
}
|
|
908
|
+
} catch {
|
|
909
|
+
return { exists: false, sha: null, record: null, entries: [] }
|
|
731
910
|
}
|
|
732
|
-
|
|
733
|
-
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** 锁竞争后的有限次延迟重试;失败仍保持脏状态,下一次写继续尝试。 */
|
|
914
|
+
_scheduleSaveRetry() {
|
|
915
|
+
if (this._saveRetryTimer || this._saveRetryAttempts >= 3) return
|
|
916
|
+
this._saveRetryAttempts++
|
|
917
|
+
this._saveRetryTimer = setTimeout(() => {
|
|
918
|
+
this._saveRetryTimer = null
|
|
734
919
|
try {
|
|
735
|
-
|
|
736
|
-
} catch {
|
|
737
|
-
|
|
920
|
+
this.save()
|
|
921
|
+
} catch (err) {
|
|
922
|
+
console.error(`[dsh-project-memory] deferred save failed: ${err?.message || err}`)
|
|
738
923
|
}
|
|
739
|
-
}
|
|
740
|
-
this.
|
|
924
|
+
}, 100)
|
|
925
|
+
this._saveRetryTimer.unref?.()
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** 冲突只提示一次:这是“对方更新更晚”的正常并发结果,不是每轮刷屏的故障。 */
|
|
929
|
+
_warnConflict(rel) {
|
|
930
|
+
if (this._conflictWarned.has(rel)) return
|
|
931
|
+
this._conflictWarned.add(rel)
|
|
932
|
+
console.error(`[dsh-project-memory] ${rel} changed by another dsh process; this local copy was not written (it will be re-derived on the next scan).`)
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* 写盘前把另一进程已落盘的小文档合并进来。
|
|
937
|
+
*
|
|
938
|
+
* 只合并不覆盖:同 id 取 `updatedAt` 更新的一侧;本进程删掉的 id 用墓碑挡住,
|
|
939
|
+
* 避免“删了又被对方的旧副本复活”。分片不走这里(按 hash 冲突检测)。
|
|
940
|
+
*/
|
|
941
|
+
_mergeAuxFromDisk() {
|
|
741
942
|
if (this._dirtyInsights) {
|
|
742
|
-
//
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
this.
|
|
943
|
+
// 先按“上次落盘基线”记墓碑:prune/applyDecay 等原地 splice 不经过 replaceInsightItems。
|
|
944
|
+
const current = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
|
|
945
|
+
for (const id of this._baseInsightIds) if (!current.has(id)) this._deletedInsightIds.add(id)
|
|
946
|
+
for (const id of current) this._deletedInsightIds.delete(id)
|
|
947
|
+
const disk = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
|
|
948
|
+
if (isRecord(disk) && Array.isArray(disk.items)) {
|
|
949
|
+
const byId = new Map()
|
|
950
|
+
for (const it of disk.items) if (isRecord(it) && it.id) byId.set(it.id, it)
|
|
951
|
+
for (const it of this.insights.items) {
|
|
952
|
+
if (!isRecord(it) || !it.id) continue
|
|
953
|
+
if (this._deletedInsightIds.has(it.id)) {
|
|
954
|
+
byId.delete(it.id)
|
|
955
|
+
continue
|
|
956
|
+
}
|
|
957
|
+
const prev = byId.get(it.id)
|
|
958
|
+
if (!prev || newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
|
|
959
|
+
}
|
|
960
|
+
for (const id of this._deletedInsightIds) byId.delete(id)
|
|
961
|
+
this.insights = { ...this.insights, items: [...byId.values()] }
|
|
962
|
+
this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
|
|
963
|
+
this._auxVersion++
|
|
964
|
+
}
|
|
747
965
|
}
|
|
748
966
|
if (this._dirtyTasks) {
|
|
749
|
-
|
|
750
|
-
|
|
967
|
+
const disk = this._loadJson(path.join(this.dir, TASKS_FILE), [])
|
|
968
|
+
if (Array.isArray(disk)) {
|
|
969
|
+
const byId = new Map()
|
|
970
|
+
for (const t of disk) if (isRecord(t) && t.id) byId.set(t.id, t)
|
|
971
|
+
for (const t of this.tasks) {
|
|
972
|
+
if (!isRecord(t) || !t.id || this._deletedTaskIds.has(t.id)) {
|
|
973
|
+
if (isRecord(t) && t.id) byId.delete(t.id)
|
|
974
|
+
continue
|
|
975
|
+
}
|
|
976
|
+
const prev = byId.get(t.id)
|
|
977
|
+
if (!prev || newerIso(t.updatedAt || t.lastActiveAt, prev.updatedAt || prev.lastActiveAt) >= 0) byId.set(t.id, t)
|
|
978
|
+
}
|
|
979
|
+
this.tasks = [...byId.values()]
|
|
980
|
+
this._auxVersion++
|
|
981
|
+
}
|
|
751
982
|
}
|
|
752
983
|
if (this._dirtyBinding) {
|
|
753
|
-
|
|
754
|
-
|
|
984
|
+
const disk = this._loadJson(path.join(this.dir, BINDING_FILE), {})
|
|
985
|
+
if (isRecord(disk)) {
|
|
986
|
+
const merged = { ...disk }
|
|
987
|
+
for (const [sid, tid] of Object.entries(this.binding)) merged[sid] = tid
|
|
988
|
+
for (const sid of this._deletedBindings) delete merged[sid]
|
|
989
|
+
this.binding = merged
|
|
990
|
+
this._auxVersion++
|
|
991
|
+
}
|
|
755
992
|
}
|
|
756
993
|
if (this._dirtyWatch) {
|
|
757
|
-
|
|
758
|
-
|
|
994
|
+
const disk = this._loadJson(path.join(this.dir, WATCH_FILE), [])
|
|
995
|
+
if (Array.isArray(disk)) {
|
|
996
|
+
const set = new Set([...disk, ...this.watchlist])
|
|
997
|
+
for (const root of this._removedWatch) set.delete(root)
|
|
998
|
+
this.watchlist = [...set]
|
|
999
|
+
this._auxVersion++
|
|
1000
|
+
}
|
|
759
1001
|
}
|
|
760
1002
|
}
|
|
761
1003
|
|
|
@@ -797,6 +1039,7 @@ export class ProjectMemoryStore {
|
|
|
797
1039
|
if (!this.watchlist.includes(root)) {
|
|
798
1040
|
this.watchlist.push(root)
|
|
799
1041
|
this._dirtyWatch = true
|
|
1042
|
+
this._removedWatch.delete(root)
|
|
800
1043
|
this._auxVersion++
|
|
801
1044
|
return true
|
|
802
1045
|
}
|
|
@@ -807,6 +1050,7 @@ export class ProjectMemoryStore {
|
|
|
807
1050
|
const before = this.watchlist.length
|
|
808
1051
|
this.watchlist = this.watchlist.filter((r) => r !== root)
|
|
809
1052
|
if (this.watchlist.length !== before) {
|
|
1053
|
+
this._removedWatch.add(root)
|
|
810
1054
|
this._dirtyWatch = true
|
|
811
1055
|
this._auxVersion++
|
|
812
1056
|
}
|
|
@@ -934,6 +1178,7 @@ export class ProjectMemoryStore {
|
|
|
934
1178
|
|
|
935
1179
|
addTask(task) {
|
|
936
1180
|
this.tasks.push(task)
|
|
1181
|
+
if (task?.id) this._deletedTaskIds.delete(task.id)
|
|
937
1182
|
this._dirtyTasks = true
|
|
938
1183
|
this._auxVersion++
|
|
939
1184
|
}
|
|
@@ -951,18 +1196,38 @@ export class ProjectMemoryStore {
|
|
|
951
1196
|
const idx = this.tasks.findIndex((t) => t.id === id)
|
|
952
1197
|
if (idx === -1) return false
|
|
953
1198
|
this.tasks.splice(idx, 1)
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
}
|
|
1199
|
+
this._deletedTaskIds.add(id)
|
|
1200
|
+
this.removeBindingsForTask(id)
|
|
957
1201
|
this._dirtyTasks = true
|
|
958
|
-
this._dirtyBinding = true
|
|
959
1202
|
this._auxVersion++
|
|
960
1203
|
return true
|
|
961
1204
|
}
|
|
962
1205
|
|
|
1206
|
+
/**
|
|
1207
|
+
* 清掉所有指向该任务的会话绑定。归档/删除任务时调用:任务已停用,绑定再留着
|
|
1208
|
+
* 只会在下一次 todo 写入时被当成"没有任务"再建一条新任务,旧条目却永远占着 binding.json。
|
|
1209
|
+
* @param {string} taskId
|
|
1210
|
+
* @returns {boolean} 是否真的删掉了绑定
|
|
1211
|
+
*/
|
|
1212
|
+
removeBindingsForTask(taskId) {
|
|
1213
|
+
let changed = false
|
|
1214
|
+
for (const sid of Object.keys(this.binding)) {
|
|
1215
|
+
if (this.binding[sid] !== taskId) continue
|
|
1216
|
+
delete this.binding[sid]
|
|
1217
|
+
this._deletedBindings.add(sid)
|
|
1218
|
+
changed = true
|
|
1219
|
+
}
|
|
1220
|
+
if (changed) {
|
|
1221
|
+
this._dirtyBinding = true
|
|
1222
|
+
this._auxVersion++
|
|
1223
|
+
}
|
|
1224
|
+
return changed
|
|
1225
|
+
}
|
|
1226
|
+
|
|
963
1227
|
setBinding(sessionId, taskId) {
|
|
964
1228
|
if (!sessionId) return
|
|
965
1229
|
this.binding[sessionId] = taskId
|
|
1230
|
+
this._deletedBindings.delete(sessionId)
|
|
966
1231
|
this._dirtyBinding = true
|
|
967
1232
|
this._auxVersion++
|
|
968
1233
|
}
|
|
@@ -974,6 +1239,7 @@ export class ProjectMemoryStore {
|
|
|
974
1239
|
removeBinding(sessionId) {
|
|
975
1240
|
if (sessionId && sessionId in this.binding) {
|
|
976
1241
|
delete this.binding[sessionId]
|
|
1242
|
+
this._deletedBindings.add(sessionId)
|
|
977
1243
|
this._dirtyBinding = true
|
|
978
1244
|
this._auxVersion++
|
|
979
1245
|
}
|
|
@@ -1008,10 +1274,15 @@ export class ProjectMemoryStore {
|
|
|
1008
1274
|
return toArchive.length
|
|
1009
1275
|
}
|
|
1010
1276
|
|
|
1011
|
-
|
|
1277
|
+
/**
|
|
1278
|
+
* @param {(store: ProjectMemoryStore) => any} fn 变更函数
|
|
1279
|
+
* @param {{save?: boolean}} [options] save=false 时只标脏,由调用方在回合结束统一 flush。
|
|
1280
|
+
* 文件工具每读一次都会更新任务热点,逐次落盘会把 tasks.json 写成每工具调用一次。
|
|
1281
|
+
*/
|
|
1282
|
+
commit(fn, options = {}) {
|
|
1012
1283
|
const result = fn(this)
|
|
1013
1284
|
this.pruneTasks()
|
|
1014
|
-
this.save()
|
|
1285
|
+
if (options.save !== false) this.save()
|
|
1015
1286
|
return result
|
|
1016
1287
|
}
|
|
1017
1288
|
|
package/src/tools/forget.js
CHANGED
|
@@ -2,6 +2,7 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
|
2
2
|
import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
|
|
3
3
|
import { ProjectMemoryStore } from '../store.js'
|
|
4
4
|
import { cfgInsight, DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
|
|
5
|
+
import { forgetVectorRows } from '../vector-index.js'
|
|
5
6
|
|
|
6
7
|
/** 回报用的一行:`ins_xxx《标题》(project)`。标题已在 removeMemory 里截断。 */
|
|
7
8
|
function line(e) {
|
|
@@ -28,21 +29,18 @@ export function forgetTool(config) {
|
|
|
28
29
|
return defineTool({
|
|
29
30
|
name: 'forget',
|
|
30
31
|
description:
|
|
31
|
-
'Delete memories by id or
|
|
32
|
-
'
|
|
33
|
-
'
|
|
34
|
-
'A keyword that matches more than the configured cap deletes nothing and lists the candidates instead. ' +
|
|
35
|
-
`The ${DELETED_KEEP} most recently deleted entries are kept in that layer's deleted.json next to its store ` +
|
|
36
|
-
'(the path is returned after every deletion) — read it to recover an accidental deletion and save it again.',
|
|
32
|
+
'Delete memories by id or matching keywords, at task/project/global scope. Real deletion, no undo; '
|
|
33
|
+
+ 'the last 5 deleted entries are kept in deleted.json. A keyword matching more than the cap deletes nothing '
|
|
34
|
+
+ 'and lists the candidates instead.',
|
|
37
35
|
parameters: {
|
|
38
36
|
id_or_query: {
|
|
39
37
|
type: 'string',
|
|
40
38
|
required: true,
|
|
41
|
-
description: '
|
|
39
|
+
description: '精确 id 或关键词;id 优先',
|
|
42
40
|
},
|
|
43
41
|
root: {
|
|
44
42
|
type: 'string',
|
|
45
|
-
description: '
|
|
43
|
+
description: '项目根(默认当前工作目录)',
|
|
46
44
|
},
|
|
47
45
|
},
|
|
48
46
|
output: {
|
|
@@ -62,6 +60,11 @@ export function forgetTool(config) {
|
|
|
62
60
|
return res
|
|
63
61
|
})
|
|
64
62
|
globalStore.commit() // global 侧若被删过才落盘
|
|
63
|
+
if (res && res.removed.length) {
|
|
64
|
+
// 向量缓存也是"这条记忆"的一部分:`vectors.json` 里那行是标题的 256 维均值池化,
|
|
65
|
+
// 留着就不算真删。这里不加载模型(只读文件 + 原子重写),失败也只是缓存残留。
|
|
66
|
+
try { forgetVectorRows({ dir: memoryDir, ids: res.removed.map((e) => e.id) }) } catch { /* 缓存删除失败不影响删除承诺 */ }
|
|
67
|
+
}
|
|
65
68
|
if (res && res.tooMany) {
|
|
66
69
|
const head = res.matches.slice(0, 10).map(line)
|
|
67
70
|
const more = res.matches.length > head.length ? ` …(共 ${res.matches.length} 条)` : ''
|
package/src/tools/index-doc.js
CHANGED
|
@@ -9,18 +9,16 @@ export function indexDocTool(ctx, config) {
|
|
|
9
9
|
return defineTool({
|
|
10
10
|
name: 'index_doc',
|
|
11
11
|
description:
|
|
12
|
-
'Index
|
|
13
|
-
'store a short cited summary plus a full-chunk literal term index (no LLM at index time), for later ' +
|
|
14
|
-
'query_memory recall. Re-indexing the same unchanged file is a no-op (content-hash skip).',
|
|
12
|
+
'Index one document (PDF/MD/txt) into project memory; unchanged files are skipped.',
|
|
15
13
|
parameters: {
|
|
16
14
|
file_path: {
|
|
17
15
|
type: 'string',
|
|
18
16
|
required: true,
|
|
19
|
-
description: '
|
|
17
|
+
description: '文档绝对路径',
|
|
20
18
|
},
|
|
21
19
|
root: {
|
|
22
20
|
type: 'string',
|
|
23
|
-
description: '
|
|
21
|
+
description: '项目根(默认会话项目根)',
|
|
24
22
|
},
|
|
25
23
|
},
|
|
26
24
|
output: {
|