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

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +162 -8
  2. package/README.md +44 -26
  3. package/README.zh-CN.md +42 -24
  4. package/client/client.js +272 -138
  5. package/client/client.js.map +1 -1
  6. package/cordis.patch.yml +6 -1
  7. package/package.json +3 -2
  8. package/scripts/bench-synthetic.mjs +22 -11
  9. package/src/audit.js +36 -32
  10. package/src/auto-inject.js +55 -32
  11. package/src/client/MemoryView.tsx +72 -4
  12. package/src/client/ShowTaskPanelNode.tsx +8 -5
  13. package/src/client/TaskCommandNode.tsx +22 -17
  14. package/src/client/TaskComponents.tsx +18 -3
  15. package/src/client/TaskPanel.tsx +50 -85
  16. package/src/client/client.ts +26 -6
  17. package/src/client/commands.ts +67 -0
  18. package/src/client/task-ui-store.ts +15 -2
  19. package/src/commands/insight-actions.js +1 -1
  20. package/src/commands/task-actions.js +57 -3
  21. package/src/commands/tasks.js +1 -1
  22. package/src/index.js +29 -11
  23. package/src/insight-store.js +200 -78
  24. package/src/lazy.js +7 -3
  25. package/src/ops.js +1 -1
  26. package/src/readiness.js +1 -1
  27. package/src/recall.js +76 -30
  28. package/src/setup/taskbridge.js +37 -6
  29. package/src/store.js +315 -44
  30. package/src/tools/forget.js +11 -8
  31. package/src/tools/index-doc.js +14 -8
  32. package/src/tools/index-repo.js +10 -11
  33. package/src/tools/lesson-tools.js +25 -35
  34. package/src/tools/query-memory.js +81 -28
  35. package/src/tools/remember.js +14 -11
  36. package/src/tools/stats.js +26 -3
  37. package/src/tools/task-tools.js +11 -12
  38. package/src/tools/watch-repo.js +6 -8
  39. package/src/types.js +9 -4
  40. package/src/util/fs.js +502 -37
  41. package/src/util/search.js +6 -27
  42. package/src/vector-index.js +175 -22
  43. package/src/watch.js +15 -10
package/src/util/fs.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
- accessSync, constants, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync,
2
+ accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync,
3
3
  unlinkSync, writeFileSync,
4
4
  } from 'node:fs'
5
+ import { execFileSync } from 'node:child_process'
5
6
  import { readFile } from 'node:fs/promises'
6
7
  import { createHash } from 'node:crypto'
7
8
  import os from 'node:os'
@@ -37,6 +38,53 @@ export function writeJsonAtomic(file, data) {
37
38
  }
38
39
  }
39
40
 
41
+ /**
42
+ * 目录级写锁(跨进程)。写入前短暂持有,读改写之间不会交错。
43
+ * 锁文件是 `.write.lock`;崩溃留下的锁超过 staleMs 自动清掉。
44
+ * @param {string} dir 目标目录(不存在则创建)
45
+ * @param {{timeoutMs?: number, staleMs?: number}} [opts]
46
+ * @returns {null | (() => void)} 释放函数;拿不到锁返回 null
47
+ */
48
+ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000 } = {}) {
49
+ try {
50
+ mkdirSync(dir, { recursive: true })
51
+ } catch {
52
+ return null
53
+ }
54
+ const file = path.join(dir, '.write.lock')
55
+ const deadline = Date.now() + timeoutMs
56
+ const sleeper = new Int32Array(new SharedArrayBuffer(4))
57
+ for (;;) {
58
+ try {
59
+ const fd = openSync(file, 'wx')
60
+ try {
61
+ writeFileSync(fd, String(process.pid))
62
+ } finally {
63
+ closeSync(fd)
64
+ }
65
+ return () => {
66
+ try {
67
+ unlinkSync(file)
68
+ } catch {
69
+ // 已被 stale 清理或目录不可写:不影响写入结果
70
+ }
71
+ }
72
+ } catch (err) {
73
+ if (err?.code !== 'EEXIST') return null
74
+ try {
75
+ if (Date.now() - statSync(file).mtimeMs > staleMs) {
76
+ unlinkSync(file)
77
+ continue
78
+ }
79
+ } catch {
80
+ // 锁刚好被释放:下一轮重试
81
+ }
82
+ if (Date.now() >= deadline) return null
83
+ Atomics.wait(sleeper, 0, 0, 10)
84
+ }
85
+ }
86
+ }
87
+
40
88
  export function assertReadableFile(filePath, maxFileSizeMb) {
41
89
  if (typeof filePath !== 'string' || !filePath) {
42
90
  throw new Error('file_path must be a non-empty string')
@@ -223,6 +271,12 @@ export function walkDir(root, opts = {}) {
223
271
  // 扫描也该同意这一点;否则父根会把子项目的全部内容再存一份(实测一个父目录
224
272
  // 的 store 里 9075/9081 个文件是子根 store 的重复副本)。
225
273
  const nestedStoreName = opts.nestedStoreName || null
274
+ // `roots.exclude` 是子树级前缀匹配:命中的目录整棵剪掉,命中的文件直接不收。
275
+ const policy = isCompiledRootPolicy(opts.policy)
276
+ ? opts.policy
277
+ : isCompiledRootPolicy(opts.config)
278
+ ? opts.config
279
+ : opts.config ? compileRootPolicy(opts.config) : null
226
280
  const out = []
227
281
  const skipped = []
228
282
  const unreadable = []
@@ -247,6 +301,7 @@ export function walkDir(root, opts = {}) {
247
301
  const full = path.join(dir, entry.name)
248
302
  if (entry.isDirectory()) {
249
303
  if (ignoreNames.has(entry.name)) continue
304
+ if (policy && excludedEntryForAbs(full, policy)) continue
250
305
  if (nestedStoreName && hasOwnStore(full, nestedStoreName)) {
251
306
  skipped.push(full)
252
307
  continue
@@ -258,6 +313,7 @@ export function walkDir(root, opts = {}) {
258
313
  }
259
314
  stack.push([full, depth + 1])
260
315
  } else {
316
+ if (policy && excludedEntryForAbs(full, policy)) continue
261
317
  if (out.length >= maxFiles) {
262
318
  truncated = true
263
319
  capped = true
@@ -275,6 +331,94 @@ export function walkDir(root, opts = {}) {
275
331
  return { files: out, truncated, capped, skipped, unreadable }
276
332
  }
277
333
 
334
+ /**
335
+ * git 工作区文件(已跟踪 + 未跟踪且未被忽略);git 不可用/不是仓库时返回 null。
336
+ * `--exclude-standard` 让嵌套 `.gitignore` 也生效,构建产物与内部文档不会再进语料。
337
+ * @param {string} root 项目根
338
+ * @returns {string[]|null} 仓库相对路径(`/` 分隔)
339
+ */
340
+ function gitListedFiles(root) {
341
+ try {
342
+ const out = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
343
+ encoding: 'utf8',
344
+ maxBuffer: 64 * 1024 * 1024,
345
+ stdio: ['ignore', 'pipe', 'ignore'],
346
+ })
347
+ return out.split('\0').filter(Boolean)
348
+ } catch {
349
+ return null
350
+ }
351
+ }
352
+
353
+ /**
354
+ * 项目文件清单:git 仓库走 `git ls-files`(尊重 `.gitignore` 与嵌套规则),
355
+ * 非 git 目录回退 {@link walkDir}。返回形状与 walkDir 一致,调用方无需分支。
356
+ * @param {string} root 项目根
357
+ * @param {object} [opts] 同 walkDir,另加 `gitAware: false` 强制走 walkDir
358
+ * @returns {{files: string[], truncated: boolean, capped: boolean, skipped: string[], unreadable: string[]}}
359
+ */
360
+ export function listProjectFiles(root, opts = {}) {
361
+ const policy = isCompiledRootPolicy(opts.policy)
362
+ ? opts.policy
363
+ : isCompiledRootPolicy(opts.config)
364
+ ? opts.config
365
+ : opts.config ? compileRootPolicy(opts.config) : null
366
+ const listed = opts.gitAware === false ? null : gitListedFiles(root)
367
+ if (listed === null) return walkDir(root, opts)
368
+ const maxFiles = Number.isFinite(opts.maxFiles) && opts.maxFiles > 0 ? opts.maxFiles : Infinity
369
+ const maxDepth = Number.isFinite(opts.maxDepth) && opts.maxDepth > 0 ? opts.maxDepth : Infinity
370
+ const nestedName = opts.nestedStoreName || null
371
+ const nested = nestedName
372
+ ? nestedStoreRoots(root, nestedName).map((p) => relativePath(root, p))
373
+ : []
374
+ const files = []
375
+ const skipped = new Set()
376
+ let capped = false
377
+ for (const raw of listed) {
378
+ const rel = String(raw).split(path.sep).join('/')
379
+ if (!rel) continue
380
+ const segs = rel.split('/')
381
+ if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
382
+ const abs = path.join(root, rel)
383
+ // 与 walkDir 同一判据:exclude 是子树级前缀,git 清单里的文件同样要过这一关。
384
+ // 这一步必须在 maxDepth 之前:被排除文件不该把扫描标成 truncated(否则本轮
385
+ // 不会清理"未见到的旧条目",排除规则反而让旧索引留在盘上)。
386
+ if (policy && excludedEntryForAbs(abs, policy)) continue
387
+ if (segs.length > maxDepth) {
388
+ capped = true
389
+ continue
390
+ }
391
+ const under = nested.find((n) => rel === n || rel.startsWith(`${n}/`))
392
+ if (under) {
393
+ skipped.add(path.join(root, under))
394
+ continue
395
+ }
396
+ if (files.length >= maxFiles) {
397
+ capped = true
398
+ break
399
+ }
400
+ try {
401
+ if (!statSync(abs).isFile()) continue
402
+ } catch {
403
+ continue
404
+ }
405
+ files.push(abs)
406
+ }
407
+ files.sort()
408
+ return { files, truncated: capped, capped, skipped: [...skipped].sort(), unreadable: [] }
409
+ }
410
+
411
+ /** 单个文件是否被 git 忽略(仅 git 仓库;非 git 目录返回 false)。 */
412
+ export function isGitIgnored(root, filePath) {
413
+ if (!root || !filePath || !existsSync(path.join(root, '.git'))) return false
414
+ try {
415
+ execFileSync('git', ['-C', root, 'check-ignore', '-q', '--', relativePath(root, filePath)], { stdio: 'ignore' })
416
+ return true
417
+ } catch {
418
+ return false
419
+ }
420
+ }
421
+
278
422
  export function isSupportedDoc(ext) {
279
423
  return ['.pdf', '.md', '.markdown', '.txt'].includes(ext)
280
424
  }
@@ -488,57 +632,363 @@ const UNSAFE = collectUnsafeRootSets()
488
632
  const UNSAFE_DIRS = UNSAFE.unsafe
489
633
  const SHARED_TEMP_DIRS = UNSAFE.sharedTemp
490
634
 
491
- /** 判定依据文案:用于拒绝时告诉用户「为什么是它」。 */
492
- function unsafeReason(abs) {
493
- const key = storeKey(abs)
494
- const parsed = path.parse(abs)
495
- if (abs === parsed.root) return 'the filesystem root'
496
- let home = null
635
+ // ---------------------------------------------------------------------------
636
+ // 用户可配置的根名单(`roots.allow` / `roots.deny` / `roots.exclude`)。
637
+ //
638
+ // 三个字段的匹配口径刻意不同,别合并成一个:
639
+ // - allow / deny:**精确匹配**,只针对目录本身。`deny: /srv/shared` 不拒绝
640
+ // `/srv/shared/myproj`——它自己是一个合法项目根。
641
+ // - exclude:**路径边界前缀匹配**,整棵子树都算。子树里的文件一律不进索引,
642
+ // 也不能在这棵子树里推出新的项目根。
643
+ //
644
+ // 优先级:exclude > deny > allow > 内置名单。`allowUnsafeRoots: true` 保留为兼容,
645
+ // 只放开**内置名单**;deny / exclude 仍然优先。文件系统根永远不能当根(allow 也不行)。
646
+ // ---------------------------------------------------------------------------
647
+
648
+ const ROOT_POLICY_FIELDS = ['allow', 'deny', 'exclude']
649
+
650
+ /** 每条告警只打一次:配置在进程内是静态的,重复刷屏没有信息量。 */
651
+ const warnedRootPolicyEntries = new Set()
652
+
653
+ function warnRootPolicyOnce(key, message, warn) {
654
+ if (warnedRootPolicyEntries.has(key)) return
655
+ warnedRootPolicyEntries.add(key)
656
+ const log = typeof warn === 'function' ? warn : console.error
657
+ log(`[dsh-project-memory] ${message}`)
658
+ }
659
+
660
+ function expandHomeEntry(value, home, pathApi) {
661
+ if (value === '~') return home
662
+ if (value.startsWith('~/') || value.startsWith('~\\')) {
663
+ return home ? pathApi.resolve(home, value.slice(2)) : null
664
+ }
665
+ return value
666
+ }
667
+
668
+ function normalizeRootPolicyEntries(list, field, { platform, pathApi, home, warn }) {
669
+ const out = []
670
+ if (list === undefined || list === null) return out
671
+ if (!Array.isArray(list)) {
672
+ warnRootPolicyOnce(
673
+ `shape:${field}`,
674
+ `config.roots.${field} must be an array of absolute paths; ignoring it.`,
675
+ warn,
676
+ )
677
+ return out
678
+ }
679
+ for (const raw of list) {
680
+ if (typeof raw !== 'string') {
681
+ warnRootPolicyOnce(
682
+ `type:${field}:${typeof raw}`,
683
+ `config.roots.${field} contains a non-string entry; ignoring it (only absolute path strings are accepted).`,
684
+ warn,
685
+ )
686
+ continue
687
+ }
688
+ const value = raw.trim()
689
+ if (!value) continue
690
+ const expanded = expandHomeEntry(value, home, pathApi)
691
+ if (expanded === null) {
692
+ warnRootPolicyOnce(
693
+ `home:${field}:${value}`,
694
+ `config.roots.${field} entry ${JSON.stringify(value)} cannot be expanded: the home directory is unavailable.`,
695
+ warn,
696
+ )
697
+ continue
698
+ }
699
+ if (!pathApi.isAbsolute(expanded)) {
700
+ warnRootPolicyOnce(
701
+ `relative:${field}:${value}`,
702
+ `config.roots.${field} entry ignored (not an absolute path): ${JSON.stringify(value)}. ` +
703
+ 'Relative paths would be resolved against the host cwd and are unpredictable; use an absolute path or ~/...',
704
+ warn,
705
+ )
706
+ continue
707
+ }
708
+ let abs
709
+ try {
710
+ abs = pathApi.resolve(expanded)
711
+ } catch {
712
+ warnRootPolicyOnce(
713
+ `resolve:${field}:${value}`,
714
+ `config.roots.${field} entry ignored (cannot be resolved): ${JSON.stringify(value)}.`,
715
+ warn,
716
+ )
717
+ continue
718
+ }
719
+ out.push({ abs, key: storeKey(abs, platform), raw: value })
720
+ }
721
+ return out
722
+ }
723
+
724
+ function isCompiledRootPolicy(value) {
725
+ return Boolean(value && typeof value === 'object' && value.__rootPolicy === true)
726
+ }
727
+
728
+ /**
729
+ * 把插件 config 编译成一份可复用的根判定策略。
730
+ *
731
+ * 参数化(platform / pathApi / home / env)是为了在任意平台上验证 Windows 语义,
732
+ * 与 `collectUnsafeRootSets()` 的测试惯例一致;生产路径只用无参形式。
733
+ *
734
+ * @param {object} [config] 插件 config(只读 `config.roots` 与 `config.allowUnsafeRoots`)
735
+ * @param {{platform?: string, pathApi?: object, home?: string|null, env?: object, warn?: Function,
736
+ * allowUnsafe?: boolean, unsafeDirs?: Set<string>, sharedTemp?: Set<string>}} [opts]
737
+ * @returns {object} 策略对象(内部结构,调用方应通过 rootRejection/isUnsafeRoot/isExcludedPath 使用)
738
+ */
739
+ export function compileRootPolicy(config, opts = {}) {
740
+ const platform = opts.platform || process.platform
741
+ const pathApi = opts.pathApi || path
742
+ const home = Object.prototype.hasOwnProperty.call(opts, 'home') ? opts.home : safeHomedir()
743
+ const warn = opts.warn
744
+ const rawRoots = config && typeof config === 'object' ? config.roots : undefined
745
+ const roots = rawRoots && typeof rawRoots === 'object' && !Array.isArray(rawRoots) ? rawRoots : {}
746
+ if (rawRoots !== undefined && (typeof rawRoots !== 'object' || rawRoots === null || Array.isArray(rawRoots))) {
747
+ warnRootPolicyOnce(
748
+ 'shape:roots',
749
+ 'config.roots must be an object with `allow` / `deny` / `exclude` arrays; ignoring it.',
750
+ warn,
751
+ )
752
+ }
753
+
754
+ const entries = {}
755
+ for (const field of ROOT_POLICY_FIELDS) {
756
+ entries[field] = normalizeRootPolicyEntries(roots[field], field, { platform, pathApi, home, warn })
757
+ }
758
+
759
+ let builtin = opts.unsafeDirs || null
760
+ let sharedTemp = opts.sharedTemp || null
761
+ if (!builtin || !sharedTemp) {
762
+ // 只有"完全没传模拟参数"时才复用模块级集合。只要显式给了 platform / pathApi /
763
+ // home / tmp / env 中的任一个,就按这些参数重算——否则在 Linux 上模拟 Windows
764
+ // 或换一个 home 时,内置名单会悄悄沿用当前机器的那一份。
765
+ const simulated = ['platform', 'pathApi', 'home', 'tmp', 'env'].some((key) =>
766
+ Object.prototype.hasOwnProperty.call(opts, key),
767
+ )
768
+ if (!simulated && platform === process.platform) {
769
+ builtin = builtin || UNSAFE_DIRS
770
+ sharedTemp = sharedTemp || SHARED_TEMP_DIRS
771
+ } else {
772
+ const sets = collectUnsafeRootSets({
773
+ platform,
774
+ home,
775
+ tmp: Object.prototype.hasOwnProperty.call(opts, 'tmp') ? opts.tmp : os.tmpdir(),
776
+ env: opts.env || process.env,
777
+ pathApi,
778
+ })
779
+ builtin = builtin || sets.unsafe
780
+ sharedTemp = sharedTemp || sets.sharedTemp
781
+ }
782
+ }
783
+
784
+ const allowEntries = new Map(entries.allow.map((e) => [e.key, e.raw]))
785
+ const denyEntries = new Map(entries.deny.map((e) => [e.key, e.raw]))
786
+ return {
787
+ __rootPolicy: true,
788
+ platform,
789
+ pathApi,
790
+ home,
791
+ allowUnsafeRoots: config?.allowUnsafeRoots === true || opts.allowUnsafe === true,
792
+ allow: new Set(allowEntries.keys()),
793
+ deny: new Set(denyEntries.keys()),
794
+ exclude: entries.exclude,
795
+ allowEntries,
796
+ denyEntries,
797
+ builtin,
798
+ sharedTemp,
799
+ }
800
+ }
801
+
802
+ function policyFor(configOrPolicy, opts) {
803
+ if (isCompiledRootPolicy(configOrPolicy)) return configOrPolicy
804
+ return compileRootPolicy(configOrPolicy, opts)
805
+ }
806
+
807
+ /** `parent` 是否等于 `child` 或它的祖先(按路径分隔符,含子树)。 */
808
+ function isInsideKey(parentKey, childKey, sep) {
809
+ if (parentKey === childKey) return true
810
+ const prefix = parentKey.endsWith(sep) ? parentKey : `${parentKey}${sep}`
811
+ return childKey.startsWith(prefix)
812
+ }
813
+
814
+ function excludedEntryForAbs(abs, policy) {
815
+ if (!policy.exclude.length) return null
816
+ let absResolved
497
817
  try {
498
- home = storeKey(path.resolve(os.homedir()))
818
+ absResolved = policy.pathApi.resolve(abs)
499
819
  } catch {
500
- home = null
820
+ return null
501
821
  }
502
- if (home && key === home) return 'your home directory'
503
- if (SHARED_TEMP_DIRS.has(key)) return 'the shared temp directory'
822
+ const key = storeKey(absResolved, policy.platform)
823
+ for (const entry of policy.exclude) {
824
+ if (isInsideKey(entry.key, key, policy.pathApi.sep)) return entry
825
+ }
826
+ return null
827
+ }
828
+
829
+ /**
830
+ * 某个文件/目录是否落在 `roots.exclude` 的子树里。
831
+ * @returns {{abs: string, key: string, raw: string}|null} 命中的条目(用于报告),否则 null
832
+ */
833
+ export function excludedEntryForPath(filePath, configOrPolicy, opts) {
834
+ if (typeof filePath !== 'string' || !filePath) return null
835
+ const policy = policyFor(configOrPolicy, opts)
836
+ let abs
837
+ try {
838
+ abs = policy.pathApi.resolve(filePath)
839
+ } catch {
840
+ return null
841
+ }
842
+ return excludedEntryForAbs(abs, policy)
843
+ }
844
+
845
+ /** 文案用的「为什么是它」。 */
846
+ function unsafeReason(abs, policy = {}) {
847
+ const platform = policy.platform || process.platform
848
+ const pathApi = policy.pathApi || path
849
+ const key = storeKey(abs, platform)
850
+ const parsed = pathApi.parse(abs)
851
+ if (key === storeKey(parsed.root, platform)) return 'the filesystem root'
852
+ if (policy.home) {
853
+ try {
854
+ if (key === storeKey(pathApi.resolve(policy.home), platform)) return 'your home directory'
855
+ } catch {
856
+ // 家目录不可解析:继续按临时/系统目录归类
857
+ }
858
+ } else {
859
+ try {
860
+ if (key === storeKey(path.resolve(os.homedir()), platform)) return 'your home directory'
861
+ } catch {
862
+ // 同上
863
+ }
864
+ }
865
+ const shared = policy.sharedTemp || SHARED_TEMP_DIRS
866
+ if (shared.has(key)) return 'the shared temp directory'
504
867
  return 'a system directory that is never a project root'
505
868
  }
506
869
 
507
- /** 这个目录能否当项目记忆根?纯判定,无副作用。 */
508
- export function isUnsafeRoot(root) {
509
- if (typeof root !== 'string' || !root) return true
870
+ /**
871
+ * 根判定的**唯一实现**:返回 null(可用)或一条命中记录。
872
+ *
873
+ * 命中记录带 `kind` / `field` / `entry` / `reason`,调用方据此生成"是哪条命中的、
874
+ * 该改哪个字段"的拒绝文案。优先级在这里一眼可见:exclude → deny → 内置(allow
875
+ * 与 allowUnsafeRoots 只作用于内置名单)→ 文件系统根永远拒绝。
876
+ *
877
+ * @param {string} root 候选根
878
+ * @param {object} [configOrPolicy] 插件 config,或 `compileRootPolicy()` 的返回值
879
+ */
880
+ export function rootRejection(root, configOrPolicy, opts) {
881
+ const policy = policyFor(configOrPolicy, opts)
882
+ if (typeof root !== 'string' || !root) {
883
+ return { kind: 'invalid', field: null, entry: null, reason: 'not a usable directory path' }
884
+ }
510
885
  let abs
511
886
  try {
512
- abs = path.resolve(root)
887
+ abs = policy.pathApi.resolve(root)
513
888
  } catch {
514
- return true
889
+ return { kind: 'invalid', field: null, entry: null, reason: 'not a usable directory path' }
890
+ }
891
+ const platform = policy.platform
892
+ const key = storeKey(abs, platform)
893
+ const parsed = policy.pathApi.parse(abs)
894
+ if (!parsed.dir || key === storeKey(parsed.root, platform)) {
895
+ return { kind: 'filesystem-root', abs, field: null, entry: null, reason: 'the filesystem root' }
896
+ }
897
+ const excluded = excludedEntryForAbs(abs, policy)
898
+ if (excluded) {
899
+ return {
900
+ kind: 'exclude',
901
+ abs,
902
+ field: 'roots.exclude',
903
+ entry: excluded.raw,
904
+ reason: `inside the subtree excluded by ${JSON.stringify(excluded.raw)}`,
905
+ }
906
+ }
907
+ if (policy.deny.has(key)) {
908
+ return {
909
+ kind: 'deny',
910
+ abs,
911
+ field: 'roots.deny',
912
+ entry: policy.denyEntries.get(key) || null,
913
+ reason: 'listed in roots.deny',
914
+ }
915
+ }
916
+ if (policy.builtin.has(key) && !policy.allowUnsafeRoots && !policy.allow.has(key)) {
917
+ return { kind: 'builtin', abs, field: 'roots.allow', entry: null, reason: unsafeReason(abs, policy) }
918
+ }
919
+ return null
920
+ }
921
+
922
+ /** 这个目录能否当项目记忆根?纯判定,无副作用。 */
923
+ export function isUnsafeRoot(root, configOrPolicy, opts) {
924
+ return rootRejection(root, configOrPolicy, opts) !== null
925
+ }
926
+
927
+ const CONFIG_LOCATION = 'under `- id: project-memory` → `config:`'
928
+
929
+ /** 把命中记录变成一句可执行的拒绝文案。 */
930
+ function rootRejectionMessage(target, rejection) {
931
+ const head = `Refusing to use ${target} as a project memory root: `
932
+ switch (rejection.kind) {
933
+ case 'filesystem-root':
934
+ return (
935
+ head +
936
+ 'it is the filesystem root. That can never be a project memory root; pass a project directory instead.'
937
+ )
938
+ case 'exclude':
939
+ return (
940
+ head +
941
+ `it is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(rejection.entry)}. ` +
942
+ `Remove that entry from \`config.roots.exclude\` ${CONFIG_LOCATION} if this directory should be a root.`
943
+ )
944
+ case 'deny':
945
+ return (
946
+ head +
947
+ `it is listed in \`roots.deny\`${rejection.entry ? ` as ${JSON.stringify(rejection.entry)}` : ''}. ` +
948
+ `Remove that entry from \`config.roots.deny\` ${CONFIG_LOCATION} to allow it.`
949
+ )
950
+ case 'builtin':
951
+ return (
952
+ head +
953
+ `it is ${rejection.reason}, a built-in protected root. Indexing or watching it would walk the whole ` +
954
+ 'directory tree (hundreds of thousands of files) and exhaust memory. Pass a project directory instead, ' +
955
+ `or add this exact directory to \`config.roots.allow\` ${CONFIG_LOCATION} if you really mean it ` +
956
+ '(or set `allowUnsafeRoots: true` to allow every built-in protected directory).'
957
+ )
958
+ default:
959
+ return head + `${rejection.reason}. Pass an absolute project directory instead.`
515
960
  }
516
- const parsed = path.parse(abs)
517
- if (!parsed.dir || abs === parsed.root) return true
518
- return UNSAFE_DIRS.has(storeKey(abs))
519
961
  }
520
962
 
521
963
  export class UnsafeRootError extends Error {
522
- constructor(root, requested) {
964
+ constructor(root, requested, options = {}) {
523
965
  const target = requested && String(requested).trim() ? String(requested) : String(root)
524
- super(
525
- `Refusing to use ${target} as a project memory root: it is ${unsafeReason(path.resolve(root))}. ` +
526
- 'Indexing or watching it would walk the whole directory tree (hundreds of thousands of files) and exhaust memory. ' +
527
- 'Pass a project directory instead, or set allowUnsafeRoots: true if you really mean it.',
528
- )
966
+ const rejection = options.rejection || rootRejection(root, options.config)
967
+ super(rootRejectionMessage(target, rejection))
529
968
  this.name = 'UnsafeRootError'
530
969
  this.root = root
970
+ this.code = rejection.kind
971
+ this.kind = rejection.kind
972
+ this.reason = rejection.reason
973
+ this.field = rejection.field
974
+ this.entry = rejection.entry
531
975
  }
532
976
  }
533
977
 
534
978
  /**
535
979
  * 校验「这个根可以当项目记忆根」。所有把目录当根写盘的入口都必须先过这一关:
536
980
  * 写盘前拒绝,比事后清理 `.dsh-project-memory` 便宜得多。
981
+ *
982
+ * `allowUnsafe` 是旧的内部兼容参数,语义等同 `allowUnsafeRoots: true`——只放开内置
983
+ * 名单,绝不会越过 `roots.deny` / `roots.exclude`。
537
984
  */
538
- export function assertSafeRoot(root, { requested = root, allowUnsafe = false } = {}) {
539
- if (allowUnsafe) return root
540
- if (!isUnsafeRoot(root)) return root
541
- throw new UnsafeRootError(root, requested)
985
+ export function assertSafeRoot(root, { requested = root, allowUnsafe = false, config } = {}) {
986
+ const policy = isCompiledRootPolicy(config)
987
+ ? (allowUnsafe && !config.allowUnsafeRoots ? { ...config, allowUnsafeRoots: true } : config)
988
+ : compileRootPolicy(config, { allowUnsafe })
989
+ const rejection = rootRejection(root, policy)
990
+ if (!rejection) return root
991
+ throw new UnsafeRootError(root, requested, { rejection })
542
992
  }
543
993
 
544
994
  export function resolveIndexRoot(exec, explicitRoot) {
@@ -643,11 +1093,16 @@ function nearestMarker(absPath, markers, isUnsafe) {
643
1093
  /**
644
1094
  * 项目根推导(**只认标记与显式声明,绝不从文件路径兜底**)。
645
1095
  *
1096
+ * `roots.exclude` 在这条链路里是最强的否定:文件落在被排除的子树里 → 直接 null,
1097
+ * 不再向上找标记,也不会退回会话工作目录(那棵树本来就不该进任何索引)。
1098
+ *
646
1099
  * @param {string} filePath 目标文件(也接受目录内探针文件路径)
647
- * @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean }} [opts]
1100
+ * @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
1101
+ * config?: object, policy?: object }} [opts]
648
1102
  * `extraRoots`:显式登记过的根(watch_repo / watchManager)。
649
1103
  * `sessionRoot`:会话工作目录,作为**最后**一级推定——仅当文件确实在它里面、
650
1104
  * 且它是安全目录时采用。
1105
+ * `config`:插件 config;`roots.deny` / `roots.exclude` / `roots.allow` 由此生效。
651
1106
  * `isUnsafe`:危险根判定,默认 `isUnsafeRoot`。可注入是为了让"被拒前缀里有一个合法
652
1107
  * `.git`"这条反直觉输入能在任意平台上用一个临时目录复现(`/opt/homebrew` 正是被
653
1108
  * `.git` 主动选中的,不是兜底误判——issue #5 的现场复核结论)。
@@ -655,13 +1110,21 @@ function nearestMarker(absPath, markers, isUnsafe) {
655
1110
  */
656
1111
  export function findProjectRoot(filePath, opts = {}) {
657
1112
  if (typeof filePath !== 'string' || !filePath) return null
658
- const isUnsafe = typeof opts.isUnsafe === 'function' ? opts.isUnsafe : isUnsafeRoot
1113
+ const policy = isCompiledRootPolicy(opts.policy)
1114
+ ? opts.policy
1115
+ : isCompiledRootPolicy(opts.config)
1116
+ ? opts.config
1117
+ : compileRootPolicy(opts.config, { allowUnsafe: opts.allowUnsafe === true })
1118
+ const isUnsafe = typeof opts.isUnsafe === 'function'
1119
+ ? opts.isUnsafe
1120
+ : (dir) => rootRejection(dir, policy) !== null
659
1121
  let abs
660
1122
  try {
661
1123
  abs = path.resolve(filePath)
662
1124
  } catch {
663
1125
  return null
664
1126
  }
1127
+ if (excludedEntryForAbs(abs, policy)) return null
665
1128
  const explicit = longestRootContaining(opts.extraRoots || [], abs)
666
1129
  if (explicit) return isUnsafe(explicit) ? null : explicit
667
1130
 
@@ -676,11 +1139,12 @@ export function findProjectRoot(filePath, opts = {}) {
676
1139
  /**
677
1140
  * **会话记忆根**:本插件所有"这个会话的记忆放哪"的唯一答案。
678
1141
  * 声明优先(标记)→ 会话工作目录(安全时)→ null(家目录/系统目录,且没有标记)。
1142
+ * `config` 里的 `roots.*` 与 `allowUnsafeRoots` 与工具侧共用同一套判定。
679
1143
  */
680
- export function resolveProjectMemoryRoot(cwd) {
1144
+ export function resolveProjectMemoryRoot(cwd, config) {
681
1145
  const base = resolveDir(cwd) || resolveDir(process.cwd())
682
1146
  if (!base) return null
683
- return findProjectRoot(path.join(base, PROJECT_PROBE), { sessionRoot: base })
1147
+ return findProjectRoot(path.join(base, PROJECT_PROBE), { sessionRoot: base, config })
684
1148
  }
685
1149
 
686
1150
  /**
@@ -692,13 +1156,14 @@ export function resolveSafeIndexRoot(exec, explicitRoot, config) {
692
1156
  const allowUnsafe = config?.allowUnsafeRoots === true
693
1157
  const explicit = explicitRoot && String(explicitRoot).trim() ? String(explicitRoot) : null
694
1158
  if (explicit) {
695
- return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe })
1159
+ return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe, config })
696
1160
  }
697
1161
  const cwd = resolveIndexRoot(exec)
698
- const root = resolveProjectMemoryRoot(cwd)
1162
+ const root = resolveProjectMemoryRoot(cwd, config)
699
1163
  if (root) return root
700
- if (allowUnsafe) return cwd
701
- throw new UnsafeRootError(cwd, cwd)
1164
+ // allowUnsafeRoots 只放开内置名单;cwd 被 deny / exclude / 文件系统根命中时仍然拒绝。
1165
+ if (allowUnsafe && !rootRejection(cwd, config)) return cwd
1166
+ throw new UnsafeRootError(cwd, cwd, { config })
702
1167
  }
703
1168
 
704
1169
  /** 尽力而为的会话记忆根:拿不到就返回 null(用于审计镜像这类旁路,不抛错)。 */