@yolk_vat-y/dsh-project-memory 0.6.8 → 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
+ }
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
@@ -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,34 @@ 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)
169
178
  continue
170
179
  }
180
+ clearIndexFailure(cand.root, cand.rel)
171
181
  if (plan.key === OVERSIZE) continue
172
182
  updates.push(toFileUpdate(cand.rel, plan, cand.record))
173
183
  if (plan.key !== DROP && plan.type === 'code') onFileObserved(store, cand.rel, cand.filePath, config, root)
174
184
  results.set(cand.filePath, plan.key !== DROP)
175
- } catch {
176
- // 单文件读盘 / 解析失败不影响同批其它文件。
185
+ } catch (err) {
186
+ // 单文件读盘 / 解析失败不影响同批其它文件;但要登记,否则"读了却没索引成"
187
+ // 在界面上完全不可见(过去这里连日志都没有)。
188
+ recordIndexFailure(cand.root, cand.rel, err.message)
177
189
  results.set(cand.filePath, false)
178
190
  }
179
191
  }
180
192
 
193
+ let addedWatch = false
181
194
  if (watchManager && watchManager.addRoot(root)) {
182
195
  // 只有真正新登记的根才持久化:addRoot 拒绝的根(不安全/不存在)不再被无条件
183
196
  // addWatch 记进 watch.json —— 那样会造出一个每次启动都复活的"僵尸根"。
184
- store.addWatch(root)
197
+ addedWatch = store.addWatch(root)
185
198
  }
186
199
 
187
200
  try {
188
201
  if (updates.length > 0) commitFileUpdates(store, { updates })
189
- else if (refreshed) store.commit(() => {})
202
+ // addedWatch 也要落盘:本轮可能没有任何条目更新(文件已是最新),但新登记的 watch 根
203
+ // 是独立的事实;不 save 的话重启后它不在 watch.json 里,监视会静默退回启动时的根集合。
204
+ else if (refreshed || addedWatch) store.commit(() => {})
190
205
  } catch (err) {
191
206
  console.error(`[dsh-project-memory] lazy index commit failed for ${root}: ${err.message}`)
192
207
  }
@@ -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 // 兼容旧字段:读+写总数(保留,避免老任务语义漂移)