@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/enhancer.js CHANGED
@@ -359,7 +359,7 @@ export function enqueueEnhance(store, relPath, filePath, priority = PRIORITY.BAT
359
359
  enhanceQueue.splice(existingIdx, 1)
360
360
  }
361
361
 
362
- const task = { store, relPath, filePath, priority, cacheKey, promise: null, resolve: null }
362
+ const task = { store, relPath, filePath, priority, cacheKey, promise: null, resolve: null, hadRecord: Boolean(store?.files?.[relPath]) }
363
363
  task.promise = new Promise((resolve) => { task.resolve = resolve })
364
364
 
365
365
  if (enhanceQueue.length >= enhanceQueueMax) {
@@ -421,7 +421,7 @@ async function runEnhance(task) {
421
421
  try {
422
422
  const enhanced = deepParseWithTS(task.filePath, content)
423
423
  if (enhanced?.length) {
424
- await task.store.commit(fn => applyEnhancedSymbols(fn, task.relPath, enhanced))
424
+ await task.store.commit(fn => applyEnhancedSymbols(fn, task.relPath, enhanced, { hadRecord: task.hadRecord }))
425
425
  }
426
426
  } catch (err) {
427
427
  console.warn(`[dsh-project-memory] enhance failed for ${task.relPath}: ${err.message}`)
@@ -452,7 +452,11 @@ function scheduleProcess() {
452
452
  processNext()
453
453
  }
454
454
 
455
- function applyEnhancedSymbols(fn, relPath, enhanced) {
455
+ function applyEnhancedSymbols(fn, relPath, enhanced, { hadRecord = false } = {}) {
456
+ // 入队时这个文件还有记录、轮到执行时却没了:说明它已被删除/移出索引。此时再 setEntries
457
+ // 会写下**没有 files 记录**的孤儿符号,unseen 清理看不到它(只遍历 files),查询却会一直命它。
458
+ // `hadRecord` 为 false 的调用(测试 / 直接对未索引文件增强)保持旧行为:从零建条目。
459
+ if (hadRecord && !fn.files[relPath]) return
456
460
  // Store entries in fn.entries[relPath], not fn.files[relPath].entries
457
461
  const existingEntries = fn.entries[relPath] || []
458
462
  const nameOf = e => (e.title || '').replace(/\s*\([^)]*\)\s*$/, '')
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 后台索引失败的进程内账本:只负责"把静默失败报出来",不落盘。
3
+ *
4
+ * watch 的失败过去只打一行日志,懒索引的单文件失败甚至整段吞掉(`catch {}`),于是
5
+ * "某些文件一直没进语料"没有任何可观察面。这里按根记住最近失败的 rel 与原因,
6
+ * 由 index_repo / memory_stats 一并报出。
7
+ *
8
+ * 不持久化是刻意的:watch 每轮都会重试,问题仍在时失败会重新登记;重启后立刻又能看见。
9
+ */
10
+
11
+ const MAX_PER_ROOT = 50
12
+ const byRoot = new Map()
13
+
14
+ export function recordIndexFailure(root, rel, message) {
15
+ let failures = byRoot.get(root)
16
+ if (!failures) {
17
+ failures = new Map()
18
+ byRoot.set(root, failures)
19
+ }
20
+ failures.set(rel, { message: message || 'index failed', at: Date.now() })
21
+ // 上限只防失控(一次坏掉上千个文件时别把内存吃掉);超出就丢最早登记的。
22
+ if (failures.size > MAX_PER_ROOT) failures.delete(failures.keys().next().value)
23
+ }
24
+
25
+ export function clearIndexFailure(root, rel) {
26
+ const failures = byRoot.get(root)
27
+ if (!failures) return
28
+ failures.delete(rel)
29
+ if (failures.size === 0) byRoot.delete(root)
30
+ }
31
+
32
+ /** 按最近失败时间倒序返回 `{ count, items }`;`items` 至多 limit 条。 */
33
+ export function listIndexFailures(root, limit = 5) {
34
+ const failures = byRoot.get(root)
35
+ if (!failures) return { count: 0, items: [] }
36
+ const items = [...failures.entries()]
37
+ .sort((a, b) => b[1].at - a[1].at)
38
+ .slice(0, Math.max(0, limit))
39
+ .map(([rel, value]) => ({ rel, message: value.message }))
40
+ return { count: failures.size, items }
41
+ }
42
+
43
+ /** 测试用:账本是模块级状态,用例之间要能清干净。 */
44
+ export function _resetIndexFailuresForTest() {
45
+ byRoot.clear()
46
+ }
@@ -42,21 +42,39 @@ function exceedsSizeCap(size, config) {
42
42
  * key 为 UNSUPPORTED / OVERSIZE / UNCHANGED / DROP / WRITE 之一。
43
43
  * @param {object} args
44
44
  * @param {number} [args.size] 调用方已 statSync 时传入,避免重复 stat。
45
+ * @param {number} [args.mtimeMs] 调用方已 statSync 时传入;与 `record.mtimeMs` 构成"未改"快路径。
45
46
  * @param {boolean} [args.force] index_repo 的 reindex:忽略哈希跳过。
46
47
  */
47
- export async function planFileIndex({ rel, filePath, kind, config, record, existingEntries = [], size, force = false }) {
48
+ export async function planFileIndex({ rel, filePath, kind, config, record, existingEntries = [], size, mtimeMs, force = false }) {
48
49
  if (!kind) return { key: UNSUPPORTED }
49
- const fileSize = typeof size === 'number' ? size : statSync(filePath).size
50
+ let fileSize = size
51
+ let fileMtime = mtimeMs
52
+ if (typeof fileSize !== 'number' || typeof fileMtime !== 'number') {
53
+ const st = statSync(filePath)
54
+ if (typeof fileSize !== 'number') fileSize = st.size
55
+ if (typeof fileMtime !== 'number') fileMtime = st.mtimeMs
56
+ }
50
57
  if (exceedsSizeCap(fileSize, config)) return { key: OVERSIZE }
51
58
 
52
- // 单次读盘:同一 buffer 供内容哈希与正文解码使用(未变更的文件不解码)。
53
- const { hash, buffer } = readFileForIndex(filePath)
54
59
  // 旧 store 的 doc 条目缺 terms → 即使哈希未变也重抽一次(一次性回填)。
55
60
  const backfill = kind === 'doc' && docEntriesNeedBackfill(existingEntries)
56
- if (!force && record && record.sha256 === hash && !backfill) return { key: UNCHANGED }
61
+ // 快路径:mtime + size 都没动就不读盘、不哈希。懒索引由 `fs/observed` 触发,重复读同一个
62
+ // 文件不该每次整读 + sha256。代价与 make/tsc 同一取舍(rsync -t 保留 mtime 的还原察觉不到,
63
+ // 需要时用 reindex: true 强制重读)。
64
+ if (!force && !backfill && record && typeof record.mtimeMs === 'number' && record.mtimeMs === fileMtime && record.size === fileSize) {
65
+ return { key: UNCHANGED }
66
+ }
67
+
68
+ // 单次读盘:同一 buffer 供内容哈希与正文解码使用(未变更的文件不解码)。
69
+ const { hash, buffer } = readFileForIndex(filePath)
70
+ if (!force && record && record.sha256 === hash && !backfill) {
71
+ // 内容没变但 mtime 变了(touch / checkout / 还原):把新 mtime 记回去,否则快路径永远命不中,
72
+ // 每次扫描都要重新整读这个文件。调用方负责 `refreshMtime`。
73
+ return record.mtimeMs === fileMtime ? { key: UNCHANGED } : { key: UNCHANGED, mtimeMs: fileMtime }
74
+ }
57
75
 
58
76
  if (kind === 'code') {
59
- return { key: WRITE, hash, size: fileSize, type: 'code', entries: scanSymbols(rel, filePath, buffer.toString('utf8')) }
77
+ return { key: WRITE, hash, size: fileSize, type: 'code', entries: scanSymbols(rel, filePath, buffer.toString('utf8')), mtimeMs: fileMtime }
60
78
  }
61
79
  // dump 判定在 buildDocEntries 内部(唯一真源):不可索引的文档返回 null。
62
80
  const entries = await buildDocEntries(rel, filePath, {
@@ -65,7 +83,7 @@ export async function planFileIndex({ rel, filePath, kind, config, record, exist
65
83
  maxFileSizeMb: config.maxFileSizeMb,
66
84
  maxPdfPages: config.maxPdfPages,
67
85
  })
68
- return entries === null ? { key: DROP } : { key: WRITE, hash, size: fileSize, type: 'doc', entries }
86
+ return entries === null ? { key: DROP } : { key: WRITE, hash, size: fileSize, type: 'doc', entries, mtimeMs: fileMtime }
69
87
  }
70
88
 
71
89
  /**
@@ -84,6 +102,7 @@ export function toFileUpdate(rel, plan, record) {
84
102
  size: plan.size,
85
103
  type: plan.type,
86
104
  entries: plan.entries,
105
+ mtimeMs: plan.mtimeMs,
87
106
  }
88
107
  }
89
108
 
package/src/index.js CHANGED
@@ -7,7 +7,7 @@ import { rememberTool } from './tools/remember.js'
7
7
  import { forgetTool } from './tools/forget.js'
8
8
  import { watchRepoTool } from './tools/watch-repo.js'
9
9
  import { statsTool } from './tools/stats.js'
10
- import { WatchManager } from './watch.js'
10
+ import { WatchManager, applyWatchSettings } from './watch.js'
11
11
  import { setupLazyIndexing } from './lazy.js'
12
12
  import { initTypeScript } from './enhancer.js'
13
13
  import { setupTaskbridge } from './setup/taskbridge.js'
@@ -18,6 +18,7 @@ import { rememberRoute } from './llm-route.js'
18
18
  import { workflowCommandDefinition } from './commands/workflow.js'
19
19
  import { setupSkill } from './skill.js'
20
20
  import { flushDirtyStores } from './util/flush.js'
21
+ import { cfgValue, changedConfigKeys, asVolatile } from './util/config.js'
21
22
 
22
23
  export const name = 'dsh-project-memory'
23
24
  export const inject = ['llm', 'tools']
@@ -32,7 +33,7 @@ export const Config = Schema.object({
32
33
  maxFileSizeMb: Schema.number().default(10),
33
34
  maxOutputChars: Schema.number().default(8000),
34
35
  maxPdfPages: Schema.number().default(1000),
35
- llmQueryExpansion: Schema.boolean().default(false),
36
+ llmQueryExpansion: asVolatile(Schema.boolean().default(false)),
36
37
  expansionCount: Schema.number().default(6),
37
38
  // 辅助 LLM 调用的路由覆写 —— **索引期零 LLM**,只服务召回期查询扩展与反思期。
38
39
  // 未设置时取当前会话 header 的 provider/model,后台路径取最近一次会话路由;都拿不到时
@@ -41,10 +42,16 @@ export const Config = Schema.object({
41
42
  provider: Schema.string(),
42
43
  model: Schema.string(),
43
44
  }).default({}),
45
+ // 以下三个键在 web 的插件页上有可视化设置(`plugins.bundle.config`,见 src/client/settings-card.tsx)。
46
+ // `.volatile()` 是宿主设置页的准入条件:只有 volatile 字段能经 settings 接口写入,且写入后**不重启**
47
+ // 插件、以 ref 形式原地更新。读取一律走 util/config.js 的 cfgValue()(ref 是对象,直接判真会读错)。
48
+ //
49
+ // 其余的键**刻意不标 volatile**:`lazyIndexing` / `watch` / `enableTypeScript` 关掉只会让记忆变旧,
50
+ // 不属于"用户偏好";它们仍可在 profile 里改,但不出现在卡片上(关掉监视等于放任索引过期)。
44
51
  lazyIndexing: Schema.boolean().default(true),
45
- autoIndexOnFirstUse: Schema.boolean().default(false),
52
+ autoIndexOnFirstUse: asVolatile(Schema.boolean().default(false)),
46
53
  watch: Schema.boolean().default(true),
47
- watchInterval: Schema.number().default(30),
54
+ watchInterval: asVolatile(Schema.number().default(30)),
48
55
  // 危险根护栏:家目录 / 文件系统根 / 系统目录 / 包管理器前缀(/opt/homebrew …)整体扫描会吃满
49
56
  // 内存,默认一律拒绝。`roots.*` 是配置档级例外表;`allowUnsafeRoots` 只放开内置名单,deny/exclude 仍优先。
50
57
  allowUnsafeRoots: Schema.boolean().default(false),
@@ -159,18 +166,34 @@ export function apply(ctx, config) {
159
166
  }
160
167
 
161
168
  const watchManager = new WatchManager(ctx, config)
162
- if (config.watch) {
163
- watchManager.restorePersisted()
164
- ctx.effect(() => {
165
- watchManager.start(config.watchInterval * 1000)
166
- return () => watchManager.stop()
167
- })
169
+ // watchInterval 是 volatile 字段:设置页改完要当场生效(重排定时器),而不是等下次启动。
170
+ // watch 本身不提供界面开关(关掉监视等于放任索引过期),但仍可在 profile 里设 false。
171
+ // 持久化的根清单只恢复一次;先关后开时补一次(否则"打开监视"要等到下次启动才真的开始轮询)。
172
+ let watchRestored = false
173
+ const syncWatch = () => {
174
+ if (cfgValue(config, 'watch') !== false && !watchRestored) {
175
+ watchRestored = true
176
+ watchManager.restorePersisted()
177
+ }
178
+ return applyWatchSettings(watchManager, config)
168
179
  }
180
+ ctx.effect(() => {
181
+ syncWatch()
182
+ return () => watchManager.stop()
183
+ })
169
184
 
170
185
  if (config.lazyIndexing) {
171
186
  setupLazyIndexing(ctx, config, watchManager)
172
187
  }
173
188
 
189
+ // 设置页保存(宿主 volatile 更新)后:只有 watchInterval 会影响运行中的定时器,
190
+ // 其余 volatile 字段都在各自的读取点当场生效(llmQueryExpansion 每次查询读、autoIndex 只认启动值)。
191
+ // paths 为 `[[]]` 时表示整份 Config 都可能变了 → changedConfigKeys 返回 null,按"全部重读"处理。
192
+ ctx.on('loader/volatile-update', (paths) => {
193
+ const changed = changedConfigKeys(paths)
194
+ if (changed === null || changed.has('watchInterval')) syncWatch()
195
+ })
196
+
174
197
  // 卸载/退出前把还脏着的 store 同步写一次(后台重试只是兜底,不能当正确性保证)。
175
198
  if (typeof ctx.effect === 'function') {
176
199
  ctx.effect(() => () => flushDirtyStores({ timeoutMs: 1500 }))
@@ -218,7 +241,9 @@ export function apply(ctx, config) {
218
241
  // 注册 agent/pre-step 监听,向每步请求追加记忆消息(默认开;异常/无会话 cwd → 交回默认决策)。
219
242
  installAutoInject(ctx, config)
220
243
 
221
- if (config.autoIndexOnFirstUse) {
244
+ // 启动时全量索引是**一次性**动作:设置页把它打开只影响下一次启动,不会当场扫全树
245
+ // (卡片上的说明也这么写)。所以这里读的是本次启动时的值,不订阅后续变化。
246
+ if (cfgValue(config, 'autoIndexOnFirstUse')) {
222
247
  // effect 回调必须同步并返回 disposer;异步体独立执行,用 cancelled 标志避免卸载后再写日志
223
248
  ctx.effect(() => {
224
249
  let cancelled = false
@@ -481,7 +481,9 @@ function readJson(file, fallback) {
481
481
  function normalizeDoc(doc) {
482
482
  if (doc && typeof doc === 'object' && Array.isArray(doc.items)) {
483
483
  if (typeof doc.version !== 'number') doc.version = 1
484
- if (!Array.isArray(doc.items)) doc.items = []
484
+ // 手改/旧版本可能把 null 混进 items:调用方大量使用 `it.id` / `it.archived`,一个 null
485
+ // 就能让全局召回或容量裁剪整段抛错。与 project 级 `_loadInsights` 的过滤保持一致。
486
+ doc.items = doc.items.filter((it) => it && typeof it === 'object' && !Array.isArray(it))
485
487
  return doc
486
488
  }
487
489
  return emptyInsightsDoc()
@@ -528,6 +530,9 @@ export class GlobalStore {
528
530
 
529
531
  markDirty() {
530
532
  this._dirty = true
533
+ // 退出/卸载时 flushDirtyStores() 只遍历 tracked 集合:不在这里登记,query_memory 这类
534
+ // "只改内存、不立刻 commit"的路径(命中记账、派生 trigger 回填)就会在进程退出时丢掉。
535
+ trackDirty(this)
531
536
  }
532
537
 
533
538
  /**
package/src/lazy.js CHANGED
@@ -1,53 +1,218 @@
1
1
  import path from 'node:path'
2
2
  import { statSync } from 'node:fs'
3
- import { excludedEntryForPath, findProjectRoot, isGitIgnored, memoryRootFor, relativePath, rootRejection, storeKey } from './util/fs.js'
3
+ import {
4
+ ROOT_SOURCES,
5
+ excludedEntryForPath,
6
+ findProjectRoot,
7
+ findProjectRootWithSource,
8
+ isGitIgnored,
9
+ isGitIgnoredBatch,
10
+ isHiddenPath,
11
+ memoryRootFor,
12
+ relativePath,
13
+ rootRejection,
14
+ storeKey,
15
+ } from './util/fs.js'
4
16
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
5
17
  import { ProjectMemoryStore } from './store.js'
6
18
  import { onFileObserved } from './enhancer.js'
7
19
  import { sessionWorkingDir } from './util/session-dir.js'
20
+ import { clearIndexFailure, recordIndexFailure } from './index-failures.js'
8
21
 
9
22
  // 根推导策略已收敛到 util/fs.js(唯一实现)。这里重新导出,保持既有 import 路径可用。
10
23
  export { findProjectRoot }
11
24
 
12
- export async function indexFile(ctx, config, filePath, watchManager = null, sessionRoot = null) {
13
- const kind = fileKind(path.extname(filePath).toLowerCase())
14
- if (!kind) return false
15
- // roots.exclude 是子树级否定:被排除的文件连根都不推导,直接不落任何记忆。
16
- if (excludedEntryForPath(filePath, config)) return false
17
- // 根来源优先级:显式 watch 过的根 → 项目标记 → 会话工作目录(安全时)。
18
- // 显式登记过的根优先,是为了让"没有标记但被 watch_repo 指定过"的项目也能持续刷新。
25
+ /**
26
+ * 懒索引的成本结构(9p 代理实测,原生 NTFS 同序只是常数小):
27
+ * `findProjectRoot`(逐层 readdir)18–45ms、`git check-ignore`(起进程)30ms、
28
+ * 整读 + sha256 4ms、save 35ms。前两项**每个文件各付一次**,与文件内容变没变无关。
29
+ *
30
+ * 所以这里做三件事,且都不改变语义:
31
+ * ① 根按目录缓存(5s 上限):一次 flush 里的文件通常同目录,别每个文件走一遍祖先;
32
+ * ② mtime + size 未变 → 不读盘、不问 git(`record.mtimeMs` 由写入侧记下);
33
+ * ③ 一次 flush 只 commit 一次、只起一次 `git check-ignore`。
34
+ * 根缓存只存**由标记推出**的根:`session` 兜底是"这一带还没有标记"的推断,钉 5s 会让
35
+ * `git init` / `npm init` 建出来的项目先落进会话根的 store(真根出现后就是一份重复条目)。
36
+ * 代价只是无标记目录仍按次走一遍祖先(与加缓存之前一致),有标记的项目热路径不受影响。
37
+ * 已有标记的根仍缓存 5s:在它的子目录里 5s 内嵌套新建项目,文件可能先落进父根的 store,
38
+ * 下一次解析就换根、父 store 里的副本留给扫描清理——这是缓存换热路径的必要取舍。
39
+ */
40
+ const ROOT_CACHE_TTL_MS = 5000
41
+ const ROOT_CACHE_MAX = 4096
42
+ const rootCaches = new WeakMap()
43
+
44
+ function rootCacheFor(config) {
45
+ let cache = rootCaches.get(config)
46
+ if (!cache) {
47
+ cache = new Map()
48
+ rootCaches.set(config, cache)
49
+ }
50
+ return cache
51
+ }
52
+
53
+ /** 清空根缓存(测试 / 诊断;不传 config 表示全清)。 */
54
+ export function clearRootCache(config) {
55
+ if (config) rootCaches.delete(config)
56
+ else rootCaches.clear()
57
+ }
58
+
59
+ function cachedProjectRoot(config, filePath, watchManager, sessionRoot) {
60
+ const cache = rootCacheFor(config)
61
+ const dir = path.dirname(filePath)
19
62
  const extraRoots = watchManager ? [...watchManager.roots.keys()] : []
20
- const root = findProjectRoot(filePath, { extraRoots, sessionRoot, config })
21
- if (!root || rootRejection(root, config)) return false
22
- // 被 .gitignore 排除的文件(构建产物 / 内部文档)不进语料;显式 index_doc 不受此限。
23
- if (isGitIgnored(root, filePath)) return false
24
-
25
- const memoryDir = memoryRootFor(root, config.memoryDir)
26
- const store = new ProjectMemoryStore(memoryDir).load()
27
- const rel = storeKey(relativePath(root, filePath))
28
- const record = store.fileRecord(rel)
29
-
30
- let size
31
- let plan
32
- try {
33
- size = statSync(filePath).size
34
- plan = await planFileIndex({ rel, filePath, kind, config, record, existingEntries: store.entries[rel], size })
35
- } catch {
36
- return false
63
+ // 会话工作目录 / watch 根集合变了,答案就可能变:都进 key,不做过期以外的失效。
64
+ const key = `${sessionRoot || ''}\u0000${extraRoots.join('\u0001')}\u0000${dir}`
65
+ const hit = cache.get(key)
66
+ const now = Date.now()
67
+ if (hit && now - hit.at < ROOT_CACHE_TTL_MS) return hit.root
68
+ const { root, source } = findProjectRootWithSource(filePath, { extraRoots, sessionRoot, config })
69
+ if (!root) return null
70
+ // 会话根兜底不进缓存:它是"没找到标记"的推断,而"后来才建出标记"正是唯一能让它失效的事件。
71
+ if (source === ROOT_SOURCES.SESSION) return root
72
+ if (cache.size >= ROOT_CACHE_MAX) cache.clear()
73
+ cache.set(key, { root, at: now })
74
+ return root
75
+ }
76
+
77
+ /**
78
+ * 一批"观察到的文件" → 每个 store 一次 commit。
79
+ *
80
+ * @param {object} config 插件配置
81
+ * @param {{filePath: string, sessionRoot: string|null, watchManager?: object|null}[]} items
82
+ * @returns {Promise<Map<string, boolean>>} filePath → 是否真的写入了条目(未变更 / 被排除 / 失败都是 false)
83
+ */
84
+ export async function indexObservedBatch(config, items, watchManager = null) {
85
+ const results = new Map()
86
+ /** 需要进一步判定(可能真变了)的候选;未变更的文件在这一步就被排除了。 */
87
+ const candidates = []
88
+
89
+ for (const item of items) {
90
+ const { filePath, sessionRoot } = item
91
+ try {
92
+ const kind = fileKind(path.extname(filePath).toLowerCase())
93
+ if (!kind) {
94
+ results.set(filePath, false)
95
+ continue
96
+ }
97
+ // roots.exclude 是子树级否定:被排除的文件连根都不推导,直接不落任何记忆。
98
+ if (excludedEntryForPath(filePath, config)) {
99
+ results.set(filePath, false)
100
+ continue
101
+ }
102
+ const root = cachedProjectRoot(config, filePath, watchManager, sessionRoot)
103
+ if (!root || rootRejection(root, config)) {
104
+ results.set(filePath, false)
105
+ continue
106
+ }
107
+ const store = new ProjectMemoryStore(memoryRootFor(root, config.memoryDir)).load()
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
+ }
115
+ const record = store.fileRecord(rel)
116
+ const st = statSync(filePath)
117
+ // 快路径:mtime + size 都没动 → 连 git 都不用问。这是"重复读同一个文件"的主路径。
118
+ // doc 不走这条捷径:旧 store 的 terms 回填条件要看 entries,交给 planFileIndex 判。
119
+ if (kind === 'code' && record && typeof record.mtimeMs === 'number' && record.mtimeMs === st.mtimeMs && record.size === st.size) {
120
+ results.set(filePath, false)
121
+ continue
122
+ }
123
+ candidates.push({ store, root, rel, filePath, kind, record, size: st.size, mtimeMs: st.mtimeMs, gitRel: relativePath(root, filePath) })
124
+ results.set(filePath, false)
125
+ } catch {
126
+ results.set(filePath, false)
127
+ }
37
128
  }
38
- if (plan.key === UNCHANGED || plan.key === OVERSIZE) return false
39
129
 
40
- if (watchManager && watchManager.addRoot(root)) {
41
- // 只有真正新登记的根才持久化:addRoot 拒绝的根(不安全/不存在)不再被无条件
42
- // addWatch 记进 watch.json —— 那样会造出一个每次启动都复活的"僵尸根"。
43
- store.addWatch(root)
130
+ if (candidates.length === 0) return results
131
+
132
+ // 按根分组:同一个 flush 里同根的文件共用一次 check-ignore 子进程。
133
+ const byRoot = new Map()
134
+ for (const cand of candidates) {
135
+ let list = byRoot.get(cand.root)
136
+ if (!list) {
137
+ list = []
138
+ byRoot.set(cand.root, list)
139
+ }
140
+ list.push(cand)
44
141
  }
45
142
 
46
- if (plan.key !== DROP && plan.type === 'code') {
47
- onFileObserved(store, rel, filePath, config, root)
143
+ for (const [root, list] of byRoot) {
144
+ // gitignore 只管"**新条目**进不进语料":已经有记录的条目(这次是内容变了要刷新)
145
+ // 不再逐次问 git —— 那是一次进程启动(9p 30ms / 原生 Windows 15–40ms),
146
+ // 而"文件被加进 .gitignore"由 index_repo / watch 的清理路径负责,不该在读路径上判。
147
+ const fresh = list.filter((c) => !c.record)
148
+ let ignored = new Set()
149
+ if (fresh.length > 0) {
150
+ try {
151
+ ignored = isGitIgnoredBatch(root, fresh.map((c) => c.gitRel))
152
+ } catch {
153
+ ignored = new Set()
154
+ }
155
+ }
156
+ const kept = ignored.size === 0 ? list : list.filter((c) => !ignored.has(c.gitRel))
157
+ if (kept.length === 0) continue
158
+
159
+ const store = kept[0].store
160
+ const updates = []
161
+ let refreshed = false
162
+ for (const cand of kept) {
163
+ try {
164
+ const plan = await planFileIndex({
165
+ rel: cand.rel,
166
+ filePath: cand.filePath,
167
+ kind: cand.kind,
168
+ config,
169
+ record: cand.record,
170
+ existingEntries: store.entries[cand.rel],
171
+ size: cand.size,
172
+ mtimeMs: cand.mtimeMs,
173
+ })
174
+ if (plan.key === UNCHANGED) {
175
+ // 内容没变、只有 mtime 变了:把新 mtime 记回去,否则下次还要整读一遍。
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) continue
182
+ updates.push(toFileUpdate(cand.rel, plan, cand.record))
183
+ if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
184
+ results.set(cand.filePath, plan.key !== DROP)
185
+ } catch (err) {
186
+ // 单文件读盘 / 解析失败不影响同批其它文件;但要登记,否则"读了却没索引成"
187
+ // 在界面上完全不可见(过去这里连日志都没有)。
188
+ recordIndexFailure(cand.root, cand.rel, err.message)
189
+ results.set(cand.filePath, false)
190
+ }
191
+ }
192
+
193
+ let addedWatch = false
194
+ if (watchManager && watchManager.addRoot(root)) {
195
+ // 只有真正新登记的根才持久化:addRoot 拒绝的根(不安全/不存在)不再被无条件
196
+ // addWatch 记进 watch.json —— 那样会造出一个每次启动都复活的"僵尸根"。
197
+ addedWatch = store.addWatch(root)
198
+ }
199
+
200
+ try {
201
+ if (updates.length > 0) commitFileUpdates(store, { updates })
202
+ // addedWatch 也要落盘:本轮可能没有任何条目更新(文件已是最新),但新登记的 watch 根
203
+ // 是独立的事实;不 save 的话重启后它不在 watch.json 里,监视会静默退回启动时的根集合。
204
+ else if (refreshed || addedWatch) store.commit(() => {})
205
+ } catch (err) {
206
+ console.error(`[dsh-project-memory] lazy index commit failed for ${root}: ${err.message}`)
207
+ }
48
208
  }
49
- commitFileUpdates(store, { updates: [toFileUpdate(rel, plan, record)] })
50
- return plan.key !== DROP
209
+
210
+ return results
211
+ }
212
+
213
+ export async function indexFile(ctx, config, filePath, watchManager = null, sessionRoot = null) {
214
+ const results = await indexObservedBatch(config, [{ filePath, sessionRoot }], watchManager)
215
+ return results.get(filePath) === true
51
216
  }
52
217
 
53
218
  export function codeFirst(paths) {
@@ -64,15 +229,15 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
64
229
 
65
230
  const flush = async () => {
66
231
  timer = null
67
- const batch = codeFirst([...pending.keys()])
68
- const roots = new Map(pending)
232
+ const batch = codeFirst([...pending.keys()]).map((filePath) => ({
233
+ filePath,
234
+ sessionRoot: pending.get(filePath) || null,
235
+ }))
69
236
  pending.clear()
70
- for (const filePath of batch) {
71
- try {
72
- await indexFile(ctx, config, filePath, watchManager, roots.get(filePath) || null)
73
- } catch (err) {
74
- console.error(`[dsh-project-memory] lazy index failed for ${filePath}: ${err.message}`)
75
- }
237
+ try {
238
+ await indexObservedBatch(config, batch, watchManager)
239
+ } catch (err) {
240
+ console.error(`[dsh-project-memory] lazy index batch failed: ${err.message}`)
76
241
  }
77
242
  }
78
243
 
@@ -97,4 +262,4 @@ export function setupLazyIndexing(ctx, config, watchManager = null) {
97
262
  ctx.effect(() => () => {
98
263
  if (timer) clearTimeout(timer)
99
264
  })
100
- }
265
+ }
@@ -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,
@@ -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 // 兼容旧字段:读+写总数(保留,避免老任务语义漂移)