@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.
@@ -1,7 +1,8 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import path from 'node:path'
3
- import { assertIndexRoot, assertSafeRoot, memoryRootFor, rootRejection, sessionMemoryRootOrNull } from '../util/fs.js'
3
+ import { assertIndexRoot, assertSafeRoot, memoryRootFor, resolveIndexRoot, rootRejection, sessionMemoryRootOrNull, storeKey } from '../util/fs.js'
4
4
  import { ProjectMemoryStore } from '../store.js'
5
+ import { cfgValue } from '../util/config.js'
5
6
 
6
7
  export function watchRepoTool(watchManager, config) {
7
8
  return defineTool({
@@ -12,7 +13,7 @@ export function watchRepoTool(watchManager, config) {
12
13
  root: {
13
14
  type: 'string',
14
15
  required: true,
15
- description: '项目根(绝对路径)',
16
+ description: '项目根(相对路径按会话当前工作目录解析)',
16
17
  },
17
18
  watch: {
18
19
  type: 'boolean',
@@ -24,7 +25,7 @@ export function watchRepoTool(watchManager, config) {
24
25
  render: (_args, value) => [{ type: 'text', text: value }],
25
26
  },
26
27
  async execute(args, exec) {
27
- const root = path.resolve(args.root)
28
+ const root = resolveIndexRoot(exec, args.root)
28
29
  // 不存在的根不写进 watchlist:watch 每轮会 commit → save → mkdirSync,把它重新造出来。
29
30
  // 根是**文件**时同样要拦:否则 save() 的 mkdirSync 会抛裸 ENOTDIR。
30
31
  // 家目录 / 系统目录 / Homebrew 前缀也不监听:整体轮询扫描会吃满内存(issue #5)。
@@ -45,7 +46,8 @@ export function watchRepoTool(watchManager, config) {
45
46
  // 会话根不可用(家目录/系统目录且无标记)时跳过镜像:那会在不该有项目记忆的目录里
46
47
  // 造出 watch.json,而 watch.json 一旦落在那里,下次以该目录为 cwd 启动又会把它读回来。
47
48
  if (!sessionRoot || !sessionMemoryDir) return
48
- if (path.resolve(sessionMemoryDir) === path.resolve(memoryDir)) return
49
+ // Windows/macOS 大小写不敏感:同一目录的两种写法不能当成两个 store 互相镜像。
50
+ if (storeKey(path.resolve(sessionMemoryDir)) === storeKey(path.resolve(memoryDir))) return
49
51
  const sessionStore = new ProjectMemoryStore(sessionMemoryDir).load()
50
52
  const removed = sessionStore.removeWatch(root)
51
53
  const added = present ? sessionStore.addWatch(root) : false
@@ -67,8 +69,9 @@ export function watchRepoTool(watchManager, config) {
67
69
  new ProjectMemoryStore(memoryDir).load().commit((s) => s.addWatch(root))
68
70
  await mirrorSessionWatchlist(true)
69
71
  watchManager.addRoot(root)
70
- watchManager.start(config.watchInterval * 1000)
71
- return `Watching ${root} (interval ${config.watchInterval}s). Docs/code changes will be re-indexed silently.`
72
+ const interval = Number(cfgValue(config, 'watchInterval'))
73
+ watchManager.start(interval * 1000)
74
+ return `Watching ${root} (interval ${interval}s). Docs/code changes will be re-indexed silently.`
72
75
  },
73
76
  })
74
- }
77
+ }
@@ -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 之前——被排除文件不该把
@@ -617,6 +653,42 @@ export function isGitIgnored(root, filePath) {
617
653
  }
618
654
  }
619
655
 
656
+ /**
657
+ * 批量版 `isGitIgnored`:一次 `git check-ignore --stdin` 判定一批相对路径。
658
+ * 逐个判定的成本几乎全在**起进程**上(9p 实测 30ms/次、ext4 2.7ms/次,Windows 上更高),
659
+ * 一次懒索引 flush 里往往十几个文件,必须并成一次。
660
+ *
661
+ * @param {string} root 项目根
662
+ * @param {string[]} rels 项目相对路径(`relativePath()` 的形状,`/` 分隔)
663
+ * @returns {Set<string>} 被忽略的那些 rel(原样返回,便于与调用方的 rel 对齐)
664
+ */
665
+ export function isGitIgnoredBatch(root, rels) {
666
+ const ignored = new Set()
667
+ if (!root || !rels || rels.length === 0) return ignored
668
+ if (!existsSync(path.join(root, '.git'))) return ignored
669
+ if (rels.length === 1) {
670
+ if (isGitIgnored(root, path.join(root, rels[0]))) ignored.add(rels[0])
671
+ return ignored
672
+ }
673
+ try {
674
+ // `-z` 让输入输出都以 NUL 分隔:文件名里带换行/空格也不会错位。
675
+ const out = execFileSync('git', ['-C', root, 'check-ignore', '--stdin', '-z'], {
676
+ input: rels.join('\0') + '\0',
677
+ windowsHide: true,
678
+ stdio: ['pipe', 'pipe', 'ignore'],
679
+ maxBuffer: 16 * 1024 * 1024,
680
+ })
681
+ for (const p of String(out).split('\0')) if (p) ignored.add(p)
682
+ return ignored
683
+ } catch (err) {
684
+ // status 1 = 正常:一条都没被忽略(check-ignore 用退出码表达"有/没有")。
685
+ if (err?.status === 1) return ignored
686
+ // 其它失败(老 git 不支持 --stdin、输入过长、非仓目录):退回逐条判定,语义不变,只是慢。
687
+ for (const rel of rels) if (isGitIgnored(root, path.join(root, rel))) ignored.add(rel)
688
+ return ignored
689
+ }
690
+ }
691
+
620
692
  export function isSupportedDoc(ext) {
621
693
  return ['.pdf', '.md', '.markdown', '.txt'].includes(ext)
622
694
  }
@@ -642,6 +714,17 @@ export function relativePath(root, filePath) {
642
714
  return path.relative(root, filePath).split(path.sep).join('/')
643
715
  }
644
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
+
645
728
  /**
646
729
  * `insight.files` 的写入期归一:schema 承诺「项目相对路径」,不校验就会让项目外绝对路径原样落盘。
647
730
  * 规则:反斜杠 → `/`、去掉 `./`、去重;项目内绝对路径转相对;其余(项目外绝对、
@@ -667,13 +750,13 @@ export function normalizeCitationFiles(files, root) {
667
750
  let rel = value.replace(/^\.\//, '')
668
751
  if (abs !== null) {
669
752
  const inside = path.relative(base, abs)
670
- if (inside === '' || inside.startsWith('..') || path.isAbsolute(inside)) {
753
+ if (inside === '' || inside === '..' || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) {
671
754
  dropped.push(raw)
672
755
  continue
673
756
  }
674
757
  rel = inside.split(path.sep).join('/')
675
758
  }
676
- if (!rel || rel.startsWith('..')) {
759
+ if (!rel || rel === '..' || rel.startsWith('../')) {
677
760
  dropped.push(raw)
678
761
  continue
679
762
  }
@@ -1154,12 +1237,20 @@ export function assertSafeRoot(root, { requested = root, allowUnsafe = false, co
1154
1237
  throw new UnsafeRootError(root, requested, { rejection })
1155
1238
  }
1156
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
+ */
1157
1248
  export function resolveIndexRoot(exec, explicitRoot) {
1158
- if (explicitRoot && explicitRoot.trim()) return path.resolve(explicitRoot)
1159
1249
  // 会话当前工作目录:0.2.1+ 读 workingDirectory 投影(cd 后会变),老宿主回退 header.cwd。
1160
1250
  const sessionCwd = sessionWorkingDir(exec?.agent?.session, { agent: exec?.agent })
1161
- if (sessionCwd) return path.resolve(sessionCwd)
1162
- 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
1163
1254
  }
1164
1255
 
1165
1256
  // ---------------------------------------------------------------------------
@@ -1202,7 +1293,7 @@ export function hasProjectMarker(dir) {
1202
1293
 
1203
1294
  function isInside(parent, child) {
1204
1295
  const rel = path.relative(parent, child)
1205
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
1296
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))
1206
1297
  }
1207
1298
 
1208
1299
  /** 显式登记的根里,包含该文件的**最深**那一个(最长前缀匹配)。 */
@@ -1230,17 +1321,29 @@ function resolveDir(dir) {
1230
1321
  }
1231
1322
  }
1232
1323
 
1324
+ /**
1325
+ * 根来源:显式登记的根 / VCS 标记 / 项目标记 / 会话工作目录兜底。
1326
+ * 调用方(懒索引的根缓存)据此区分"看到的标记"与"还没有标记时的推断"——只有前者能缓存。
1327
+ */
1328
+ export const ROOT_SOURCES = Object.freeze({
1329
+ EXTRA: 'extra',
1330
+ VCS: 'vcs',
1331
+ PROJECT: 'project',
1332
+ SESSION: 'session',
1333
+ })
1334
+
1233
1335
  /**
1234
1336
  * 自底向上找最近的根标记。**一次遍历同时看 VCS 与 PROJECT**,语义仍是 VCS 优先:
1235
1337
  * 先命中的 VCS 直接返回(它一定最深的);没有 VCS 就返回最深的 PROJECT。每层只 readdir
1236
1338
  * 一次(两组标记各走一遍祖先链、每个 marker 一次 existsSync 在 WSL/NTFS 上实测 ~119ms/次)。
1339
+ * @returns {{dir: string, source: 'vcs'|'project'}|null}
1237
1340
  */
1238
1341
  function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
1239
1342
  let project = null
1240
1343
  let dir = path.dirname(absPath)
1241
1344
  for (;;) {
1242
1345
  // 撞到危险根边界就停:不把边界当根,也不再向上。已记录的 PROJECT 命中仍有效(在边界下方)。
1243
- if (isUnsafe(dir)) return project
1346
+ if (isUnsafe(dir)) return project ? { dir: project, source: ROOT_SOURCES.PROJECT } : null
1244
1347
  let names = null
1245
1348
  try {
1246
1349
  names = new Set(readdirSync(dir))
@@ -1248,11 +1351,11 @@ function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
1248
1351
  names = null
1249
1352
  }
1250
1353
  if (names) {
1251
- if (vcsMarkers.some((marker) => names.has(marker))) return dir
1354
+ if (vcsMarkers.some((marker) => names.has(marker))) return { dir, source: ROOT_SOURCES.VCS }
1252
1355
  if (!project && projectMarkers.some((marker) => names.has(marker))) project = dir
1253
1356
  }
1254
1357
  const parent = path.dirname(dir)
1255
- if (parent === dir) return project
1358
+ if (parent === dir) return project ? { dir: project, source: ROOT_SOURCES.PROJECT } : null
1256
1359
  dir = parent
1257
1360
  }
1258
1361
  }
@@ -1260,13 +1363,17 @@ function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
1260
1363
  /**
1261
1364
  * 项目根推导(**只认标记与显式声明,绝不从文件路径兜底**)。`roots.exclude` 是最强的否定:
1262
1365
  * 文件落在被排除子树里 → 直接 null,不再向上找标记,也不退回会话工作目录。
1366
+ *
1367
+ * 比 `findProjectRoot` 多返回 `source`:调用方需要区分"看到的标记"和"没有标记时的会话目录兜底",
1368
+ * 二者不能同等缓存(见 `src/lazy.js` 的根缓存:兜底是"这一带还没有标记"的推断,项目可能刚建出来)。
1369
+ *
1263
1370
  * @param {string} filePath 目标文件(也接受目录内探针文件路径)
1264
1371
  * @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
1265
1372
  * config?: object, policy?: object }} [opts] `extraRoots` 显式登记的根;`sessionRoot` 作为**最后**一级推定。
1266
- * @returns {string|null}
1373
+ * @returns {{root: string|null, source: 'extra'|'vcs'|'project'|'session'|null}}
1267
1374
  */
1268
- export function findProjectRoot(filePath, opts = {}) {
1269
- if (typeof filePath !== 'string' || !filePath) return null
1375
+ export function findProjectRootWithSource(filePath, opts = {}) {
1376
+ if (typeof filePath !== 'string' || !filePath) return { root: null, source: null }
1270
1377
  const policy = isCompiledRootPolicy(opts.policy)
1271
1378
  ? opts.policy
1272
1379
  : isCompiledRootPolicy(opts.config)
@@ -1279,19 +1386,32 @@ export function findProjectRoot(filePath, opts = {}) {
1279
1386
  try {
1280
1387
  abs = path.resolve(filePath)
1281
1388
  } catch {
1282
- return null
1389
+ return { root: null, source: null }
1283
1390
  }
1284
- if (excludedEntryForAbs(abs, policy)) return null
1391
+ if (excludedEntryForAbs(abs, policy)) return { root: null, source: null }
1285
1392
  const explicit = longestRootContaining(opts.extraRoots || [], abs)
1286
- if (explicit) return isUnsafe(explicit) ? null : explicit
1393
+ if (explicit) {
1394
+ return isUnsafe(explicit) ? { root: null, source: null } : { root: explicit, source: ROOT_SOURCES.EXTRA }
1395
+ }
1287
1396
 
1288
1397
  // 标记优先于会话根兜底;VCS 优先于 PROJECT("a marker above the cwd still wins" 是既有契约)。
1289
1398
  const byMarker = nearestRootByMarkers(abs, VCS_MARKERS, PROJECT_MARKERS, isUnsafe)
1290
- if (byMarker) return byMarker
1399
+ if (byMarker) return { root: byMarker.dir, source: byMarker.source }
1291
1400
 
1292
1401
  const session = resolveDir(opts.sessionRoot)
1293
- if (session && !isUnsafe(session) && isInside(session, abs)) return session
1294
- return null
1402
+ if (session && !isUnsafe(session) && isInside(session, abs)) return { root: session, source: ROOT_SOURCES.SESSION }
1403
+ return { root: null, source: null }
1404
+ }
1405
+
1406
+ /**
1407
+ * 项目根推导:只要根,语义与 `findProjectRootWithSource` 完全一致。
1408
+ * @param {string} filePath 目标文件(也接受目录内探针文件路径)
1409
+ * @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
1410
+ * config?: object, policy?: object }} [opts]
1411
+ * @returns {string|null}
1412
+ */
1413
+ export function findProjectRoot(filePath, opts = {}) {
1414
+ return findProjectRootWithSource(filePath, opts).root
1295
1415
  }
1296
1416
 
1297
1417
  /**
@@ -1310,10 +1430,11 @@ export function resolveProjectMemoryRoot(cwd, config) {
1310
1430
  export function resolveSafeIndexRoot(exec, explicitRoot, config) {
1311
1431
  const allowUnsafe = config?.allowUnsafeRoots === true
1312
1432
  const explicit = explicitRoot && String(explicitRoot).trim() ? String(explicitRoot) : null
1433
+ // 显式 root 也走 resolveIndexRoot:相对路径必须按**会话**工作目录解析(见该函数注释)。
1434
+ const cwd = resolveIndexRoot(exec, explicit)
1313
1435
  if (explicit) {
1314
- return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe, config })
1436
+ return assertSafeRoot(cwd, { requested: explicit, allowUnsafe, config })
1315
1437
  }
1316
- const cwd = resolveIndexRoot(exec)
1317
1438
  const root = resolveProjectMemoryRoot(cwd, config)
1318
1439
  if (root) return root
1319
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) {
@@ -278,6 +341,7 @@ export class WatchManager {
278
341
  record,
279
342
  existingEntries: store.entries[rel],
280
343
  size: stats.size,
344
+ mtimeMs: stats.mtimeMs,
281
345
  })
282
346
  } catch (err) {
283
347
  // 坏文件每轮都会重试:同一个文件的同一个错误只上报一次,否则逐轮刷屏。
@@ -285,11 +349,17 @@ export class WatchManager {
285
349
  state.failures.set(rel, err.message)
286
350
  console.error(`[dsh-project-memory] re-index failed for ${rel}: ${err.message}`)
287
351
  }
352
+ // 日志只打一次是防刷屏;账本每轮都刷新时间,index_repo / memory_stats 才看得见
353
+ // "这个文件现在仍然没进语料",而不是一条陈年记录。
354
+ recordIndexFailure(root, rel, err.message)
288
355
  continue
289
356
  }
290
357
  state.failures.delete(rel)
358
+ clearIndexFailure(root, rel)
291
359
  // 内容未变 / 体积超限也要落快照:否则 mtime:size 快路径永远命中不了,每次 poll 都要重读全仓。
292
360
  if (plan.key === UNCHANGED || plan.key === OVERSIZE) {
361
+ // 内容没变、只有 mtime 变了:把新 mtime 写回条目,让下一轮(及其它入口)的快路径能命中。
362
+ if (plan.key === UNCHANGED && typeof plan.mtimeMs === 'number') store.refreshMtime(rel, plan.mtimeMs)
293
363
  state.snapshot[rel] = sig
294
364
  continue
295
365
  }
@@ -309,7 +379,11 @@ export class WatchManager {
309
379
  // 扫全了才剪快照:删掉的文件不能留着,否则它以同样的 mtime:size 回来会被当成未变。
310
380
  if (!truncated) {
311
381
  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)
382
+ for (const rel of [...state.failures.keys()]) {
383
+ if (seen.has(rel)) continue
384
+ state.failures.delete(rel)
385
+ clearIndexFailure(root, rel)
386
+ }
313
387
  }
314
388
  const failed = new Set(stale)
315
389
  let applied = 0