@yolk_vat-y/dsh-project-memory 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +0 -0
  3. package/README.md +9 -9
  4. package/README.zh-CN.md +8 -8
  5. package/client/client.js +139 -43
  6. package/client/client.js.map +1 -1
  7. package/cordis.patch.yml +0 -0
  8. package/package.json +2 -2
  9. package/scripts/bench-edits.mjs +0 -0
  10. package/scripts/bench-store.mjs +0 -0
  11. package/skills/project-memory/SKILL.md +38 -10
  12. package/src/audit.js +2 -2
  13. package/src/auto-inject.js +10 -5
  14. package/src/client/MemoryView.tsx +5 -14
  15. package/src/client/TaskComponents.tsx +109 -99
  16. package/src/client/TaskPanel.module.css +10 -4
  17. package/src/client/TaskPanel.tsx +49 -2
  18. package/src/client/locales.ts +2 -0
  19. package/src/client/task-data-store.ts +2 -0
  20. package/src/client/task-window.js +33 -0
  21. package/src/commands/insight-actions.js +43 -41
  22. package/src/commands/task-actions.js +42 -21
  23. package/src/commands/tasks.js +24 -10
  24. package/src/index-pipeline.js +5 -3
  25. package/src/inject-visible.js +16 -18
  26. package/src/insight-store.js +90 -72
  27. package/src/readiness.js +2 -2
  28. package/src/setup/taskbridge.js +51 -5
  29. package/src/setup/team-task.js +220 -0
  30. package/src/store.js +105 -82
  31. package/src/symbols.js +0 -0
  32. package/src/tools/forget.js +9 -1
  33. package/src/tools/index-doc.js +37 -41
  34. package/src/tools/lesson-tools.js +119 -22
  35. package/src/tools/query-memory.js +115 -14
  36. package/src/tools/task-tools.js +83 -16
  37. package/src/util/fs.js +57 -17
  38. package/src/util/hash.js +12 -0
  39. package/src/util/insight-fields.js +56 -1
  40. package/src/util/merge-by-id.js +56 -0
  41. package/src/util/persist.js +2 -1
  42. package/src/util/session-cache.js +4 -3
  43. package/src/util/task-view.js +18 -0
  44. package/src/vector-index.js +6 -5
  45. package/src/watch.js +4 -2
package/src/store.js CHANGED
@@ -2,11 +2,12 @@ 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, ensureSelfIgnoreDir, storeKey, unlinkWithRetry, writeJsonAtomic } from './util/fs.js'
5
+ import { acquireDirLock, ensureSelfIgnoreDir, readJsonFile, storeKey, unlinkWithRetry, writeJsonAtomic } from './util/fs.js'
6
6
  import { debugPersistence } from './util/persist.js'
7
7
  import { trackDirty, untrackDirty } from './util/flush.js'
8
8
  import { backfillDerivedTriggers } from './readiness.js'
9
- import { isRecord, newerIso } from './util/value.js'
9
+ import { isRecord, isoMs, newerIso } from './util/value.js'
10
+ import { mergeById } from './util/merge-by-id.js'
10
11
 
11
12
  const FORMAT_FILE = 'format.json'
12
13
  const INDEX_FILE = 'index.json'
@@ -19,6 +20,12 @@ const INSIGHTS_FILE = 'insights.json'
19
20
  const SHARDS_DIR = 'shards'
20
21
  /** ≤0.5.10 的 TS 增强结果缓存目录;0.5.11 起废弃并自愈清理。 */
21
22
  const LEGACY_TYPE_CACHE_DIR = 'type-cache'
23
+ /**
24
+ * 空团队锚点的回收期。团队锚点镜像宿主任务,但"空壳"(没有任何任务级记忆)只是写入被
25
+ * 去重/提升后留下的残迹:宿主的删除事件不一定能到达每个进程(lead 离线、团队插件卸载),
26
+ * 超过这个时间、没有绑定、也没有记忆,就回收;有记忆的锚点一律保留(那是知识,不是镜像垃圾)。
27
+ */
28
+ const STALE_TEAM_ANCHOR_MS = 30 * 24 * 60 * 60 * 1000
22
29
 
23
30
  const storeCache = new Map()
24
31
  /**
@@ -242,15 +249,6 @@ export function _clearStoreCacheForTest() {
242
249
  /** 已就"无法迁移的旧 store"告警过的目录:避免每次 load() 都刷一行。 */
243
250
  const migrationWarned = new Set()
244
251
 
245
- /**
246
- * 合并同一任务在两份快照里的 `insights`:以**上次落盘的 id 基线**做三方判断,基线没有、
247
- * 本地有 → 本地新增;基线有、本地没有 → 本地删除(不复活);两边都有 → `updatedAt` 新者胜。
248
- * 不能只按任务 `updatedAt` 选一侧:任务条目写入不 bump 任务时间戳,会整段覆盖另一边。
249
- * @param {object} local
250
- * @param {object} disk
251
- * @param {Set<string>} base
252
- * @returns {object[]}
253
- */
254
252
  /**
255
253
  * 跨进程任务合并时的文件热点并集:两侧各自累加计数,整条任务二选一会把另一侧新增的文件静默回滚。
256
254
  * 计数取 max(同一文件两边各加一次时无法区分重试与真实两次,宁可少记不可回滚),时间取最新。
@@ -299,25 +297,27 @@ function mergeTaskFileState(a, b) {
299
297
  return { files, fileMeta: trimmed }
300
298
  }
301
299
 
300
+ /**
301
+ * 合并同一任务在两份快照里的 `insights`:以**上次落盘的 id 基线**做三方判断,基线没有、
302
+ * 本地有 → 本地新增;基线有、本地没有 → 本地删除(不复活);两边都有 → `updatedAt` 新者胜。
303
+ * 不能只按任务 `updatedAt` 选一侧:任务条目写入不 bump 任务时间戳,会整段覆盖另一边。
304
+ * @param {object} local
305
+ * @param {object} disk
306
+ * @param {Set<string>} base
307
+ * @returns {object[]}
308
+ */
302
309
  function mergeTaskInsights(local, disk, base) {
303
- const merged = new Map()
304
- for (const ins of Array.isArray(disk?.insights) ? disk.insights : []) {
305
- if (ins?.id) merged.set(ins.id, ins)
306
- }
307
- const localById = new Map()
308
- for (const ins of Array.isArray(local?.insights) ? local.insights : []) {
309
- if (ins?.id) localById.set(ins.id, ins)
310
- }
311
- for (const id of base) if (!localById.has(id)) merged.delete(id)
312
- for (const [id, ins] of localById) {
313
- const prev = merged.get(id)
314
- if (!prev) {
315
- if (!base.has(id)) merged.set(id, ins)
316
- continue
317
- }
318
- if (newerIso(ins.updatedAt, prev.updatedAt) >= 0) merged.set(id, ins)
319
- }
320
- return [...merged.values()]
310
+ const localItems = Array.isArray(local?.insights) ? local.insights : []
311
+ // 三方判断折成两份 id 集合交给 mergeById:基线有、本地没有 = 本地删了(墓碑);
312
+ // 本地有、基线没有 = 本次新建(磁盘缺失时允许补写);两边都有时按 updatedAt 取新。
313
+ const localIds = new Set(localItems.map((it) => it?.id).filter(Boolean))
314
+ const baseIds = base || new Set()
315
+ return mergeById({
316
+ diskItems: Array.isArray(disk?.insights) ? disk.insights : [],
317
+ localItems,
318
+ deletedIds: new Set([...baseIds].filter((id) => !localIds.has(id))),
319
+ createdIds: new Set([...localIds].filter((id) => !baseIds.has(id))),
320
+ }) || []
321
321
  }
322
322
 
323
323
  /**
@@ -370,32 +370,17 @@ export function _stripPersistedDerivedForTest(entry) {
370
370
  return withoutPersistedDerived(entry)
371
371
  }
372
372
 
373
+ // 读盘判据(ENOENT / 读失败 / 损坏隔离)只在 util/fs.js 的 readJsonFile 里定义一次;
374
+ // 这里只接本 store 的两件副作用:读错误进 `_readErrors`(触发只读降级)与读盘字符数计量。
373
375
  function loadJson(filePath, fallback, counter, errorSink) {
374
- let raw
375
- try {
376
- raw = readFileSync(filePath, 'utf8')
377
- } catch (err) {
378
- // ENOENT 才是“真的没有”;EACCES/EISDIR/EIO/EMFILE 是读失败,不能当成删除。
379
- if (err?.code !== 'ENOENT') {
376
+ return readJsonFile(filePath, fallback, {
377
+ onReadError: (err) => {
380
378
  errorSink?.add(filePath)
381
379
  debugPersistence(`[dsh-project-memory] cannot read ${filePath}: ${err?.code || err?.message || err}`)
382
- }
383
- return fallback
384
- }
385
- // 累计读盘文本字符数,只供 `residentBoundBytes` 判断要不要精确计量。
386
- if (counter) counter.chars += raw.length
387
- try {
388
- return JSON.parse(raw)
389
- } catch {
390
- const backup = `${filePath}.${Date.now()}.corrupt`
391
- try {
392
- renameSync(filePath, backup)
393
- console.error(`[dsh-project-memory] corrupted ${path.basename(filePath)} moved to ${path.basename(backup)}; starting fresh`)
394
- } catch (err) {
395
- console.error(`[dsh-project-memory] corrupted ${path.basename(filePath)} could not be backed up: ${err.message}`)
396
- }
397
- return fallback
398
- }
380
+ },
381
+ // 只供 `residentBoundBytes` 判断要不要精确计量。
382
+ onChars: (chars) => { if (counter) counter.chars += chars },
383
+ })
399
384
  }
400
385
 
401
386
  function shardRelPath(dir, rel) {
@@ -506,6 +491,8 @@ export class ProjectMemoryStore {
506
491
  */
507
492
  this._createdInsightIds = new Set()
508
493
  this._createdTaskIds = new Set()
494
+ /** 待回收的过期空团队锚点:只在写盘合并后确认"另一进程也没写过"才移除(见 _pruneStaleTeamAnchors)。 */
495
+ this._staleAnchorIds = new Set()
509
496
  /** 上一次 save 是否真的落到盘上(锁竞争/权限失败时为 false)。 */
510
497
  this.lastSaveOk = true
511
498
  /** `shards/` 的 `.tmp` 清扫节流:NTFS 上 readdir(数千分片) 不便宜,不能每次 save 都扫。 */
@@ -782,8 +769,8 @@ export class ProjectMemoryStore {
782
769
  // 迁移崩溃窗口里同一 rel 可能同时出现在旧分片与新桶:取 indexedAt 更新的一份;
783
770
  // 时间相同优先 v3 桶(新布局)。
784
771
  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
772
+ const prevAt = prev ? isoMs(prev.indexedAt) : -1
773
+ const nextAt = isoMs(item.record.indexedAt)
787
774
  if (prev && prevAt > nextAt) continue
788
775
  if (prev && prevAt === nextAt && !isBucket && sourceRank.get(item.relPath) === 1) continue
789
776
  sourceRank.set(item.relPath, isBucket ? 1 : 0)
@@ -1390,7 +1377,7 @@ export class ProjectMemoryStore {
1390
1377
  const isBucket = Array.isArray(doc.items)
1391
1378
  for (const item of isBucket ? doc.items : [doc]) {
1392
1379
  if (!item || typeof item.relPath !== 'string' || !isRecord(item.record)) continue
1393
- const at = Date.parse(item.record.indexedAt || '') || 0
1380
+ const at = isoMs(item.record.indexedAt)
1394
1381
  const prev = disk.get(item.relPath)
1395
1382
  // 同 rel 多副本(崩溃/降级):时间新者胜;同时间优先 v3 桶。
1396
1383
  if (!prev || at > prev.at || (at === prev.at && isBucket && !prev.bucket)) {
@@ -1413,7 +1400,7 @@ export class ProjectMemoryStore {
1413
1400
  if (!local) continue
1414
1401
  const localSha = local.sha256 ?? null
1415
1402
  if (entry.sha === base || entry.sha === localSha) continue
1416
- const localAt = Date.parse(local.indexedAt || '') || 0
1403
+ const localAt = isoMs(local.indexedAt)
1417
1404
  if (localAt > entry.at) continue
1418
1405
  this._adoptBucketItem(rel, entry.item)
1419
1406
  this._dirtyShards.delete(rel)
@@ -1425,7 +1412,7 @@ export class ProjectMemoryStore {
1425
1412
  continue
1426
1413
  }
1427
1414
  if (entry.sha === base) continue
1428
- const localAt = Date.parse(this.files[rel].indexedAt || '') || 0
1415
+ const localAt = isoMs(this.files[rel].indexedAt)
1429
1416
  if (entry.at >= localAt) this._adoptBucketItem(rel, entry.item)
1430
1417
  }
1431
1418
  // 另一进程已删除、本地未删除且不是本进程新建的文件:从内存移除,避免 rewrite 复活。
@@ -1573,8 +1560,8 @@ export class ProjectMemoryStore {
1573
1560
  const nextSha = local.sha256 ?? null
1574
1561
  const diskSha = diskItem?.record?.sha256 ?? null
1575
1562
  if (diskItem && diskSha !== base && diskSha !== nextSha) {
1576
- const localAt = Date.parse(local.indexedAt || '') || 0
1577
- const diskAt = Date.parse(diskItem.record?.indexedAt || '') || 0
1563
+ const localAt = isoMs(local.indexedAt)
1564
+ const diskAt = isoMs(diskItem.record?.indexedAt)
1578
1565
  if (localAt <= diskAt) {
1579
1566
  this._adoptBucketItem(rel, diskItem)
1580
1567
  this._warnConflict(rel)
@@ -1655,25 +1642,14 @@ export class ProjectMemoryStore {
1655
1642
  for (const id of this._baseInsightIds) if (!current.has(id)) this._deletedInsightIds.add(id)
1656
1643
  for (const id of current) this._deletedInsightIds.delete(id)
1657
1644
  const disk = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
1658
- if (isRecord(disk) && Array.isArray(disk.items)) {
1659
- const byId = new Map()
1660
- for (const it of disk.items) if (isRecord(it) && it.id) byId.set(it.id, it)
1661
- for (const it of this.insights.items) {
1662
- if (!isRecord(it) || !it.id) continue
1663
- if (this._deletedInsightIds.has(it.id)) {
1664
- byId.delete(it.id)
1665
- continue
1666
- }
1667
- const prev = byId.get(it.id)
1668
- if (!prev) {
1669
- // 磁盘没有:本进程新建的才补写;否则是**对方删了**,丢掉内存里的旧副本。
1670
- if (this._createdInsightIds.has(it.id)) byId.set(it.id, it)
1671
- continue
1672
- }
1673
- if (newerIso(it.updatedAt, prev.updatedAt) >= 0) byId.set(it.id, it)
1674
- }
1675
- for (const id of this._deletedInsightIds) byId.delete(id)
1676
- this.insights = { ...this.insights, items: [...byId.values()] }
1645
+ const merged = mergeById({
1646
+ diskItems: isRecord(disk) && Array.isArray(disk.items) ? disk.items : null,
1647
+ localItems: this.insights.items,
1648
+ deletedIds: this._deletedInsightIds,
1649
+ createdIds: this._createdInsightIds,
1650
+ })
1651
+ if (merged) {
1652
+ this.insights = { ...this.insights, items: merged }
1677
1653
  this._baseInsightIds = new Set(this.insights.items.map((it) => it?.id).filter(Boolean))
1678
1654
  this._auxVersion++
1679
1655
  }
@@ -1689,6 +1665,19 @@ export class ProjectMemoryStore {
1689
1665
  continue
1690
1666
  }
1691
1667
  const prev = byId.get(t.id)
1668
+ if (this._staleAnchorIds.has(t.id)) {
1669
+ this._staleAnchorIds.delete(t.id)
1670
+ // 按**合并后**的条目决定:另一进程可能刚给这条锚点写了记忆,不能跟着空壳一起删。
1671
+ const mergedInsights = prev
1672
+ ? mergeTaskInsights(t, prev, this._baseTaskInsightIds.get(t.id) || new Set())
1673
+ : (Array.isArray(t.insights) ? t.insights : [])
1674
+ if (mergedInsights.length === 0) {
1675
+ byId.delete(t.id)
1676
+ this._deletedTaskIds.add(t.id)
1677
+ this._createdTaskIds.delete(t.id)
1678
+ continue
1679
+ }
1680
+ }
1692
1681
  if (!prev) {
1693
1682
  // 同 insights:磁盘缺失 = 对方删了,只有本进程新建的任务才补写。
1694
1683
  if (this._createdTaskIds.has(t.id)) byId.set(t.id, t)
@@ -1717,6 +1706,8 @@ export class ProjectMemoryStore {
1717
1706
  }
1718
1707
  // `removeTask` 已把它从内存数组移除,上面循环看不到;不在这里剔除会在同一次 save 里被写回。
1719
1708
  for (const id of this._deletedTaskIds) byId.delete(id)
1709
+ // 不在本地列表里的候选(已被删除/迁移)不再跟踪;下一轮 prune 会重新登记。
1710
+ this._staleAnchorIds.clear()
1720
1711
  this.tasks = [...byId.values()]
1721
1712
  this._auxVersion++
1722
1713
  }
@@ -2012,19 +2003,51 @@ export class ProjectMemoryStore {
2012
2003
  const fileCount = Object.keys(this.files).length
2013
2004
  const maxTasks = Math.min(100, Math.max(5, Math.floor(fileCount / 20)))
2014
2005
  const bound = new Set(Object.values(this.binding || {}))
2015
- const nonArchived = this.tasks.filter((t) => !t.archived && !bound.has(t.id))
2016
- if (nonArchived.length <= maxTasks) return 0
2006
+ // 团队锚点是宿主任务的镜像,生命周期由宿主(team/task 快照)管:本地容量 GC 不该把它归档,
2007
+ // 否则"按 id 直读、从不绑定"的锚点会在任务一多时静默失效,把绑定要求从后门放回来。
2008
+ // 空壳锚点另有过期回收(_pruneStaleTeamAnchors),不靠容量兜底。
2009
+ const nonArchived = this.tasks.filter((t) => !t.archived && !bound.has(t.id) && !t.teamTaskId)
2017
2010
  const ts = (t) => new Date(t.lastActiveAt || t.updatedAt || t.createdAt || 0).getTime()
2018
- const sorted = [...nonArchived].sort((a, b) => ts(a) - ts(b))
2019
- const toArchive = sorted.slice(0, nonArchived.length - maxTasks)
2011
+ const toArchive = nonArchived.length > maxTasks
2012
+ ? [...nonArchived].sort((a, b) => ts(a) - ts(b)).slice(0, nonArchived.length - maxTasks)
2013
+ : []
2020
2014
  for (const task of toArchive) {
2021
2015
  task.archived = true
2022
2016
  this._dirtyTasks = true
2023
2017
  }
2024
2018
  if (toArchive.length) this._auxVersion++
2019
+ this._pruneStaleTeamAnchors(bound)
2025
2020
  return toArchive.length
2026
2021
  }
2027
2022
 
2023
+ /**
2024
+ * 登记过期空团队锚点,等写盘合并时再回收。团队锚点镜像宿主任务,但没有任何任务级记忆的
2025
+ * 锚点只是写入被去重/提升后留下的残迹;宿主的删除事件不一定能到达每个进程(lead 离线、
2026
+ * 团队插件卸载、团队结束),没有本地回收就会永久留在 tasks.json 和面板里。
2027
+ *
2028
+ * 这里**只登记不删**:本地内存里的空不等于磁盘上也没人写过——另一进程可能刚给这条锚点
2029
+ * 存了记忆。真正移除在 `_mergeAuxFromDisk` 里按合并后的条目决定,避免把别人的写入一起删掉。
2030
+ * 有记忆、刚活动过、仍有会话绑定的锚点都不登记。
2031
+ * @param {Set<string>} bound - 仍有会话绑定的任务 id。
2032
+ * @returns {number} 本轮新登记的条数
2033
+ */
2034
+ _pruneStaleTeamAnchors(bound) {
2035
+ const now = Date.now()
2036
+ const stale = (t) => now - new Date(t.lastActiveAt || t.updatedAt || t.createdAt || 0).getTime() > STALE_TEAM_ANCHOR_MS
2037
+ let added = 0
2038
+ for (const t of this.tasks) {
2039
+ if (!t.teamTaskId || bound.has(t.id) || !stale(t)) continue
2040
+ // 形状异常(insights 不是数组)按"有内容"处理:宁可少回收,也不能把看不懂的数据删掉。
2041
+ if (!Array.isArray(t.insights) || t.insights.length) continue
2042
+ if (this._staleAnchorIds.has(t.id)) continue
2043
+ this._staleAnchorIds.add(t.id)
2044
+ added++
2045
+ }
2046
+ // 没有别的脏数据时 save() 会早退,合并逻辑就跑不到:标记一次脏,让这次 commit 真正落盘并回收。
2047
+ if (added) this._dirtyTasks = true
2048
+ return added
2049
+ }
2050
+
2028
2051
  /**
2029
2052
  * @param {(store: ProjectMemoryStore) => any} fn 变更函数
2030
2053
  * @param {{save?: boolean}} [options] save=false 时只标脏,由调用方在回合结束统一 flush
package/src/symbols.js CHANGED
File without changes
@@ -2,6 +2,7 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import { openProjectContext } from './context.js'
4
4
  import { DELETED_KEEP, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
5
+ import { taskVisibility } from '../setup/team-task.js'
5
6
  import { forgetVectorRows } from '../vector-index.js'
6
7
 
7
8
  /** 回报用的一行:`ins_xxx《标题》(project)`。标题已在 removeMemory 里截断。 */
@@ -46,7 +47,14 @@ export function forgetTool(config) {
46
47
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
47
48
  let res
48
49
  store.commit((s) => {
49
- res = removeMemory({ store: s, globalStore, idOrQuery: args.id_or_query, maxMatches: cfg.maxForgetMatches })
50
+ res = removeMemory({
51
+ store: s,
52
+ globalStore,
53
+ idOrQuery: args.id_or_query,
54
+ maxMatches: cfg.maxForgetMatches,
55
+ // 按 id / 关键词都不能删到本会话看不见的团队任务记忆(别队的私有条目)。
56
+ taskVisible: taskVisibility(exec),
57
+ })
50
58
  return res
51
59
  })
52
60
  globalStore.commit() // global 侧若被删过才落盘
@@ -1,11 +1,9 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { TEXT_OUTPUT, persistenceNote, rootParam } from './output.js'
3
3
  import path from 'node:path'
4
- import { existsSync, statSync } from 'node:fs'
5
- import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, sha256OfFile, storeKey } from '../util/fs.js'
6
- import { buildDocEntries } from '../doc-pipeline.js'
7
- import { docEntriesNeedBackfill } from '../doc-index.js'
8
- import { fileKind } from '../index-pipeline.js'
4
+ import { existsSync } from 'node:fs'
5
+ import { assertIndexRoot, assertReadableFile, assertSafeRoot, excludedEntryForPath, findProjectRoot, memoryRootFor, resolveIndexRoot, sessionMemoryRootOrNull, storeKey } from '../util/fs.js'
6
+ import { DROP, OVERSIZE, UNCHANGED, WRITE, fileKind, planFileIndex } from '../index-pipeline.js'
9
7
  import { ProjectMemoryStore } from '../store.js'
10
8
 
11
9
  export function indexDocTool(ctx, config) {
@@ -81,16 +79,16 @@ export function indexDocTool(ctx, config) {
81
79
  return `Not indexed: ${rel} — ${why}. The existing record was left untouched.`
82
80
  }
83
81
  const storeExists = existsSync(memoryDir)
82
+ const store = new ProjectMemoryStore(memoryDir).load()
84
83
 
85
84
  // 被排除 / 超大:旧版本留下的索引必须摘掉,否则 query_memory 会继续命中已删除的内容。
86
85
  // 但没有 store 时绝不能为了“清理”先建一个空 store(老契约:拒绝不产生副作用)。
87
86
  const dropStale = (reason) => {
88
87
  if (!storeExists) return reason
89
- const staleStore = new ProjectMemoryStore(memoryDir).load()
90
- return staleStore.commit((s) => {
88
+ return store.commit((s) => {
91
89
  s.removeFile(rel)
92
90
  return reason
93
- }) + persistenceNote(staleStore)
91
+ }) + persistenceNote(store)
94
92
  }
95
93
  if (excluded) {
96
94
  return dropStale(
@@ -98,40 +96,33 @@ export function indexDocTool(ctx, config) {
98
96
  `Removed stale index (if any). Remove that entry from \`config.roots.exclude\` under \`- id: project-memory\` if this file should be indexed.`,
99
97
  )
100
98
  }
101
- const sizeLimit = config.maxFileSizeMb
102
- if (sizeLimit) {
103
- let size = 0
104
- try { size = statSync(filePath).size } catch { size = 0 }
105
- if (size > sizeLimit * 1024 * 1024) {
106
- return dropStale(`Not indexed: ${rel} is now ${(size / 1024 / 1024).toFixed(1)} MB, over the ${sizeLimit} MB limit. Removed stale index (if any).`)
107
- }
108
- }
109
99
 
110
- const store = new ProjectMemoryStore(memoryDir).load()
111
- // mtime 必须在读正文之前取:记录里的 mtime 不能比内容新,否则懒索引的快路径会跳过之后的真实改动。
112
- let mtimeMs
113
- try {
114
- mtimeMs = statSync(filePath).mtimeMs
115
- } catch {
116
- mtimeMs = undefined
100
+ // 判重/回填/超限/抽条目全走 index-pipeline 的唯一实现:index_doc 只负责"怎么把结果说给用户"。
101
+ // `noMtimeFastPath`:显式索引必须按内容判重,不能被 mtime+size 快路径骗过去。
102
+ const plan = await planFileIndex({
103
+ rel,
104
+ filePath,
105
+ kind,
106
+ config,
107
+ record: store.fileRecord(rel),
108
+ existingEntries: store.entries[rel] || [],
109
+ noMtimeFastPath: true,
110
+ })
111
+
112
+ if (plan.key === OVERSIZE) {
113
+ const sizeLimit = config.maxFileSizeMb
114
+ const size = typeof plan.size === 'number' ? plan.size : 0
115
+ return dropStale(`Not indexed: ${rel} is now ${(size / 1024 / 1024).toFixed(1)} MB, over the ${sizeLimit} MB limit. Removed stale index (if any).`)
117
116
  }
118
- const { hash, size } = await sha256OfFile(filePath)
119
- const existing = store.fileRecord(rel)
120
- // 与 index_repo/watch/lazy 同一条判据:哈希未变但旧条目缺 terms 时仍要重抽一次(一次性回填)。
121
- // 少了这一步,terms 回填就是"路径相关"的——只有走 index_repo 才生效。
122
- if (existing && existing.sha256 === hash && !docEntriesNeedBackfill(store.entries[rel])) {
117
+
118
+ if (plan.key === UNCHANGED) {
119
+ const existing = store.fileRecord(rel)
123
120
  // 旧记录没有 explicit 时在这里补上:否则重新 index_doc 一次也救不回被扫描清理掉的文件。
124
- if (!existing.explicit) store.commit((s) => s.markFile(rel, { ...existing, explicit: true }))
121
+ if (existing && !existing.explicit) store.commit((s) => s.markFile(rel, { ...existing, explicit: true }))
125
122
  return `Skipped (unchanged): ${rel}\nAlready indexed with ${(store.entries[rel] || []).length} entry/entries.` + persistenceNote(store)
126
123
  }
127
124
 
128
- const entries = await buildDocEntries(rel, filePath, {
129
- chunkChars: config.chunkChars,
130
- maxChunks: config.maxChunksPerFile,
131
- maxFileSizeMb: config.maxFileSizeMb,
132
- maxPdfPages: config.maxPdfPages,
133
- })
134
- if (entries === null) {
125
+ if (plan.key === DROP) {
135
126
  const text = store.commit((s) => {
136
127
  s.removeFile(rel)
137
128
  return `Skipped: ${rel} looks like a reflection dump, not a document.`
@@ -139,17 +130,22 @@ export function indexDocTool(ctx, config) {
139
130
  return text + persistenceNote(store)
140
131
  }
141
132
 
133
+ if (plan.key !== WRITE) {
134
+ // UNSUPPORTED 已在上面用 fileKind 拦过;其余 key 出现即代码错误,宁可报错也不静默写脏记录。
135
+ throw new Error(`index_doc: unexpected plan key ${plan.key}`)
136
+ }
137
+
142
138
  return store.commit((s) => {
143
- s.setEntries(rel, entries)
139
+ s.setEntries(rel, plan.entries)
144
140
  // explicit:这个文件可能是被 .gitignore 排除的(显式索引不受 gitignore 限制),
145
141
  // 扫描清单里永远不会有它 —— 清理时靠这个标记区分"没扫到"与"被删了"。
146
- const record = { sha256: hash, size, type: 'doc', indexedAt: new Date().toISOString(), explicit: true }
147
- if (typeof mtimeMs === 'number' && Number.isFinite(mtimeMs)) record.mtimeMs = mtimeMs
142
+ const record = { sha256: plan.hash, size: plan.size, type: 'doc', indexedAt: new Date().toISOString(), explicit: true }
143
+ if (typeof plan.mtimeMs === 'number' && Number.isFinite(plan.mtimeMs)) record.mtimeMs = plan.mtimeMs
148
144
  s.markFile(rel, record)
149
- const preview = entries
145
+ const preview = plan.entries
150
146
  .map((e) => ` - ${e.title} @ ${rel}:${e.sourceLine}`)
151
147
  .join('\n')
152
- return `Indexed: ${rel}\nEntries: ${entries.length}\n${preview}`
148
+ return `Indexed: ${rel}\nEntries: ${plan.entries.length}\n${preview}`
153
149
  }) + persistenceNote(store)
154
150
  },
155
151
  })