@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.
@@ -0,0 +1,65 @@
1
+ /**
2
+ * 配置读取的唯一入口。
3
+ *
4
+ * Config 里标了 `.volatile()` 的字段由宿主注入成 **ref**(`{ get() }`)——这是设置页
5
+ * 「改完立即生效、不重启插件」的代价:同一个 `config` 对象上,volatile 字段是 ref、
6
+ * 其余字段仍是普通值。直接写 `if (config.watch)` 会把 ref 对象当成永远为真(watch 关不掉),
7
+ * 所以所有读取点都走 {@link cfg}。
8
+ *
9
+ * 为什么不用顶层 `inject` 或每次读 `config.x.get()`:ref 与值混在一行会让「这个键是活的吗」
10
+ * 变成隐式知识;`cfgValue()` 两种形状都给同一个答案,改字段的 volatile 属性不需要连带改读取点。
11
+ */
12
+
13
+ /**
14
+ * 读一个顶层配置字段的**当前值**。
15
+ * @param {object | undefined} config 插件 Config
16
+ * @param {string} key 顶层字段名
17
+ * @returns {*} 字段值;volatile 字段取 `ref.get()`
18
+ */
19
+ export function cfgValue(config, key) {
20
+ const value = config?.[key]
21
+ return value && typeof value.get === 'function' ? value.get() : value
22
+ }
23
+
24
+ let warnedNoVolatile = false
25
+ /**
26
+ * 把 schema 标成 volatile;宿主 schemastery < 3.18.3 时降级为普通值。
27
+ *
28
+ * `.volatile()` 是 3.18.3 才有的方法,而 peer 范围曾经写成 `^3.18.1`:旧宿主在
29
+ * **模块加载期**执行 `Schema.boolean().default(false).volatile()` 会直接抛 TypeError,插件
30
+ * 整个起不来。这里做一次特性探测:方法不在就原样返回(设置页不可用,但 cfgValue 仍能读值,
31
+ * 插件其余功能正常),并只告警一次。
32
+ * @template T
33
+ * @param {T} schema 任意 schemastery schema
34
+ * @returns {T}
35
+ */
36
+ export function asVolatile(schema) {
37
+ const method = schema?.volatile
38
+ if (typeof method === 'function') return method.call(schema)
39
+ if (!warnedNoVolatile) {
40
+ warnedNoVolatile = true
41
+ console.warn(
42
+ '[dsh-project-memory] host schemastery has no .volatile() (needs >= 3.18.3); ' +
43
+ 'visual settings are unavailable, config values stay static',
44
+ )
45
+ }
46
+ return schema
47
+ }
48
+
49
+ /**
50
+ * 把 `loader/volatile-update` 的路径列表归成顶层字段名集合。
51
+ *
52
+ * 空路径 `[]` 表示整份 Config 都可能变了:返回 `null`(调用方按「全部重读」处理),
53
+ * 而不是一个空集合——空集合会被读成「什么都没变」,正好是相反的结论。
54
+ * @param {readonly (readonly string[])[] | undefined} paths 变更路径
55
+ * @returns {Set<string> | null} 顶层字段名;`null` = 全部
56
+ */
57
+ export function changedConfigKeys(paths) {
58
+ if (!Array.isArray(paths) || paths.length === 0) return null
59
+ const keys = new Set()
60
+ for (const path of paths) {
61
+ if (!Array.isArray(path) || path.length === 0) return null
62
+ keys.add(path[0])
63
+ }
64
+ return keys
65
+ }
package/src/util/fs.js CHANGED
@@ -70,6 +70,18 @@ export function writeJsonAtomic(file, data, { ensureDir = true } = {}) {
70
70
  }
71
71
  }
72
72
 
73
+ /**
74
+ * 删除文件并对 Windows 的瞬时占用(EPERM/EBUSY/EACCES)重试。
75
+ *
76
+ * 为什么需要:`unlinkSync` 和 `renameSync` 一样会被杀毒/索引器短暂占用。删除失败若被当成
77
+ * "已经没了",删除意图(`forget` / 索引清理)会被静默丢掉,下一次 load 时旧 shard 又会复活。
78
+ * @param {string} file - 目标文件。
79
+ * @throws 真实失败(ENOENT 之外且重试仍失败)时原样抛出。
80
+ */
81
+ export function unlinkWithRetry(file) {
82
+ return retryTransient(() => unlinkSync(file))
83
+ }
84
+
73
85
  /** 本机标识:锁的存活判定只在同机可信(跨机只能退回 mtime)。 */
74
86
  const LOCK_HOST = os.hostname()
75
87
  const LOCK_FILE = '.write.lock'
@@ -243,9 +255,9 @@ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000, hardSta
243
255
  if (lockIsStale(state, { staleMs, hardLimit, maxHoldMs })) {
244
256
  // 只删"刚刚读到的那个内容":两次读之间锁可能已被别人抢到并重写。
245
257
  try {
246
- if (readFileSync(file, 'utf8') === state.text) unlinkSync(file)
258
+ if (readFileSync(file, 'utf8') === state.text) unlinkWithRetry(file)
247
259
  } catch {
248
- // 已被别处回收
260
+ // 已被别处回收,或杀毒瞬时占用;下一轮继续判定
249
261
  }
250
262
  continue
251
263
  }
@@ -275,7 +287,24 @@ function releaseDirLock(file, token) {
275
287
  } else if (text.trim() !== String(process.pid)) {
276
288
  return
277
289
  }
278
- unlinkSync(file)
290
+ // 释放失败不能静默:锁文件还在、pid 又是自己,下一次 acquire 会把自己当成活锁
291
+ // (同机 pid 存活默认不回收,save 的 maxHoldMs 是 10 分钟),后续写入会被堵住。
292
+ // 先对 Windows 的 EPERM/EBUSY 做瞬时重试;仍删不掉就把内容改成 pid 0(死进程),
293
+ // 下一次 acquire 能立即判 stale,而不是等 10 分钟。
294
+ try {
295
+ unlinkWithRetry(file)
296
+ } catch {
297
+ try {
298
+ writeFileSync(file, JSON.stringify({
299
+ pid: 0,
300
+ host: LOCK_HOST,
301
+ token: 'released',
302
+ at: new Date().toISOString(),
303
+ }))
304
+ } catch {
305
+ // 连覆盖也失败:只能等 staleMs 兜底,不能因此抛给调用方
306
+ }
307
+ }
279
308
  } catch {
280
309
  // 已被回收或目录不可写:不影响调用方
281
310
  }
@@ -491,6 +520,8 @@ export function walkDir(root, opts = {}) {
491
520
  continue
492
521
  }
493
522
  for (const entry of entries) {
523
+ // 隐藏路径一律不进语料(与 listProjectFiles 的 git 分支同一口径):配置/状态/密钥
524
+ // (`.env`、`.ssh`)默认落在点文件里;作者真要索引就显式 `index_doc`。
494
525
  if (entry.name.startsWith('.')) continue
495
526
  const full = path.join(dir, entry.name)
496
527
  if (entry.isDirectory()) {
@@ -574,6 +605,11 @@ export function listProjectFiles(root, opts = {}) {
574
605
  const rel = String(raw).split(path.sep).join('/')
575
606
  if (!rel) continue
576
607
  const segs = rel.split('/')
608
+ // 与 walkDir 同一口径:隐藏路径(任一段以 `.` 开头)与内置忽略名单都不进语料。
609
+ // 两份清单必须一致,否则同一棵树在 `git init` 前后索引内容会变;隐藏路径默认是
610
+ // 配置/状态/密钥(`.env`、`.ssh`),非 git 目录没有"被跟踪=作者同意"这层信号。
611
+ // 真要索引某个隐藏文件,走显式 `index_doc`(它不受扫描清单限制)。
612
+ if (segs.some((s) => s.startsWith('.'))) continue
577
613
  if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
578
614
  const abs = path.join(root, rel)
579
615
  // 与 walkDir 同一判据:exclude 是子树级前缀。必须在 maxDepth 之前——被排除文件不该把
@@ -678,6 +714,17 @@ export function relativePath(root, filePath) {
678
714
  return path.relative(root, filePath).split(path.sep).join('/')
679
715
  }
680
716
 
717
+ /**
718
+ * 路径里是否有以 `.` 开头的段(与扫描口径一致):隐藏路径默认是配置/状态/密钥,
719
+ * 不进入自动索引面(显式 `index_doc` 仍可索引)。按 `/` 切分后逐段判断,
720
+ * 因此 `.env`、`.github/x.md`、`src/.cache/y.js` 都算隐藏。
721
+ * @param {string} relOrAbs 项目相对或绝对路径
722
+ * @returns {boolean}
723
+ */
724
+ export function isHiddenPath(relOrAbs) {
725
+ return String(relOrAbs || '').split(/[\\/]/).some((seg) => seg.startsWith('.'))
726
+ }
727
+
681
728
  /**
682
729
  * `insight.files` 的写入期归一:schema 承诺「项目相对路径」,不校验就会让项目外绝对路径原样落盘。
683
730
  * 规则:反斜杠 → `/`、去掉 `./`、去重;项目内绝对路径转相对;其余(项目外绝对、
@@ -703,13 +750,13 @@ export function normalizeCitationFiles(files, root) {
703
750
  let rel = value.replace(/^\.\//, '')
704
751
  if (abs !== null) {
705
752
  const inside = path.relative(base, abs)
706
- if (inside === '' || inside.startsWith('..') || path.isAbsolute(inside)) {
753
+ if (inside === '' || inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) {
707
754
  dropped.push(raw)
708
755
  continue
709
756
  }
710
757
  rel = inside.split(path.sep).join('/')
711
758
  }
712
- if (!rel || rel.startsWith('..')) {
759
+ if (!rel || rel === '..' || rel.startsWith('../')) {
713
760
  dropped.push(raw)
714
761
  continue
715
762
  }
@@ -1190,12 +1237,20 @@ export function assertSafeRoot(root, { requested = root, allowUnsafe = false, co
1190
1237
  throw new UnsafeRootError(root, requested, { rejection })
1191
1238
  }
1192
1239
 
1240
+ /**
1241
+ * 解析「当前工作目录」:显式 root 优先,但**相对路径按会话工作目录解析**,而不是宿主的
1242
+ * `process.cwd()`——web profile 里一个进程会服务多个会话,cd 之后两者的 cwd 不是一回事。
1243
+ * 没有显式 root 时返回会话工作目录本身;会话信息缺失(测试 / 老宿主)才退回进程 cwd。
1244
+ * @param {object|null} exec 宿主工具执行上下文(`exec.agent.session`)
1245
+ * @param {string|null} [explicitRoot] 工具参数里的 root,可为绝对或相对路径
1246
+ * @returns {string} 绝对路径
1247
+ */
1193
1248
  export function resolveIndexRoot(exec, explicitRoot) {
1194
- if (explicitRoot && explicitRoot.trim()) return path.resolve(explicitRoot)
1195
1249
  // 会话当前工作目录:0.2.1+ 读 workingDirectory 投影(cd 后会变),老宿主回退 header.cwd。
1196
1250
  const sessionCwd = sessionWorkingDir(exec?.agent?.session, { agent: exec?.agent })
1197
- if (sessionCwd) return path.resolve(sessionCwd)
1198
- return path.resolve(process.cwd())
1251
+ const base = sessionCwd ? path.resolve(sessionCwd) : path.resolve(process.cwd())
1252
+ if (explicitRoot && String(explicitRoot).trim()) return path.resolve(base, String(explicitRoot))
1253
+ return base
1199
1254
  }
1200
1255
 
1201
1256
  // ---------------------------------------------------------------------------
@@ -1238,7 +1293,7 @@ export function hasProjectMarker(dir) {
1238
1293
 
1239
1294
  function isInside(parent, child) {
1240
1295
  const rel = path.relative(parent, child)
1241
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
1296
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))
1242
1297
  }
1243
1298
 
1244
1299
  /** 显式登记的根里,包含该文件的**最深**那一个(最长前缀匹配)。 */
@@ -1375,10 +1430,11 @@ export function resolveProjectMemoryRoot(cwd, config) {
1375
1430
  export function resolveSafeIndexRoot(exec, explicitRoot, config) {
1376
1431
  const allowUnsafe = config?.allowUnsafeRoots === true
1377
1432
  const explicit = explicitRoot && String(explicitRoot).trim() ? String(explicitRoot) : null
1433
+ // 显式 root 也走 resolveIndexRoot:相对路径必须按**会话**工作目录解析(见该函数注释)。
1434
+ const cwd = resolveIndexRoot(exec, explicit)
1378
1435
  if (explicit) {
1379
- return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe, config })
1436
+ return assertSafeRoot(cwd, { requested: explicit, allowUnsafe, config })
1380
1437
  }
1381
- const cwd = resolveIndexRoot(exec)
1382
1438
  const root = resolveProjectMemoryRoot(cwd, config)
1383
1439
  if (root) return root
1384
1440
  // allowUnsafeRoots 只放开内置名单;cwd 被 deny / exclude / 文件系统根命中时仍然拒绝。
package/src/watch.js CHANGED
@@ -1,10 +1,30 @@
1
- import { existsSync } from 'node:fs'
1
+ import { existsSync, statSync } from 'node:fs'
2
2
  import { stat } from 'node:fs/promises'
3
3
  import path from 'node:path'
4
4
  import { listProjectFiles, memoryDirName, memoryRootFor, relativePath, rootRejection, scanLimits, storeKey } from './util/fs.js'
5
5
  import { OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
6
6
  import { ProjectMemoryStore } from './store.js'
7
7
  import { onFileChanged, isTypeScriptFile } from './enhancer.js'
8
+ import { cfgValue } from './util/config.js'
9
+ import { clearIndexFailure, recordIndexFailure } from './index-failures.js'
10
+
11
+ /**
12
+ * 把 `watch` / `watchInterval` 的**当前值**落到轮询器上。
13
+ *
14
+ * 这两个键是 volatile 字段:设置页保存后宿主会发 `loader/volatile-update`,插件不重启,
15
+ * 由这里按新值重排定时器。stop() 对没启动过的实例是空操作;start() 会按新间隔重算
16
+ * base/backoff/active 三个节拍。抽成函数是为了让"关掉后没有定时器、打开后按新间隔起"
17
+ * 这条契约可以被单测直接钉住(否则它只存在于 apply 的闭包里)。
18
+ * @param {WatchManager} watchManager 轮询器
19
+ * @param {object} config 插件 Config(volatile 字段是 ref)
20
+ * @returns {boolean} 当前是否在轮询
21
+ */
22
+ export function applyWatchSettings(watchManager, config) {
23
+ watchManager.stop()
24
+ if (cfgValue(config, 'watch') === false) return false
25
+ watchManager.start(Number(cfgValue(config, 'watchInterval')) * 1000)
26
+ return true
27
+ }
8
28
 
9
29
  /**
10
30
  * 有界并发 map。同步 `statSync` 循环在 Windows(尤其 WSL 挂 `/mnt/c`)会把事件循环卡住:
@@ -30,6 +50,12 @@ export class WatchManager {
30
50
  this.ctx = ctx
31
51
  this.config = config
32
52
  this.roots = new Map()
53
+ /**
54
+ * `storeKey(root)` → `roots` 里实际使用的写法。Windows/macOS 上大小写不同的路径是同一
55
+ * 物理目录:没有这层索引,同一个项目会被登记两次(每轮扫两遍),而 `watch_repo({watch:false})`
56
+ * 只删得掉其中一条。
57
+ */
58
+ this._rootsByKey = new Map()
33
59
  this.timer = null
34
60
  this._polling = false
35
61
  this._truncationWarned = new Set()
@@ -48,7 +74,7 @@ export class WatchManager {
48
74
  let best = null
49
75
  for (const root of this.roots.keys()) {
50
76
  const rel = path.relative(root, absPath)
51
- if (rel.startsWith('..') || path.isAbsolute(rel)) continue
77
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) continue
52
78
  if (!best || root.length > best.length) best = root
53
79
  }
54
80
  return best
@@ -76,7 +102,12 @@ export class WatchManager {
76
102
  dropped++
77
103
  continue
78
104
  }
79
- this.addRoot(root)
105
+ // 文件路径(历史遗留 / 手改 watch.json)也摘掉:addRoot 现在只接受目录。
106
+ // hasRoot 按大小写归一判定:磁盘上可能是另一种写法的同一条。
107
+ if (!this.addRoot(root) && !this.hasRoot(root)) {
108
+ store.removeWatch(root)
109
+ dropped++
110
+ }
80
111
  }
81
112
  if (dropped) store.save()
82
113
  }
@@ -85,9 +116,18 @@ export class WatchManager {
85
116
  addRoot(root) {
86
117
  // 根目录不存在就拒绝:否则每轮 poll 的 commit → save → mkdirSync 会把它重新「创建」出来。
87
118
  if (!existsSync(root)) return false
119
+ // 文件不是可轮询的根:readdir/listProjectFiles 会每轮失败,持久化后还会在启动时反复自愈。
120
+ try {
121
+ if (!statSync(root).isDirectory()) return false
122
+ } catch {
123
+ return false
124
+ }
88
125
  // 文件系统根 / 家目录 / 系统前缀 / roots.deny / roots.exclude 不整体监听(子目录允许),
89
126
  // 除非配置显式放行(仅内置名单可放行)。
90
127
  if (rootRejection(root, this.config)) return false
128
+ // 同一物理目录(大小写不敏感平台)不重复登记。
129
+ const key = storeKey(root)
130
+ if (this._rootsByKey.has(key)) return false
91
131
  if (!this.roots.has(root)) {
92
132
  // **不在这里 load()**:`restorePersisted()` 会对整条 watchlist 逐个 addRoot,急切读盘等于
93
133
  // 「watch 过多少个根,启动就同步读多少个 store 的全部 shard」。store 到 pollRoot 需要时才取。
@@ -96,11 +136,17 @@ export class WatchManager {
96
136
  // rel → 上次已上报的错误。坏文件每轮都会重试,逐轮打印会刷屏。
97
137
  failures: new Map(),
98
138
  })
139
+ this._rootsByKey.set(key, root)
99
140
  return true
100
141
  }
101
142
  return false
102
143
  }
103
144
 
145
+ /** 这个目录是否已在监视(大小写不敏感平台按归一后的路径判)。 */
146
+ hasRoot(root) {
147
+ return this._rootsByKey.has(storeKey(root))
148
+ }
149
+
104
150
  /**
105
151
  * 每个根**按需**取 store(命中 `storeCache` 即 O(1))。本类不长期持有实例:否则逐出对 watch
106
152
  * 根不省内存,真被逐出后 `load()` 还会再建一份,同一 root 出现两份互不可见的状态。内存上界
@@ -111,12 +157,17 @@ export class WatchManager {
111
157
  }
112
158
 
113
159
  removeRoot(root) {
160
+ const key = storeKey(root)
161
+ const actual = this._rootsByKey.get(key)
162
+ if (actual !== undefined) {
163
+ this._rootsByKey.delete(key)
164
+ return this.roots.delete(actual)
165
+ }
166
+ // 兜底:roots 可能被外部直接写过(诊断/测试),按原写法再试一次。
114
167
  return this.roots.delete(root)
115
168
  }
116
169
 
117
170
  start(intervalMs = 30000) {
118
- // 轮询进行中 `timer` 会短暂为 null;此时再 start 会排第二个定时器。等这一轮结束由 `_tick()` 自己续。
119
- if (this.timer || this._polling) return
120
171
  // 非法值(NaN/undefined)会让定时器退化成 1ms 轮询打满事件循环,故回退默认 30s。
121
172
  const raw = Number(intervalMs)
122
173
  this._baseInterval = Number.isFinite(raw) ? Math.max(raw, 1000) : 30000
@@ -127,7 +178,13 @@ export class WatchManager {
127
178
  // 不是"永不扫描"——外部编辑器改文件、或回合一直不结束(崩溃/长任务)时索引仍会自愈。
128
179
  this._activeInterval = Math.max(this._baseInterval * 10, 300000)
129
180
  this._interval = this._baseInterval
181
+ // 复位必须在 guard 之前:设置页保存走 stop() → start(),而 stop() 会把 _stopped 置 true。
182
+ // 如果轮询正在进行(_polling=true),这里的提前返回会留下 _stopped=true,那一轮 _tick() 收尾时
183
+ // 看到"已停止"就不再排下一轮——watch 永久停摆,且 applyWatchSettings() 还返回 true。
184
+ // 在飞的一轮结束时 _tick() 会按新的 _baseInterval/_activeInterval 续上。
130
185
  this._stopped = false
186
+ // 轮询进行中 `timer` 会短暂为 null;此时再 start 会排第二个定时器。等这一轮结束由 `_tick()` 自己续。
187
+ if (this.timer || this._polling) return
131
188
  this._schedule()
132
189
  }
133
190
 
@@ -154,7 +211,13 @@ export class WatchManager {
154
211
  if (next) {
155
212
  this._interval = this._activeInterval
156
213
  this._schedule(this._activeInterval)
157
- } else void this._tick() // 回合结束:立刻补扫,然后回到常规节拍
214
+ } else if (!this._polling) {
215
+ // 回合结束:立刻补扫,然后回到常规节拍。
216
+ // 如果已经有一轮 poll 在跑,不要在这里再起一轮:`poll()` 的 reentry guard 会把它当成
217
+ // "本轮无变化"(返回 false),`_tick()` 于是按无变化把间隔翻倍;在飞那轮真正结束时
218
+ // 又因为定时器已存在而降不回 base——回合结束的补扫被推迟到退避间隔之后。
219
+ void this._tick()
220
+ }
158
221
  }
159
222
 
160
223
  _schedule(interval = this._interval) {
@@ -286,9 +349,13 @@ export class WatchManager {
286
349
  state.failures.set(rel, err.message)
287
350
  console.error(`[dsh-project-memory] re-index failed for ${rel}: ${err.message}`)
288
351
  }
352
+ // 日志只打一次是防刷屏;账本每轮都刷新时间,index_repo / memory_stats 才看得见
353
+ // "这个文件现在仍然没进语料",而不是一条陈年记录。
354
+ recordIndexFailure(root, rel, err.message)
289
355
  continue
290
356
  }
291
357
  state.failures.delete(rel)
358
+ clearIndexFailure(root, rel)
292
359
  // 内容未变 / 体积超限也要落快照:否则 mtime:size 快路径永远命中不了,每次 poll 都要重读全仓。
293
360
  if (plan.key === UNCHANGED || plan.key === OVERSIZE) {
294
361
  // 内容没变、只有 mtime 变了:把新 mtime 写回条目,让下一轮(及其它入口)的快路径能命中。
@@ -312,7 +379,11 @@ export class WatchManager {
312
379
  // 扫全了才剪快照:删掉的文件不能留着,否则它以同样的 mtime:size 回来会被当成未变。
313
380
  if (!truncated) {
314
381
  for (const rel of Object.keys(state.snapshot)) if (!seen.has(rel)) delete state.snapshot[rel]
315
- for (const rel of state.failures.keys()) if (!seen.has(rel)) state.failures.delete(rel)
382
+ for (const rel of [...state.failures.keys()]) {
383
+ if (seen.has(rel)) continue
384
+ state.failures.delete(rel)
385
+ clearIndexFailure(root, rel)
386
+ }
316
387
  }
317
388
  const failed = new Set(stale)
318
389
  let applied = 0