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

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/watch.js CHANGED
@@ -1,10 +1,30 @@
1
- import { existsSync, statSync } from 'node:fs'
1
+ import { existsSync } from 'node:fs'
2
+ import { stat } from 'node:fs/promises'
2
3
  import path from 'node:path'
3
4
  import { listProjectFiles, memoryDirName, memoryRootFor, relativePath, rootRejection, scanLimits, storeKey } from './util/fs.js'
4
5
  import { OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
5
6
  import { ProjectMemoryStore } from './store.js'
6
7
  import { onFileChanged, isTypeScriptFile } from './enhancer.js'
7
8
 
9
+ /**
10
+ * 有界并发 map。同步 `statSync` 循环在 Windows(尤其 WSL 挂 `/mnt/c`)会把事件循环卡住:
11
+ * 400 文件实测 ~0.9s、12k 文件按同一比例是几十秒,期间面板与工具调用全部停摆。
12
+ * 改用 `fs/promises.stat` + 16 并发:总量不变,主线程等 I/O 时可以让出去。
13
+ */
14
+ async function mapLimit(items, limit, fn) {
15
+ const out = new Array(items.length)
16
+ let next = 0
17
+ const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
18
+ for (;;) {
19
+ const index = next++
20
+ if (index >= items.length) return
21
+ out[index] = await fn(items[index], index)
22
+ }
23
+ })
24
+ await Promise.all(workers)
25
+ return out
26
+ }
27
+
8
28
  export class WatchManager {
9
29
  constructor(ctx, config) {
10
30
  this.ctx = ctx
@@ -13,15 +33,13 @@ export class WatchManager {
13
33
  this.timer = null
14
34
  this._polling = false
15
35
  this._truncationWarned = new Set()
16
- /** 已就「读不到的目录」告警过的根:同上,只提示一次。 */
36
+ /** 已就「读不到的目录」告警过的根,只提示一次。 */
17
37
  this._unreadableWarned = new Set()
18
- /** 已就「跳过了嵌套项目根」告警过的根:同上,只提示一次。 */
38
+ /** 已就「跳过了嵌套项目根」告警过的根,只提示一次。 */
19
39
  this._nestedStoreWarned = new Set()
20
40
  /** 正在跑回合的会话 id 集合:**多会话**下任一在跑就算活跃(见 setSessionActive)。 */
21
41
  this._activeSessions = new Set()
22
- /** 当前是否处于"有人正在用"的活跃态。 */
23
42
  this._active = false
24
- /** 活跃态下的兜底间隔(见 start):活跃 ≠ 永不扫描,只是把节拍压到最低。 */
25
43
  this._activeInterval = undefined
26
44
  }
27
45
 
@@ -36,29 +54,23 @@ export class WatchManager {
36
54
  return best
37
55
  }
38
56
 
39
- /**
40
- * 危险根是否被显式放行(兼容旧调用点;真正的判定统一走 rootRejection)。
41
- * 注意:这个开关只放开内置名单,`roots.deny` / `roots.exclude` 仍然优先。
42
- */
57
+ /** 危险根是否被显式放行(兼容旧调用点;判定统一走 rootRejection,deny/exclude 仍优先)。 */
43
58
  unsafeAllowed() {
44
59
  return this.config?.allowUnsafeRoots === true
45
60
  }
46
61
 
47
62
  restorePersisted() {
48
63
  const cwd = process.cwd()
49
- // cwd 是家目录/系统目录时直接跳过:旧顺序是「先 load 再判断」,而历史遗留的超大 store
50
- // 光读盘就能 OOM —— 那恰恰是 issue #5 的报告者重启后会撞上的场景。
64
+ // cwd 是家目录/系统目录时直接跳过:必须「先判断再 load」,否则遗留的超大 store 光读盘就能 OOM。
51
65
  if (rootRejection(cwd, this.config)) return
52
- // 用 load() 的返回值:storeCache 命中时 load() 返回的是缓存实例,忽略返回值会拿到空 store
66
+ // 用 load() 的返回值:storeCache 命中时返回的是缓存实例,忽略它会拿到空 store。
53
67
  const store = new ProjectMemoryStore(memoryRootFor(cwd, this.config.memoryDir)).load()
54
68
  if (existsSync(store.dir)) {
55
69
  let dropped = 0
56
70
  for (const root of [...store.watchlist]) {
57
71
  if (typeof root !== 'string' || !root) continue
58
72
  // 自愈剔除两类条目:已不存在的根(每轮白跑,还会把目录重新 mkdir 出来),
59
- // 以及按当前配置不能整体监听的根(内置名单 / roots.deny / roots.exclude)。
60
- // 后者同时**修复历史遗留**与"新增 deny 后 watch.json 仍留着旧根":下一次启动
61
- // 就会自动摘掉,不需要用户手删 watch.json。
73
+ // 以及按当前配置不能整体监听的根。下一次启动自动摘掉,不需要用户手删 watch.json。
62
74
  if (!existsSync(root) || rootRejection(root, this.config)) {
63
75
  store.removeWatch(root)
64
76
  dropped++
@@ -71,20 +83,17 @@ export class WatchManager {
71
83
  }
72
84
 
73
85
  addRoot(root) {
74
- // 根目录不存在就拒绝:否则每轮 poll 都会 commit → save → mkdirSync,
75
- // 把一条历史遗留、已被删除的 watchlist 条目重新「创建」出来。
86
+ // 根目录不存在就拒绝:否则每轮 poll 的 commit → save → mkdirSync 会把它重新「创建」出来。
76
87
  if (!existsSync(root)) return false
77
- // 文件系统根 / 家目录 / 系统前缀 / roots.deny 不整体监听(它们的子目录允许),
78
- // roots.exclude 下的目录同样不监听;除非配置显式放行(仅内置名单可放行)。
88
+ // 文件系统根 / 家目录 / 系统前缀 / roots.deny / roots.exclude 不整体监听(子目录允许),
89
+ // 除非配置显式放行(仅内置名单可放行)。
79
90
  if (rootRejection(root, this.config)) return false
80
91
  if (!this.roots.has(root)) {
81
- // **不在这里 load()**:`restorePersisted()` 会对 cwd store 的整条 watchlist 逐个 addRoot,
82
- // 急切读盘等于「watch 过多少个根,启动就同步读多少个 store 的全部 shard」——一个万文件
83
- // 的 store 就是秒级,几十个根就是启动卡死 + 内存无上界。这里只登记,store 到第一次
84
- // pollRoot 真正需要时才取(见 `storeFor`)。
92
+ // **不在这里 load()**:`restorePersisted()` 会对整条 watchlist 逐个 addRoot,急切读盘等于
93
+ // 「watch 过多少个根,启动就同步读多少个 store 的全部 shard」。store 到 pollRoot 需要时才取。
85
94
  this.roots.set(root, {
86
95
  snapshot: {},
87
- // rel → 上次已上报的错误信息。坏文件每轮都会重试,逐轮打印会刷屏。
96
+ // rel → 上次已上报的错误。坏文件每轮都会重试,逐轮打印会刷屏。
88
97
  failures: new Map(),
89
98
  })
90
99
  return true
@@ -93,15 +102,9 @@ export class WatchManager {
93
102
  }
94
103
 
95
104
  /**
96
- * 每个根**按需**取 store:命中 `storeCache` 时是 O(1)(一次 Map 查找 + LRU 挪位)。
97
- *
98
- * 刻意不让本类长期持有实例。旧实现把 `store` 塞进 `this.roots` 里,等于给每个 watch 根
99
- * 加了一个**进程级强引用**,于是:
100
- * - 逐出对 watch 根完全不省内存(`storeCache` 丢了 key,watcher 还攥着);
101
- * - 一旦真被逐出,下一次 `load()` 会从盘上**再建一份**,同一个 root 在同一进程里出现两份
102
- * 互不可见的内存状态,两份各自 `save()` 脏分片 → 最后写者赢,存在丢更新的窗口。
103
- * 现在唯一的活实例就是缓存里那一个:逐出即真正释放,下一轮 poll 重新读盘(缓存该有的语义),
104
- * 而内存上界回到 `STORE_CACHE_MAX_BYTES`,不再由「watch 了多少个根」决定。
105
+ * 每个根**按需**取 store(命中 `storeCache` 即 O(1))。本类不长期持有实例:否则逐出对 watch
106
+ * 根不省内存,真被逐出后 `load()` 还会再建一份,同一 root 出现两份互不可见的状态。内存上界
107
+ * 因此回到 `STORE_CACHE_MAX_BYTES`,不由「watch 了多少个根」决定。
105
108
  */
106
109
  storeFor(root) {
107
110
  return new ProjectMemoryStore(memoryRootFor(root, this.config.memoryDir)).load()
@@ -112,17 +115,16 @@ export class WatchManager {
112
115
  }
113
116
 
114
117
  start(intervalMs = 30000) {
115
- if (this.timer) return
116
- // NaN/undefined 会让定时器退化成 1ms 轮询(Node 只发一条 TimeoutNaNWarning),
117
- // 足以打满事件循环让 agent 无法响应;非法值回退到默认 30s。
118
+ // 轮询进行中 `timer` 会短暂为 null;此时再 start 会排第二个定时器。等这一轮结束由 `_tick()` 自己续。
119
+ if (this.timer || this._polling) return
120
+ // 非法值(NaN/undefined)会让定时器退化成 1ms 轮询打满事件循环,故回退默认 30s。
118
121
  const raw = Number(intervalMs)
119
122
  this._baseInterval = Number.isFinite(raw) ? Math.max(raw, 1000) : 30000
120
123
  // 空闲退避:连续没有变化的轮次把间隔翻倍,最长 2 分钟一轮;任何变化立刻回到 base。
121
- // 轮询本身是 O(树) 的 walkDir + 逐文件 stat(本仓库一轮实测 58–87ms),
122
- // 常驻 15s 一轮意味着不管有没有改动都在磨 I/O。
124
+ // 轮询是 O(树) 的 walkDir + 逐文件 stat(本仓库一轮实测 58–87ms),常驻 15s 一轮都在磨 I/O。
123
125
  this._maxInterval = Math.max(this._baseInterval, Math.min(this._baseInterval * 8, 120000))
124
126
  // 活跃兜底:**有人正在跑回合**时把节拍压到最低(默认 5 分钟、且不小于 base 的 10 倍)。
125
- // 不是"永不扫描"——外部编辑器改文件、或回合一直不结束(崩溃/长任务)时,索引仍会自愈。
127
+ // 不是"永不扫描"——外部编辑器改文件、或回合一直不结束(崩溃/长任务)时索引仍会自愈。
126
128
  this._activeInterval = Math.max(this._baseInterval * 10, 300000)
127
129
  this._interval = this._baseInterval
128
130
  this._stopped = false
@@ -131,10 +133,8 @@ export class WatchManager {
131
133
 
132
134
  /**
133
135
  * 会话活跃信号:有会话在跑就把轮询压到最低,**回合结束立刻合并扫一次**。
134
- *
135
- * 为什么:轮询是唯一"用户没在等、却仍在花机器"的地方,而它扫描的时机(用户正打字/模型正在
136
- * 跑)恰恰是最不该抢 CPU 的时候。活跃期间真实改动会由下一轮兜底(≤ activeInterval)覆盖,
137
- * 回合一结束就把这一轮攒下的改动一次性并进来——索引还比"边跑边扫"更新鲜。
136
+ * 轮询是唯一"用户没在等、却仍在花机器"的地方,扫描时机恰好最不该抢 CPU;活跃期间的
137
+ * 真实改动由下一轮兜底(≤ activeInterval 覆盖),回合结束一次性并入。
138
138
  * @param key - 会话标识(`session.id`);多会话下任一活跃即活跃。
139
139
  * @param active - 该会话是否正在跑回合。
140
140
  */
@@ -158,12 +158,15 @@ export class WatchManager {
158
158
  }
159
159
 
160
160
  _schedule(interval = this._interval) {
161
+ if (this._stopped || this.timer) return
161
162
  this.timer = setTimeout(() => this._tick(), interval)
162
163
  if (this.timer.unref) this.timer.unref()
163
164
  }
164
165
 
165
166
  async _tick() {
166
167
  this.timer = null
168
+ // stop() 之后若还有定时器已经触发,不能再扫一轮。
169
+ if (this._stopped) return
167
170
  let changed = false
168
171
  try {
169
172
  changed = await this.poll()
@@ -174,7 +177,8 @@ export class WatchManager {
174
177
  this._interval = this._active
175
178
  ? this._activeInterval
176
179
  : changed ? this._baseInterval : Math.min(this._interval * 2, this._maxInterval)
177
- this._schedule()
180
+ // poll 期间可能已排过下一轮;有就不再覆盖,否则旧句柄泄漏、轮询频率翻倍。
181
+ if (!this.timer) this._schedule()
178
182
  }
179
183
 
180
184
  stop() {
@@ -205,9 +209,9 @@ export class WatchManager {
205
209
  async pollRoot(root, state) {
206
210
  const seen = new Set()
207
211
  const updates = []
208
- // rel → 本轮采集的 mtime:size。提交成功后才落进快照;CAS 失败的条目留在原地等下一轮。
212
+ // rel → 本轮采集的 mtime:size。提交成功后才落进快照;CAS 失败的条目下轮重试。
209
213
  const signatures = new Map()
210
- // 本轮用的 store:命中缓存即 O(1),被逐出则重新读盘。整个 pollRoot 期间共用同一个实例。
214
+ // 本轮用的 store:命中缓存即 O(1),被逐出则重新读盘。整个 pollRoot 期间共用这一个实例。
211
215
  const store = this.storeFor(root)
212
216
 
213
217
  const { files, truncated, capped, skipped: nestedRoots, unreadable } = listProjectFiles(root, {
@@ -216,7 +220,7 @@ export class WatchManager {
216
220
  config: this.config,
217
221
  })
218
222
  if (nestedRoots.length && !this._nestedStoreWarned.has(root)) {
219
- // 同上,只提示一次。这里同时说明"旧副本会被本轮清掉"——升级后的存量重复就是这么收敛的。
223
+ // 只提示一次:说明它们的旧副本会被本轮清掉。
220
224
  this._nestedStoreWarned.add(root)
221
225
  const rels = nestedRoots.map((p) => storeKey(relativePath(root, p)))
222
226
  console.error(
@@ -243,18 +247,23 @@ export class WatchManager {
243
247
  )
244
248
  }
245
249
 
246
- for (const filePath of files) {
250
+ // 先把元数据并发取回来;解析仍按顺序,解析量只与"变了的文件"有关。
251
+ const statsByIndex = await mapLimit(files, 16, async (filePath) => {
252
+ try {
253
+ return await stat(filePath)
254
+ } catch {
255
+ return null
256
+ }
257
+ })
258
+ for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
259
+ const filePath = files[fileIndex]
247
260
  const rel = storeKey(relativePath(root, filePath))
248
261
  seen.add(rel)
249
262
  const kind = fileKind(path.extname(filePath).toLowerCase())
250
263
  if (!kind) continue
251
264
 
252
- let stats
253
- try {
254
- stats = statSync(filePath)
255
- } catch {
256
- continue
257
- }
265
+ const stats = statsByIndex[fileIndex]
266
+ if (!stats) continue
258
267
  const sig = `${stats.mtimeMs}:${stats.size}`
259
268
  if (state.snapshot[rel] === sig) continue
260
269
 
@@ -271,7 +280,7 @@ export class WatchManager {
271
280
  size: stats.size,
272
281
  })
273
282
  } catch (err) {
274
- // 坏文件每轮都会重试:同一个文件的同一个错误只上报一次,否则逐轮 console.error 刷屏。
283
+ // 坏文件每轮都会重试:同一个文件的同一个错误只上报一次,否则逐轮刷屏。
275
284
  if (state.failures.get(rel) !== err.message) {
276
285
  state.failures.set(rel, err.message)
277
286
  console.error(`[dsh-project-memory] re-index failed for ${rel}: ${err.message}`)
@@ -279,8 +288,7 @@ export class WatchManager {
279
288
  continue
280
289
  }
281
290
  state.failures.delete(rel)
282
- // 内容未变 / 体积超限也要落快照:否则 mtime:size 快路径永远命中不了,
283
- // 每次 poll 都要把整个仓库重读一遍再哈希(watch 默认开、15s 一轮)。
291
+ // 内容未变 / 体积超限也要落快照:否则 mtime:size 快路径永远命中不了,每次 poll 都要重读全仓。
284
292
  if (plan.key === UNCHANGED || plan.key === OVERSIZE) {
285
293
  state.snapshot[rel] = sig
286
294
  continue
@@ -290,14 +298,19 @@ export class WatchManager {
290
298
  updates.push(toFileUpdate(rel, plan, record))
291
299
  }
292
300
 
293
- // 单事务写盘;CAS 失败的条目本轮不落快照,下一轮自然重试。
294
- // 截断时**不传 unseen**:没扫到的文件不等于被删了,否则一份被上限截掉的树每轮都会
295
- // 把自己的记忆删掉一半(先删再下轮重新索引,纯粹的抖动)。`truncated` 同样覆盖
296
- // "有目录读不到"(EACCES)这一路。
301
+ // 单事务写盘;CAS 失败的条目本轮不落快照,下一轮重试。
302
+ // 截断时**不传 unseen**:没扫到的文件不等于被删了,否则被上限截掉的树每轮都会删掉自己
303
+ // 一半记忆(先删再重新索引,纯粹的抖动)。`truncated` 同样覆盖"有目录读不到"(EACCES)。
297
304
  const { stale, removed } = commitFileUpdates(store, {
298
305
  updates,
299
306
  unseen: truncated ? null : seen,
307
+ root,
300
308
  })
309
+ // 扫全了才剪快照:删掉的文件不能留着,否则它以同样的 mtime:size 回来会被当成未变。
310
+ if (!truncated) {
311
+ for (const rel of Object.keys(state.snapshot)) if (!seen.has(rel)) delete state.snapshot[rel]
312
+ for (const rel of state.failures.keys()) if (!seen.has(rel)) state.failures.delete(rel)
313
+ }
301
314
  const failed = new Set(stale)
302
315
  let applied = 0
303
316
  for (const update of updates) {