@yolk_vat-y/dsh-project-memory 0.6.8 → 0.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lazy.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  findProjectRootWithSource,
8
8
  isGitIgnored,
9
9
  isGitIgnoredBatch,
10
+ isHiddenPath,
10
11
  memoryRootFor,
11
12
  relativePath,
12
13
  rootRejection,
@@ -16,6 +17,7 @@ import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex,
16
17
  import { ProjectMemoryStore } from './store.js'
17
18
  import { onFileObserved } from './enhancer.js'
18
19
  import { sessionWorkingDir } from './util/session-dir.js'
20
+ import { clearIndexFailure, recordIndexFailure } from './index-failures.js'
19
21
 
20
22
  // 根推导策略已收敛到 util/fs.js(唯一实现)。这里重新导出,保持既有 import 路径可用。
21
23
  export { findProjectRoot }
@@ -104,6 +106,12 @@ export async function indexObservedBatch(config, items, watchManager = null) {
104
106
  }
105
107
  const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
106
108
  const rel = storeKey(relativePath(root, filePath))
109
+ // 隐藏路径与扫描口径一致:`.env` / `.github/**` 这类默认是配置/状态/密钥,不因模型
110
+ // 偶然读了一次就进语料;要索引就显式 `index_doc`。
111
+ if (isHiddenPath(rel)) {
112
+ results.set(filePath, false)
113
+ continue
114
+ }
107
115
  const record = store.fileRecord(rel)
108
116
  const st = statSync(filePath)
109
117
  // 快路径:mtime + size 都没动 → 连 git 都不用问。这是"重复读同一个文件"的主路径。
@@ -166,27 +174,39 @@ export async function indexObservedBatch(config, items, watchManager = null) {
166
174
  if (plan.key === UNCHANGED) {
167
175
  // 内容没变、只有 mtime 变了:把新 mtime 记回去,否则下次还要整读一遍。
168
176
  if (typeof plan.mtimeMs === 'number' && store.refreshMtime(cand.rel, plan.mtimeMs)) refreshed = true
177
+ clearIndexFailure(cand.root, cand.rel)
178
+ continue
179
+ }
180
+ clearIndexFailure(cand.root, cand.rel)
181
+ if (plan.key === OVERSIZE) {
182
+ // 与 index_repo 同一语义:文件涨过阈值后,旧条目必须摘掉,而不是只跳过本轮。
183
+ updates.push({ rel: cand.rel, drop: true })
184
+ results.set(cand.filePath, false)
169
185
  continue
170
186
  }
171
- if (plan.key === OVERSIZE) continue
172
187
  updates.push(toFileUpdate(cand.rel, plan, cand.record))
173
188
  if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
174
189
  results.set(cand.filePath, plan.key !== DROP)
175
- } catch {
176
- // 单文件读盘 / 解析失败不影响同批其它文件。
190
+ } catch (err) {
191
+ // 单文件读盘 / 解析失败不影响同批其它文件;但要登记,否则"读了却没索引成"
192
+ // 在界面上完全不可见(过去这里连日志都没有)。
193
+ recordIndexFailure(cand.root, cand.rel, err.message)
177
194
  results.set(cand.filePath, false)
178
195
  }
179
196
  }
180
197
 
198
+ let addedWatch = false
181
199
  if (watchManager && watchManager.addRoot(root)) {
182
200
  // 只有真正新登记的根才持久化:addRoot 拒绝的根(不安全/不存在)不再被无条件
183
201
  // addWatch 记进 watch.json —— 那样会造出一个每次启动都复活的"僵尸根"。
184
- store.addWatch(root)
202
+ addedWatch = store.addWatch(root)
185
203
  }
186
204
 
187
205
  try {
188
206
  if (updates.length > 0) commitFileUpdates(store, { updates })
189
- else if (refreshed) store.commit(() => {})
207
+ // addedWatch 也要落盘:本轮可能没有任何条目更新(文件已是最新),但新登记的 watch 根
208
+ // 是独立的事实;不 save 的话重启后它不在 watch.json 里,监视会静默退回启动时的根集合。
209
+ else if (refreshed || addedWatch) store.commit(() => {})
190
210
  } catch (err) {
191
211
  console.error(`[dsh-project-memory] lazy index commit failed for ${root}: ${err.message}`)
192
212
  }
package/src/ops.js CHANGED
@@ -391,6 +391,19 @@ export function classifyToolCall(name, argsText) {
391
391
  const tool = String(name || '').toLowerCase()
392
392
  const { command, path } = argsFields(argsText)
393
393
  if (SHELL_TOOLS.has(tool)) return classifyShellCommand(command || String(argsText || ''))
394
+ // 宿主的 `str_replace_editor` 用 path + command(view/create/str_replace/insert),
395
+ // 不是 file_path;view 是读,其余三个才是写。漏掉它时文件编辑既不产 file-write,也进不了
396
+ // TaskBridge 的热点文件。
397
+ if (tool === 'str_replace_editor') {
398
+ const obj = safeJson(argsText) || {}
399
+ const filePath = typeof obj.path === 'string' ? obj.path : ''
400
+ const cmd = typeof obj.command === 'string' ? obj.command.toLowerCase() : ''
401
+ if (!filePath || !['create', 'str_replace', 'insert'].includes(cmd)) {
402
+ return { ops: [], targets: [], hosts: [] }
403
+ }
404
+ const targets = [filePath, ...extractPathTokens(filePath)]
405
+ return { ops: ['file-write'], targets: [...new Set(targets)], hosts: [] }
406
+ }
394
407
  if (READ_IMAGE_TOOLS.has(tool)) return { ops: ['read-image'], targets: [], hosts: [] }
395
408
  if (INDEX_TOOLS.has(tool)) return { ops: ['index-doc'], targets: [], hosts: [] }
396
409
  if (FETCH_TOOLS.has(tool)) return { ops: ['fetch-web'], targets: [], hosts: [] }
@@ -1,15 +1,43 @@
1
1
  import { readFile } from 'node:fs/promises'
2
+ import { createRequire } from 'node:module'
3
+ import { pathToFileURL } from 'node:url'
4
+
5
+ const WORKER_SPECIFIER = 'pdfjs-dist/legacy/build/pdf.worker.mjs'
2
6
 
3
7
  let pdfjsPromise
4
8
  let configuredWorkerSrc
5
9
 
10
+ /**
11
+ * 解析 pdf.js 的 worker 模块位置,返回 file:// URL;解析不到返回 undefined。
12
+ *
13
+ * 为什么必须显式给:pdf.js 只在 `isNodeJS` 为真时兜底 `workerSrc ||= './pdf.worker.mjs'`,
14
+ * 而 `isNodeJS` 排除 `process.versions.electron && process.type !== 'browser'`。宿主的插件
15
+ * 进程正是这种形态 → 默认值整块跳过、worker 也没被禁用,取 workerSrc 时直接抛
16
+ * `No "GlobalWorkerOptions.workerSrc" specified`。纯 Node 测试里 `isNodeJS` 为真,永远看不见。
17
+ *
18
+ * 用 file:// URL 而不是路径:worker 由 pdf.js `import(this.workerSrc)` 加载,Windows 的
19
+ * `C:\...` 会被当成协议。
20
+ */
21
+ function resolveWorkerSrc() {
22
+ // Node ≥ 20.6 / 18.19 无 flag;更老的版本这里会抛,退回 require 解析
23
+ try {
24
+ if (typeof import.meta.resolve === 'function') return import.meta.resolve(WORKER_SPECIFIER)
25
+ } catch {}
26
+ try {
27
+ return pathToFileURL(createRequire(import.meta.url).resolve(WORKER_SPECIFIER)).href
28
+ } catch {}
29
+ return undefined
30
+ }
31
+
6
32
  function loadPdfjs() {
7
33
  if (!pdfjsPromise) {
8
34
  pdfjsPromise = import('pdfjs-dist/legacy/build/pdf.mjs')
9
35
  .then((mod) => {
10
- if (configuredWorkerSrc) {
11
- mod.GlobalWorkerOptions.workerSrc = configuredWorkerSrc
12
- }
36
+ // 显式配置 > pdf.js 自己已设的默认值 > 按文件位置解析出来的 URL。
37
+ // 必须用 `||` 而不是 `??`:GlobalWorkerOptions.workerSrc 的初始值是空字符串
38
+ // (GlobalWorkerOptions.#src = ""),`??` 会停在 "" 上直接跳过兜底解析。
39
+ const workerSrc = configuredWorkerSrc || mod.GlobalWorkerOptions.workerSrc || resolveWorkerSrc()
40
+ if (workerSrc) mod.GlobalWorkerOptions.workerSrc = workerSrc
13
41
  return mod
14
42
  })
15
43
  .catch((err) => {
@@ -24,7 +52,8 @@ const PDFJS_OPTIONS = {
24
52
  useSystemFonts: true,
25
53
  isEvalSupported: false,
26
54
  useWorkerFetch: false,
27
- useWorker: false,
55
+ // 这里没有 useWorker:pdf.js 4.x 不认这个键(只有 useWorkerFetch),
56
+ // worker 是否启用只由 GlobalWorkerOptions.workerSrc 决定。
28
57
  // 0 = ERRORS。损坏/线性化缺失的 PDF 会让 pdf.js 打 "Warning: Indexing all PDF objects"
29
58
  // 之类的告警——那是它自己的恢复路径,对使用者没有可操作性,静音。
30
59
  verbosity: 0,
package/src/recall.js CHANGED
@@ -152,7 +152,8 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
152
152
  }
153
153
  if (boundTaskId && store && typeof store.getTask === 'function') {
154
154
  const task = store.getTask(boundTaskId)
155
- for (const it of (task && task.insights) || []) {
155
+ // 归档任务不再向绑定会话提供任务级记忆(与 buildInjection 的 task 守卫同一判据)。
156
+ for (const it of (task && !task.archived && task.insights) || []) {
156
157
  if (!it || it.archived) continue
157
158
  // 任务级也要挡草稿:reflection 写的是 draft:true,未确认前不该被召回。
158
159
  if (it.draft === true) continue
@@ -9,7 +9,7 @@ import { ProjectMemoryStore } from '../store.js'
9
9
  import { BoundedMap } from '../util/session-cache.js'
10
10
  import { stepContent, stepStatus } from '../util/task-view.js'
11
11
 
12
- const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image'])
12
+ const FS_FILE_TOOLS = new Set(['read', 'write', 'edit', 'read_image', 'str_replace_editor'])
13
13
  const WRITE_TOOLS = new Set(['write', 'edit']) // 编辑/写入 = 高热点
14
14
  const READ_TOOLS = new Set(['read', 'read_image'])
15
15
  const MAX_FILES_PER_TASK = 100
@@ -60,7 +60,7 @@ export function normalizeRelFile(root, file) {
60
60
  if (typeof file !== 'string' || !file) return null
61
61
  const abs = path.isAbsolute(file) ? file : path.resolve(root, file)
62
62
  const rel = path.relative(root, abs)
63
- if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null
63
+ if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) return null
64
64
  return rel.split(path.sep).join('/')
65
65
  }
66
66
 
@@ -145,7 +145,10 @@ export function hotSortFiles(files, meta) {
145
145
 
146
146
  /** 触碰文件后更新元数据并重排 task.files(写 vs 读分别记时间/次数)。 */
147
147
  export function touchTaskFile(task, rel, kind, now) {
148
- task.fileMeta = task.fileMeta || {}
148
+ // 手改 / 旧版本的 tasks.json 可能没有这两个集合。读路径必须容错:这里抛一次就会让
149
+ // 该任务后续的所有文件热点更新都静默停掉(外层 catch 只打一行日志)。
150
+ if (!Array.isArray(task.files)) task.files = []
151
+ task.fileMeta = task.fileMeta && typeof task.fileMeta === 'object' && !Array.isArray(task.fileMeta) ? task.fileMeta : {}
149
152
  if (!task.files.includes(rel)) task.files.push(rel)
150
153
  const m = task.fileMeta[rel] || {}
151
154
  m.n = (m.n || 0) + 1 // 兼容旧字段:读+写总数(保留,避免老任务语义漂移)
@@ -263,11 +266,21 @@ export function onSessionEvent(config, session, event, meta, ctx) {
263
266
  } catch {
264
267
  return
265
268
  }
266
- const raw = typeof args?.file_path === 'string' ? args.file_path : null
269
+ // read/write/edit/read_image 用 file_path;宿主的 str_replace_editor 用 path。
270
+ const raw = typeof args?.file_path === 'string'
271
+ ? args.file_path
272
+ : typeof args?.path === 'string' ? args.path : null
267
273
  if (!raw) return
268
274
  const rel = normalizeRelFile(root, raw)
269
275
  if (!rel) return
270
- const kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
276
+ let kind = null
277
+ if (data.name === 'str_replace_editor') {
278
+ const cmd = typeof args?.command === 'string' ? args.command.toLowerCase() : ''
279
+ if (cmd === 'view') kind = 'read'
280
+ else if (['create', 'str_replace', 'insert'].includes(cmd)) kind = 'write'
281
+ } else {
282
+ kind = WRITE_TOOLS.has(data.name) ? 'write' : READ_TOOLS.has(data.name) ? 'read' : null
283
+ }
271
284
  if (!kind) return
272
285
  // 文件工具调用是最高频的写口:每次 commit 都落盘会把 tasks.json 写成“每读一个文件一次”。
273
286
  // 这里只改内存 + 标脏,回合结束(turn/end)或会话销毁时统一 flush。
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, writeJsonAtomic } from './util/fs.js'
5
+ import { acquireDirLock, 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'
@@ -360,6 +360,35 @@ function shardRelPath(dir, rel) {
360
360
  return path.join(dir, SHARDS_DIR, createHash('sha256').update(rel).digest('hex') + '.json')
361
361
  }
362
362
 
363
+ /**
364
+ * watch.json 去重:Windows/macOS 上 `D:\proj` 与 `d:\PROJ` 是同一个物理目录,字符串却不同。
365
+ * 同一目录写两条会让 watch 每轮扫两遍、`watch_repo({watch:false})` 也只删掉其中一条(另一条
366
+ * 下次启动又复活)。保留第一次出现的写法(用户看到的形态不变)。
367
+ * @param {unknown} list
368
+ * @returns {string[]}
369
+ */
370
+ function dedupeWatchRoots(list) {
371
+ const seen = new Set()
372
+ const out = []
373
+ for (const root of Array.isArray(list) ? list : []) {
374
+ if (typeof root !== 'string' || !root) continue
375
+ const key = storeKey(root)
376
+ if (seen.has(key)) continue
377
+ seen.add(key)
378
+ out.push(root)
379
+ }
380
+ return out
381
+ }
382
+
383
+ /** 数条目但**不**物化 searchText:stats/overview 只报数量,不该为一次统计把整库检索文本建出来。 */
384
+ function countEntries(store) {
385
+ let n = 0
386
+ const entries = store?.entries
387
+ if (!entries || typeof entries !== 'object') return n
388
+ for (const list of Object.values(entries)) if (Array.isArray(list)) n += list.length
389
+ return n
390
+ }
391
+
363
392
  export class ProjectMemoryStore {
364
393
  constructor(memoryDir) {
365
394
  this.dir = memoryDir
@@ -513,8 +542,14 @@ export class ProjectMemoryStore {
513
542
  )
514
543
  }
515
544
  for (const rel of Object.keys(files)) {
516
- // 父目录由 writeJsonAtomic 保证
517
- writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: files[rel], entries: (entries[rel] || []).map(withoutPersistedDerived) })
545
+ // 父目录由 writeJsonAtomic 保证。legacy 的每个组都可能是手改/损坏的形状;不是数组就
546
+ // 跳过该组(与 `_loadSharded` 对畸形 shard 的处理一致),不能让一个坏组拖垮整次迁移。
547
+ const group = entries[rel]
548
+ const list = Array.isArray(group) ? group : []
549
+ if (group !== undefined && !Array.isArray(group)) {
550
+ console.error(`[dsh-project-memory] migration skipped malformed entry group for ${rel} (expected an array)`)
551
+ }
552
+ writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: files[rel], entries: list.map(withoutPersistedDerived) })
518
553
  }
519
554
  writeJsonAtomic(formatPath, { version: 2, layout: 'sharded' })
520
555
  for (const stale of [legacyEntriesPath, path.join(this.dir, INDEX_FILE)]) {
@@ -589,9 +624,35 @@ export class ProjectMemoryStore {
589
624
  }
590
625
  this._entriesVersion++
591
626
  this.experience = this._loadJson(path.join(this.dir, EXPERIENCE_FILE), [])
592
- this.tasks = this._loadJson(path.join(this.dir, TASKS_FILE), [])
593
- this.binding = this._loadJson(path.join(this.dir, BINDING_FILE), {})
594
- this.watchlist = this._loadJson(path.join(this.dir, WATCH_FILE), [])
627
+ // 辅助集合也可能被手改/旧版本写成别的形状。读路径不能因此抛错:tasks 里的 null 会让
628
+ // `t.archived` / `.id` 崩,watchlist 不是数组则 `[...watchlist]` 直接 TypeError。
629
+ const tasksDoc = this._loadJson(path.join(this.dir, TASKS_FILE), [])
630
+ this.tasks = Array.isArray(tasksDoc) ? tasksDoc.filter(isRecord) : []
631
+ if (tasksDoc !== null && !Array.isArray(tasksDoc)) {
632
+ console.error(`[dsh-project-memory] ${TASKS_FILE} is not an array; starting with no tasks`)
633
+ }
634
+ // 任务级 insights 同样可能混进 null:`taskContaining()` / `removeMemory()` 直接读 `i.id`,
635
+ // 一个 null 就能让 forget/去重整段抛错。只保留对象,非数组形状按空处理。
636
+ // `files` / `fileMeta` 同理:taskbridge 的 `touchTaskFile()` 每读/写一个文件都会读它们,
637
+ // 缺一个集合就等于这个任务的热点追踪从第一次工具调用起永久失效。
638
+ for (const task of this.tasks) {
639
+ if (Array.isArray(task.insights)) task.insights = task.insights.filter(isRecord)
640
+ else if (task.insights !== undefined) task.insights = []
641
+ if (Array.isArray(task.files)) task.files = task.files.filter((f) => typeof f === 'string' && f)
642
+ else task.files = []
643
+ if (!isRecord(task.fileMeta)) task.fileMeta = {}
644
+ }
645
+ const bindingDoc = this._loadJson(path.join(this.dir, BINDING_FILE), {})
646
+ this.binding = isRecord(bindingDoc) ? bindingDoc : {}
647
+ const watchDoc = this._loadJson(path.join(this.dir, WATCH_FILE), [])
648
+ const rawWatch = Array.isArray(watchDoc) ? watchDoc.filter((r) => typeof r === 'string' && r) : []
649
+ // 老版本可能把同一个物理目录按不同大小写写了两条(Windows/macOS 大小写不敏感):
650
+ // 加载时归一,加载后下一次 save 顺手把 watch.json 也治好。
651
+ this.watchlist = dedupeWatchRoots(rawWatch)
652
+ if (this.watchlist.length !== rawWatch.length) this._dirtyWatch = true
653
+ if (watchDoc !== null && !Array.isArray(watchDoc)) {
654
+ console.error(`[dsh-project-memory] ${WATCH_FILE} is not an array; starting with no watch roots`)
655
+ }
595
656
  // 这四个集合的内容刚刚被换掉,让 auxCharsOf/精确估算重算(而不是沿用上一份实例的账)。
596
657
  this._auxVersion++
597
658
  this._formatWritten = existsSafe(path.join(this.dir, FORMAT_FILE))
@@ -637,51 +698,80 @@ export class ProjectMemoryStore {
637
698
  console.error(`[dsh-project-memory] ${EXPERIENCE_FILE} is not an array; importing nothing (file kept as-is)`)
638
699
  return
639
700
  }
640
- let imported = 0
641
- // 只有值得写的输入(`migratedAt` 为空 + 旧文件在或有旧条目)才导入:否则 `load()` 会在空目录里
642
- // mkdir + 写 insights.json,让调用方"目录已存在/有内容"的判断失真(容器目录被当成项目根)。
643
- if (!this.insights.migratedAt && (legacyOnDisk || legacy.length > 0)) {
644
- const now = new Date().toISOString()
645
- const known = new Set(this.insights.items.map((it) => it.id))
646
- for (const item of legacy) {
647
- if (!item || !item.problem || known.has(item.id)) continue
648
- known.add(item.id)
649
- this.insights.items.push({
650
- id: item.id,
651
- kind: 'experience',
652
- scope: 'project',
653
- title: String(item.problem).slice(0, 120),
654
- problem: item.problem,
655
- solution: item.solution,
656
- files: item.sourceFile ? [item.sourceFile] : [],
657
- symbols: [],
658
- sourceTaskIds: [],
659
- source: 'migrate',
660
- confidence: 1,
661
- hitCount: 0,
662
- createdAt: item.createdAt || now,
663
- updatedAt: item.updatedAt || now,
664
- })
665
- imported++
701
+ // 已经迁移过、或没有可导入的输入:只负责把残留的旧文件归档,然后清空内存副本。
702
+ if (this.insights.migratedAt || (!legacyOnDisk && legacy.length === 0)) {
703
+ if (legacyOnDisk) {
704
+ try {
705
+ renameSync(legacyFile, `${legacyFile}.migrated`)
706
+ } catch (err) {
707
+ if (err?.code !== 'ENOENT') {
708
+ console.error(`[dsh-project-memory] could not archive ${EXPERIENCE_FILE}: ${err.message}`)
709
+ }
710
+ }
666
711
  }
667
- this.insights.migratedAt = now
668
- try {
712
+ this.experience = []
713
+ return
714
+ }
715
+ // 需要导入:整段"读 insights → 合并 → 写回 → 归档旧文件"必须放在跨进程目录锁里。
716
+ // 否则两个 dsh 同时升级同一个旧 store 时,后写的迁移会把另一个进程刚写入的 insight 覆盖掉。
717
+ const release = acquireDirLock(this.dir, { timeoutMs: 2000, ensureDir: false })
718
+ if (!release) {
719
+ // 保持 experience 原样,下一次 load() 再试;本次查询暂时看不到旧笔记,但不丢数据。
720
+ console.error(`[dsh-project-memory] ${EXPERIENCE_FILE} migration skipped: store is busy; will retry on next load`)
721
+ return
722
+ }
723
+ let imported = 0
724
+ try {
725
+ // 等锁期间另一个进程可能已经迁移完:以磁盘为准,绝不能用等锁前的旧快照覆盖它。
726
+ const insightsPath = path.join(this.dir, INSIGHTS_FILE)
727
+ const diskDoc = this._loadJson(insightsPath, null)
728
+ if (isRecord(diskDoc) && Array.isArray(diskDoc.items) && diskDoc.migratedAt) {
729
+ this.insights = { ...diskDoc, items: diskDoc.items.filter(isRecord) }
730
+ } else {
731
+ const now = new Date().toISOString()
732
+ const known = new Set(this.insights.items.map((it) => it.id))
733
+ for (const item of legacy) {
734
+ if (!item || !item.problem || known.has(item.id)) continue
735
+ known.add(item.id)
736
+ this.insights.items.push({
737
+ id: item.id,
738
+ kind: 'experience',
739
+ scope: 'project',
740
+ title: String(item.problem).slice(0, 120),
741
+ problem: item.problem,
742
+ solution: item.solution,
743
+ files: item.sourceFile ? [item.sourceFile] : [],
744
+ symbols: [],
745
+ sourceTaskIds: [],
746
+ source: 'migrate',
747
+ confidence: 1,
748
+ hitCount: 0,
749
+ createdAt: item.createdAt || now,
750
+ updatedAt: item.updatedAt || now,
751
+ })
752
+ imported++
753
+ }
754
+ this.insights.migratedAt = now
669
755
  mkdirSync(this.dir, { recursive: true })
670
- writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights, { ensureDir: false })
671
- } catch (err) {
672
- // 没写进 insights.json 就**不能**把旧文件收走:那会真的丢数据。
673
- console.error(`[dsh-project-memory] insights migration write failed, keeping ${EXPERIENCE_FILE}: ${err.message}`)
674
- return
756
+ writeJsonAtomic(insightsPath, this.insights, { ensureDir: false })
675
757
  }
676
- }
677
- if (legacyOnDisk) {
678
- try {
679
- renameSync(legacyFile, `${legacyFile}.migrated`)
680
- } catch (err) {
681
- console.error(`[dsh-project-memory] could not archive ${EXPERIENCE_FILE} (imported ${imported} note(s)): ${err.message}`)
758
+ if (legacyOnDisk) {
759
+ try {
760
+ renameSync(legacyFile, `${legacyFile}.migrated`)
761
+ } catch (err) {
762
+ // 另一个进程可能已经归档走了;ENOENT 不算失败。
763
+ if (err?.code !== 'ENOENT') {
764
+ console.error(`[dsh-project-memory] could not archive ${EXPERIENCE_FILE} (imported ${imported} note(s)): ${err.message}`)
765
+ }
766
+ }
682
767
  }
768
+ this.experience = []
769
+ } catch (err) {
770
+ // 没写进 insights.json 就**不能**把旧文件收走:那会真的丢数据。
771
+ console.error(`[dsh-project-memory] insights migration write failed, keeping ${EXPERIENCE_FILE}: ${err.message}`)
772
+ } finally {
773
+ release()
683
774
  }
684
- this.experience = []
685
775
  }
686
776
 
687
777
  insightsDoc() {
@@ -851,8 +941,7 @@ export class ProjectMemoryStore {
851
941
  this._scheduleSaveRetry()
852
942
  return false
853
943
  }
854
- let wroteInsights = false
855
- let wroteTasks = false
944
+ let removalFailed = false
856
945
  try {
857
946
  // 先合并另一进程已落盘的小文档,再写;分片按“加载时 hash”做冲突检测。
858
947
  this._mergeAuxFromDisk()
@@ -903,27 +992,40 @@ export class ProjectMemoryStore {
903
992
  // 删除与另一进程的更新撞车:没有删除时间戳可比,保守采用对方版本,让内存与磁盘一致。
904
993
  this._adoptDiskShard(rel, disk)
905
994
  this._warnConflict(rel)
995
+ this._removedShards.delete(rel)
906
996
  continue
907
997
  }
908
998
  try {
909
- unlinkSync(shardRelPath(this.dir, rel))
910
- } catch {
911
- // shard file already gone; nothing to do
999
+ // 删除也要对 Windows 瞬时占用重试;失败时**保留删除意图**,否则下一次 load 会把
1000
+ // 这个 shard 里的旧条目复活(`unlinkSync` 的 EPERM 曾经被 catch 成"已经没了")。
1001
+ unlinkWithRetry(shardRelPath(this.dir, rel))
1002
+ } catch (err) {
1003
+ if (err?.code !== 'ENOENT') {
1004
+ removalFailed = true
1005
+ console.error(
1006
+ `[dsh-project-memory] could not delete shard for ${rel}: ${err?.message || err}; will retry`,
1007
+ )
1008
+ continue
1009
+ }
912
1010
  }
1011
+ this._removedShards.delete(rel)
913
1012
  this._baseFileSha.delete(rel)
914
1013
  }
915
- this._removedShards.clear()
916
- wroteInsights = this._dirtyInsights
917
- wroteTasks = this._dirtyTasks
918
- if (wroteInsights) {
1014
+ if (this._dirtyInsights) {
919
1015
  // v2 → v3 是纯语义升级,形状不变;老版本读到 v3 仍按 v2 字段解析。
920
1016
  if (this.insights && this.insights.version !== 3) this.insights.version = 3
921
1017
  writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights, { ensureDir: false })
922
1018
  this._dirtyInsights = false
1019
+ // 合并基线在**这一份写成功后**就推进:后面的 binding/watch 写失败时,
1020
+ // 不能让 insights 的基线停在旧水位,否则下一次删除新建条目可能算不出墓碑。
1021
+ this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
1022
+ this._createdInsightIds.clear()
923
1023
  }
924
1024
  if (this._dirtyTasks) {
925
1025
  writeJsonAtomic(path.join(this.dir, TASKS_FILE), this.tasks, { ensureDir: false })
926
1026
  this._dirtyTasks = false
1027
+ this._createdTaskIds.clear()
1028
+ this._resetTaskInsightBases()
927
1029
  }
928
1030
  if (this._dirtyBinding) {
929
1031
  writeJsonAtomic(path.join(this.dir, BINDING_FILE), this.binding, { ensureDir: false })
@@ -941,20 +1043,17 @@ export class ProjectMemoryStore {
941
1043
  } finally {
942
1044
  release()
943
1045
  }
944
- this._saveRetryAttempts = 0
945
- this.lastSaveOk = true
946
- untrackDirty(this)
947
- // 落盘成功才推进基线:失败时保持"本进程新建"的标记,下一次 save 仍要补写。
948
- if (wroteInsights) {
949
- this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
950
- this._createdInsightIds.clear()
951
- }
952
- if (wroteTasks) {
953
- // 只有真的落盘成功才推进任务条目的合并基线;失败时保留旧基线,重试仍能识别本地新增/删除。
954
- this._createdTaskIds.clear()
955
- this._resetTaskInsightBases()
1046
+ if (removalFailed) {
1047
+ // 其它文件已经写成功,只是删除没做完:保持脏、留给后台/退出 flush 重试,并如实返回 false。
1048
+ this.lastSaveOk = false
1049
+ trackDirty(this)
1050
+ this._scheduleSaveRetry()
1051
+ } else {
1052
+ this._saveRetryAttempts = 0
1053
+ this.lastSaveOk = true
1054
+ untrackDirty(this)
956
1055
  }
957
- return true
1056
+ return !removalFailed
958
1057
  }
959
1058
 
960
1059
  /**
@@ -1100,9 +1199,10 @@ export class ProjectMemoryStore {
1100
1199
  if (this._dirtyWatch) {
1101
1200
  const disk = this._loadJson(path.join(this.dir, WATCH_FILE), [])
1102
1201
  if (Array.isArray(disk)) {
1103
- const set = new Set([...disk, ...this.watchlist])
1104
- for (const root of this._removedWatch) set.delete(root)
1105
- this.watchlist = [...set]
1202
+ // 跨进程合并也按归一键去重:另一进程可能写了同一目录的另一种大小写。
1203
+ const merged = dedupeWatchRoots([...disk, ...this.watchlist])
1204
+ .filter((r) => !this._removedWatch.has(storeKey(r)))
1205
+ this.watchlist = merged
1106
1206
  this._auxVersion++
1107
1207
  }
1108
1208
  }
@@ -1140,10 +1240,13 @@ export class ProjectMemoryStore {
1140
1240
  }
1141
1241
 
1142
1242
  addWatch(root) {
1143
- if (!this.watchlist.includes(root)) {
1243
+ // 大小写不同的同一目录视为同一条:否则 `watch_repo` 传入不同大小写就登记两次,
1244
+ // 每轮扫两遍;`removeWatch` 还会漏掉另一条,重启后它又复活。
1245
+ const key = storeKey(root)
1246
+ if (!this.watchlist.some((r) => storeKey(r) === key)) {
1144
1247
  this.watchlist.push(root)
1145
1248
  this._dirtyWatch = true
1146
- this._removedWatch.delete(root)
1249
+ this._removedWatch.delete(key)
1147
1250
  this._auxVersion++
1148
1251
  return true
1149
1252
  }
@@ -1151,10 +1254,12 @@ export class ProjectMemoryStore {
1151
1254
  }
1152
1255
 
1153
1256
  removeWatch(root) {
1257
+ const key = storeKey(root)
1154
1258
  const before = this.watchlist.length
1155
- this.watchlist = this.watchlist.filter((r) => r !== root)
1259
+ this.watchlist = this.watchlist.filter((r) => storeKey(r) !== key)
1156
1260
  if (this.watchlist.length !== before) {
1157
- this._removedWatch.add(root)
1261
+ // 墓碑按归一键记:磁盘上那条可能是另一种大小写的写法。
1262
+ this._removedWatch.add(key)
1158
1263
  this._dirtyWatch = true
1159
1264
  this._auxVersion++
1160
1265
  }
@@ -1255,7 +1360,7 @@ export class ProjectMemoryStore {
1255
1360
  stats() {
1256
1361
  return {
1257
1362
  files: Object.keys(this.files).length,
1258
- entries: this.allEntries().length,
1363
+ entries: countEntries(this),
1259
1364
  // 经验笔记 = insight 里 kind:'experience' 的那些(含从 v0.4 导入的)。project 级为准。
1260
1365
  experience: this.insights.items.filter((it) => it && it.kind === 'experience').length,
1261
1366
  tasks: this.tasks.length,
@@ -1391,16 +1496,23 @@ export class ProjectMemoryStore {
1391
1496
  */
1392
1497
  applyFileUpdate(relPath, { expectedHash, hash, entries, type, size, mtimeMs }) {
1393
1498
  if ((this.fileRecord(relPath)?.sha256 ?? null) !== (expectedHash ?? null)) return false
1499
+ const previous = this.fileRecord(relPath)
1394
1500
  const record = {
1395
1501
  sha256: hash,
1396
1502
  size,
1397
1503
  type,
1398
1504
  indexedAt: new Date().toISOString(),
1399
1505
  }
1506
+ // `explicit` 是"这个文件不在扫描清单里(gitignore / roots.exclude),但作者显式索引过"的
1507
+ // 唯一凭证:watch/lazy 重新索引它时必须保留,否则下一次 index_repo 的 unseen 清理会把它删掉。
1508
+ if (previous?.explicit) record.explicit = true
1400
1509
  // mtime 是**加速用的缓存**,不是事实:缺了只是退化成每次整读 + 哈希(老 store 的条目就没有)。
1401
1510
  if (typeof mtimeMs === 'number' && Number.isFinite(mtimeMs)) record.mtimeMs = mtimeMs
1402
- this.markFile(relPath, record)
1511
+ // 先写 entries 再写 files:`setEntries` 里 makeSearchText/内存分配可能抛(极端但存在)。
1512
+ // 顺序反过来的话,files 已指向新 hash、entries 还是旧的,下一次扫描会被 mtime/size 快路径
1513
+ // 当成"未变更"直接跳过,旧条目就永久留在库里。
1403
1514
  this.setEntries(relPath, entries)
1515
+ this.markFile(relPath, record)
1404
1516
  return true
1405
1517
  }
1406
1518
 
@@ -1437,7 +1549,7 @@ export function storeOverview(store) {
1437
1549
  }
1438
1550
  return {
1439
1551
  files: Object.keys(store.files).length,
1440
- entries: store.allEntries().length,
1552
+ entries: countEntries(store),
1441
1553
  // 不调 store.stats():overview 也会被喂裸桩(测试/子索引汇总),少一个必需方法就少一处崩点。
1442
1554
  experience: Array.isArray(store.insights?.items) ? store.insights.items.filter((it) => it && it.kind === 'experience').length : 0,
1443
1555
  latest,
@@ -1,7 +1,7 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import path from 'node:path'
3
3
  import { statSync } from 'node:fs'
4
- import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
4
+ import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
5
5
  import { buildDocEntries } from '../doc-pipeline.js'
6
6
  import { docEntriesNeedBackfill } from '../doc-index.js'
7
7
  import { ProjectMemoryStore } from '../store.js'
@@ -39,7 +39,8 @@ export function indexDocTool(ctx, config) {
39
39
  const explicit = args.root && args.root.trim() ? args.root : null
40
40
  let root
41
41
  if (explicit) {
42
- root = path.resolve(explicit)
42
+ // 相对 root 按会话当前工作目录解析(不是宿主进程 cwd)。
43
+ root = resolveIndexRoot(exec, explicit)
43
44
  assertIndexRoot(root, explicit)
44
45
  assertSafeRoot(root, { requested: explicit, config })
45
46
  } else {
@@ -54,10 +55,19 @@ export function indexDocTool(ctx, config) {
54
55
  }
55
56
  }
56
57
  const memoryDir = memoryRootFor(root, config.memoryDir)
58
+ // root 可以是显式传入的。文件必须真的在 root 之内:否则 rel 会变成 `../x`,引用路径
59
+ // 逃出项目根,下一次扫描也不可能再见到它(既不会被清理,也没法按项目相对路径引用)。
60
+ const relRaw = path.relative(root, filePath)
61
+ if (!relRaw || relRaw === '..' || relRaw.startsWith(`..${path.sep}`) || path.isAbsolute(relRaw)) {
62
+ return (
63
+ `Not indexed: ${filePath} is outside the index root ${root}. ` +
64
+ 'Pass the document\'s own project root (or omit root to detect it from the document path).'
65
+ )
66
+ }
57
67
 
58
68
  const store = new ProjectMemoryStore(memoryDir).load()
59
69
 
60
- const rel = storeKey(path.relative(root, filePath).split(path.sep).join('/'))
70
+ const rel = storeKey(relRaw.split(path.sep).join('/'))
61
71
  // mtime 必须在读正文之前取:记录里的 mtime 不能比内容新,否则懒索引的快路径会跳过之后的真实改动。
62
72
  let mtimeMs
63
73
  try {