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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.js CHANGED
@@ -2,7 +2,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,
@@ -1389,15 +1494,41 @@ export class ProjectMemoryStore {
1389
1494
  * (调用方让该条目保持未落快照,下一轮重试)。
1390
1495
  * 移除条目不经过这里:调用方在 commit 里直接 removeFile(见 index-pipeline.js)。
1391
1496
  */
1392
- applyFileUpdate(relPath, { expectedHash, hash, entries, type, size }) {
1497
+ applyFileUpdate(relPath, { expectedHash, hash, entries, type, size, mtimeMs }) {
1393
1498
  if ((this.fileRecord(relPath)?.sha256 ?? null) !== (expectedHash ?? null)) return false
1394
- this.markFile(relPath, {
1499
+ const previous = this.fileRecord(relPath)
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
1509
+ // mtime 是**加速用的缓存**,不是事实:缺了只是退化成每次整读 + 哈希(老 store 的条目就没有)。
1510
+ if (typeof mtimeMs === 'number' && Number.isFinite(mtimeMs)) record.mtimeMs = mtimeMs
1511
+ // 先写 entries 再写 files:`setEntries` 里 makeSearchText/内存分配可能抛(极端但存在)。
1512
+ // 顺序反过来的话,files 已指向新 hash、entries 还是旧的,下一次扫描会被 mtime/size 快路径
1513
+ // 当成"未变更"直接跳过,旧条目就永久留在库里。
1400
1514
  this.setEntries(relPath, entries)
1515
+ this.markFile(relPath, record)
1516
+ return true
1517
+ }
1518
+
1519
+ /**
1520
+ * 内容没变、只是 mtime 变了(touch / checkout / 还原)时把新 mtime 记回去。
1521
+ * 不记回去的话 `planFileIndex` 的快路径永远命不中,每次扫描都要重新整读一遍这个文件。
1522
+ * 只标脏、不立刻落盘:调用方本来就在一次扫描/一批里,等那一次 save 一起写。
1523
+ * @returns {boolean} 是否真的改了(用于测试与诊断)
1524
+ */
1525
+ refreshMtime(relPath, mtimeMs) {
1526
+ const rec = this.files[relPath]
1527
+ if (!rec || typeof mtimeMs !== 'number' || !Number.isFinite(mtimeMs)) return false
1528
+ if (rec.mtimeMs === mtimeMs) return false
1529
+ this.files[relPath] = { ...rec, mtimeMs }
1530
+ this._dirtyShards.add(relPath)
1531
+ this._removedShards.delete(relPath)
1401
1532
  return true
1402
1533
  }
1403
1534
  }
@@ -1418,7 +1549,7 @@ export function storeOverview(store) {
1418
1549
  }
1419
1550
  return {
1420
1551
  files: Object.keys(store.files).length,
1421
- entries: store.allEntries().length,
1552
+ entries: countEntries(store),
1422
1553
  // 不调 store.stats():overview 也会被喂裸桩(测试/子索引汇总),少一个必需方法就少一处崩点。
1423
1554
  experience: Array.isArray(store.insights?.items) ? store.insights.items.filter((it) => it && it.kind === 'experience').length : 0,
1424
1555
  latest,
@@ -1,6 +1,7 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import path from 'node:path'
3
- import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
3
+ import { statSync } from 'node:fs'
4
+ import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
4
5
  import { buildDocEntries } from '../doc-pipeline.js'
5
6
  import { docEntriesNeedBackfill } from '../doc-index.js'
6
7
  import { ProjectMemoryStore } from '../store.js'
@@ -38,7 +39,8 @@ export function indexDocTool(ctx, config) {
38
39
  const explicit = args.root && args.root.trim() ? args.root : null
39
40
  let root
40
41
  if (explicit) {
41
- root = path.resolve(explicit)
42
+ // 相对 root 按会话当前工作目录解析(不是宿主进程 cwd)。
43
+ root = resolveIndexRoot(exec, explicit)
42
44
  assertIndexRoot(root, explicit)
43
45
  assertSafeRoot(root, { requested: explicit, config })
44
46
  } else {
@@ -53,10 +55,26 @@ export function indexDocTool(ctx, config) {
53
55
  }
54
56
  }
55
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
+ }
56
67
 
57
68
  const store = new ProjectMemoryStore(memoryDir).load()
58
69
 
59
- const rel = storeKey(path.relative(root, filePath).split(path.sep).join('/'))
70
+ const rel = storeKey(relRaw.split(path.sep).join('/'))
71
+ // mtime 必须在读正文之前取:记录里的 mtime 不能比内容新,否则懒索引的快路径会跳过之后的真实改动。
72
+ let mtimeMs
73
+ try {
74
+ mtimeMs = statSync(filePath).mtimeMs
75
+ } catch {
76
+ mtimeMs = undefined
77
+ }
60
78
  const { hash, size } = await sha256OfFile(filePath)
61
79
  const existing = store.fileRecord(rel)
62
80
  // 与 index_repo/watch/lazy 同一条判据:哈希未变但旧条目缺 terms 时仍要重抽一次(一次性回填)。
@@ -84,7 +102,9 @@ export function indexDocTool(ctx, config) {
84
102
  s.setEntries(rel, entries)
85
103
  // explicit:这个文件可能是被 .gitignore 排除的(显式索引不受 gitignore 限制),
86
104
  // 扫描清单里永远不会有它 —— 清理时靠这个标记区分"没扫到"与"被删了"。
87
- s.markFile(rel, { sha256: hash, size, type: 'doc', indexedAt: new Date().toISOString(), explicit: true })
105
+ const record = { sha256: hash, size, type: 'doc', indexedAt: new Date().toISOString(), explicit: true }
106
+ if (typeof mtimeMs === 'number' && Number.isFinite(mtimeMs)) record.mtimeMs = mtimeMs
107
+ s.markFile(rel, record)
88
108
  const preview = entries
89
109
  .map((e) => ` - ${e.title} @ ${rel}:${e.sourceLine}`)
90
110
  .join('\n')
@@ -1,10 +1,11 @@
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, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey } from '../util/fs.js'
4
+ import { assertIndexRoot, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, resolveIndexRoot, scanLimits, storeKey } from '../util/fs.js'
5
5
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from '../index-pipeline.js'
6
6
  import { ProjectMemoryStore } from '../store.js'
7
7
  import { onFileIndexed, isTypeScriptFile, enhanceQueueStats } from '../enhancer.js'
8
+ import { listIndexFailures } from '../index-failures.js'
8
9
 
9
10
  /**
10
11
  * 每批提交的文件数。旧实现把整棵树的 updates 攒到最后一次性 commit:一次全量扫描的
@@ -50,10 +51,13 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
50
51
  if (!kind) continue
51
52
 
52
53
  try {
53
- const size = statSync(filePath).size
54
+ const st = statSync(filePath)
55
+ const size = st.size
54
56
  const record = store.fileRecord(rel)
55
- const plan = await planFileIndex({ rel, filePath, kind, config, record, existingEntries: store.entries[rel], size, force: reindex })
57
+ const plan = await planFileIndex({ rel, filePath, kind, config, record, existingEntries: store.entries[rel], size, mtimeMs: st.mtimeMs, force: reindex })
56
58
  if (plan.key === UNCHANGED) {
59
+ // 内容没变、mtime 变了(touch / checkout 还原):把新 mtime 记回去,下一次扫描才命得快路径。
60
+ if (typeof plan.mtimeMs === 'number') store.refreshMtime(rel, plan.mtimeMs)
57
61
  skipped++
58
62
  continue
59
63
  }
@@ -113,6 +117,13 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
113
117
  if (failures.length) {
114
118
  report += `\nfailed to index ${failures.length} file(s): ${failures.join(', ')}`
115
119
  }
120
+ // 后台(watch / 懒索引)的失败不在本次扫描里,但它们同样意味着"这些文件没进语料"。
121
+ // 过去只写日志,用户看不到;这里跟随本次结果一起报出来。
122
+ const background = listIndexFailures(root, 5)
123
+ if (background.count) {
124
+ const detail = background.items.map((i) => `${i.rel} — ${i.message.slice(0, 100)}`).join('; ')
125
+ report += `\n${background.count} file(s) failing in background indexing (watch / lazy): ${detail}`
126
+ }
116
127
 
117
128
  // Trigger TS enhancement for code files (TS/JS only), now that the base entries are on disk.
118
129
  const dropsBefore = enhanceQueueStats().dropped
@@ -139,7 +150,7 @@ export function indexRepoTool(ctx, config) {
139
150
  root: {
140
151
  type: 'string',
141
152
  required: true,
142
- description: '项目根(绝对路径)',
153
+ description: '项目根(相对路径按会话当前工作目录解析)',
143
154
  },
144
155
  reindex: {
145
156
  type: 'boolean',
@@ -150,8 +161,9 @@ export function indexRepoTool(ctx, config) {
150
161
  schema: { type: 'string' },
151
162
  render: (_args, value) => [{ type: 'text', text: value }],
152
163
  },
153
- async execute(args) {
154
- const root = path.resolve(args.root)
164
+ async execute(args, exec) {
165
+ // 相对 root 按会话当前工作目录解析(不是宿主进程 cwd)——见 util/fs.js 的 resolveIndexRoot。
166
+ const root = resolveIndexRoot(exec, args.root)
155
167
  // 透传原始入参:Windows 风格路径在 POSIX 上会被 resolve 成 <cwd>/D:\...,
156
168
  // 报错时要点明这是路径风格问题,而不是“目录被删了”。
157
169
  assertIndexRoot(root, args.root)
@@ -11,6 +11,7 @@ import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
11
11
  import { resolveLinkedSymbols } from '../link.js'
12
12
  import { truncate } from '../util/text.js'
13
13
  import { stepContent, stepStatus } from '../util/task-view.js'
14
+ import { cfgValue } from '../util/config.js'
14
15
  function toAbs(root, rel) {
15
16
  return path.isAbsolute(rel) ? rel : path.join(root, rel)
16
17
  }
@@ -101,7 +102,7 @@ export function queryMemoryTool(ctx, config) {
101
102
  const type = args.type || 'all'
102
103
  const limit = Math.max(1, Math.min(Number(args.limit) || 8, 20))
103
104
 
104
- const queries = config.llmQueryExpansion
105
+ const queries = cfgValue(config, 'llmQueryExpansion')
105
106
  ? await expandQuery(ctx.llm, args.query, config.expansionCount, { route: resolveRoute(exec, config) })
106
107
  : [args.query]
107
108
 
@@ -247,19 +248,30 @@ export function queryMemoryTool(ctx, config) {
247
248
  if (type === 'task') {
248
249
  const q = (queries[0] || '').toLowerCase()
249
250
  const matched = tasks
250
- .filter((t) => !t.archived && (t.title.toLowerCase().includes(q) || (t.steps || []).some((s) => stepContent(s).toLowerCase().includes(q)) || (t.files || []).some((f) => f.toLowerCase().includes(q))))
251
+ .filter((t) => {
252
+ const title = String(t.title || '').toLowerCase()
253
+ const steps = Array.isArray(t.steps) ? t.steps : []
254
+ const files = Array.isArray(t.files) ? t.files : []
255
+ return !t.archived && (
256
+ title.includes(q)
257
+ || steps.some((s) => stepContent(s).toLowerCase().includes(q))
258
+ || files.some((f) => String(f).toLowerCase().includes(q))
259
+ )
260
+ })
251
261
  .slice(0, limit)
252
262
  if (!matched.length) {
253
263
  return `任务记录: 0 套匹配 "${args.query}"(list_tasks 查看全部,select_task 续做)`
254
264
  }
255
265
  for (const t of matched) {
256
- const done = (t.steps || []).filter((s) => stepStatus(s) === 'completed').length
257
- const total = (t.steps || []).length
258
- const stepsText = (t.steps || []).length
259
- ? (t.steps || []).map((s) => `- [${stepStatus(s) === 'completed' ? 'x' : stepStatus(s) === 'in_progress' ? '*' : ' '}] ${stepContent(s)}`).join('\n')
266
+ const steps = Array.isArray(t.steps) ? t.steps : []
267
+ const files = Array.isArray(t.files) ? t.files : []
268
+ const done = steps.filter((s) => stepStatus(s) === 'completed').length
269
+ const total = steps.length
270
+ const stepsText = steps.length
271
+ ? steps.map((s) => `- [${stepStatus(s) === 'completed' ? 'x' : stepStatus(s) === 'in_progress' ? '*' : ' '}] ${stepContent(s)}`).join('\n')
260
272
  : '(无步骤)'
261
- const files = (t.files || []).slice(0, 8).join(', ')
262
- lines.push(`### ${t.title} (${done}/${total} 完成)\n${stepsText}\n- 文件: ${files || '无'}`)
273
+ const filesText = files.slice(0, 8).join(', ')
274
+ lines.push(`### ${t.title} (${done}/${total} 完成)\n${stepsText}\n- 文件: ${filesText || '无'}`)
263
275
  }
264
276
  return truncate(lines.join('\n\n'), config.maxOutputChars)
265
277
  }
@@ -5,6 +5,7 @@ import { cfgInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
5
5
  import { cfgEngine } from '../auto-inject.js'
6
6
  import { resolveVectorLayer, vectorIndexSummary, vectorItemsFrom } from '../vector-index.js'
7
7
  import { truncate } from '../util/text.js'
8
+ import { listIndexFailures } from '../index-failures.js'
8
9
 
9
10
  const TOP_N = 30
10
11
 
@@ -37,6 +38,13 @@ export function statsTool(config) {
37
38
  `Files indexed: ${overview.files} | Entries: ${overview.entries} | Experience notes: ${overview.experience}`,
38
39
  overview.latest ? `Last index: ${overview.latest}` : 'Last index: never',
39
40
  ]
41
+ // 后台索引失败(watch / 懒索引)过去只写日志:这里跟 store 状态一起报,避免
42
+ // "看着一切正常、实际有文件从没进过语料"。
43
+ const background = listIndexFailures(root, 3)
44
+ if (background.count) {
45
+ const detail = background.items.map((i) => `${i.rel} (${truncate(i.message, 60)})`).join('; ')
46
+ lines.push(`Index failures: ${background.count} file(s) — ${detail}`)
47
+ }
40
48
  if (files.length) {
41
49
  lines.push('')
42
50
  for (const [rel, rec] of files.slice(0, TOP_N)) {