@yolk_vat-y/dsh-project-memory 0.6.4 → 0.6.6

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/util/fs.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  } from 'node:fs'
5
5
  import { execFileSync } from 'node:child_process'
6
6
  import { readFile } from 'node:fs/promises'
7
- import { createHash } from 'node:crypto'
7
+ import { createHash, randomUUID } from 'node:crypto'
8
8
  import os from 'node:os'
9
9
  import path from 'node:path'
10
10
  import { sessionWorkingDir } from './session-dir.js'
@@ -22,62 +22,192 @@ import { sessionWorkingDir } from './session-dir.js'
22
22
  * @param {unknown} data - 要序列化的 JSON 值。
23
23
  * @throws 序列化失败或写盘/rename 失败时原样抛出(调用方决定回退策略)。
24
24
  */
25
- export function writeJsonAtomic(file, data) {
26
- mkdirSync(path.dirname(file), { recursive: true })
25
+ const TRANSIENT_FS_CODES = new Set(['EPERM', 'EBUSY', 'EACCES'])
26
+
27
+ /**
28
+ * Windows 上 rename/unlink 会被杀毒软件、搜索索引、备份代理瞬时占用(EPERM/EBUSY),
29
+ * 同一参数重试一次通常就过。只在**瞬时错误码**上重试;真实失败(EISDIR/ENOSPC/EACCES 持续)
30
+ * 立即抛出,保持原有"失败要清 .tmp 并抛出去"的契约。
31
+ */
32
+ function retryTransient(op, attempts = 3) {
33
+ let last
34
+ for (let i = 0; i < attempts; i++) {
35
+ try {
36
+ return op()
37
+ } catch (err) {
38
+ last = err
39
+ if (!TRANSIENT_FS_CODES.has(err?.code)) throw err
40
+ if (i + 1 < attempts) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10 * (i + 1))
41
+ }
42
+ }
43
+ throw last
44
+ }
45
+
46
+ export function writeJsonAtomic(file, data, { ensureDir = true } = {}) {
47
+ const dir = path.dirname(file)
48
+ if (ensureDir) mkdirSync(dir, { recursive: true })
27
49
  const tmp = `${file}.${process.pid}.tmp`
50
+ const payload = JSON.stringify(data)
51
+ const write = () => {
52
+ retryTransient(() => writeFileSync(tmp, payload))
53
+ retryTransient(() => renameSync(tmp, file))
54
+ }
28
55
  try {
29
- writeFileSync(tmp, JSON.stringify(data))
30
- renameSync(tmp, file)
56
+ write()
31
57
  } catch (err) {
58
+ let failure = err
59
+ // 目录可能在两次写之间被外部删掉(测试、用户清理、挂载点抖动);`ensureDir: false` 的
60
+ // 快路径因此不能假设目录一定在——补建后重做一次,仍然失败才按原契约抛。
61
+ if (err?.code === 'ENOENT') {
62
+ try {
63
+ mkdirSync(dir, { recursive: true })
64
+ write()
65
+ return
66
+ } catch (retryErr) {
67
+ failure = retryErr
68
+ }
69
+ }
32
70
  try {
33
71
  unlinkSync(tmp)
34
72
  } catch {
35
73
  // tmp 已不在(rename 其实成功了)或不可删;两种都无需处理
36
74
  }
37
- throw err
75
+ throw failure
38
76
  }
39
77
  }
40
78
 
79
+ /** 本机标识:锁的存活判定只在同机可信(跨机只能退回 mtime)。 */
80
+ const LOCK_HOST = os.hostname()
81
+ const LOCK_FILE = '.write.lock'
82
+ let lockSeq = 0
83
+
41
84
  /**
42
- * 目录级写锁(跨进程)。写入前短暂持有,读改写之间不会交错。
43
- * 锁文件是 `.write.lock`;崩溃留下的锁超过 staleMs 自动清掉。
44
- * @param {string} dir 目标目录(不存在则创建)
45
- * @param {{timeoutMs?: number, staleMs?: number}} [opts]
46
- * @returns {null | (() => void)} 释放函数;拿不到锁返回 null
85
+ * 读锁文件(不存在/读失败返回 null)。
86
+ * 旧版本写的是裸 pid;新版本写 JSON(pid + host + token)。两种都要能读。
87
+ * @param {string} file
88
+ * @returns {null | { text: string, meta: { pid?: number, host?: string, token?: string }, ageMs: number }}
47
89
  */
48
- export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000 } = {}) {
90
+ function readLockState(file) {
49
91
  try {
50
- mkdirSync(dir, { recursive: true })
92
+ const text = readFileSync(file, 'utf8')
93
+ const ageMs = Date.now() - statSync(file).mtimeMs
94
+ let meta = null
95
+ try {
96
+ const parsed = JSON.parse(text)
97
+ if (parsed && typeof parsed === 'object') meta = parsed
98
+ } catch {
99
+ // 旧格式:裸 pid
100
+ }
101
+ if (!meta) meta = { pid: Number.parseInt(text.trim(), 10) }
102
+ return { text, meta, ageMs }
51
103
  } catch {
52
104
  return null
53
105
  }
54
- const file = path.join(dir, '.write.lock')
106
+ }
107
+
108
+ /**
109
+ * 进程启动时刻(Linux:`/proc/<pid>` 的 ctime)。其它平台读不到就返回 null。
110
+ * 只用于识别 **pid 复用**:一个新进程复用了崩溃进程的 pid 时,它的启动时刻一定晚于
111
+ * 旧锁的 `at` —— 那是"锁确实死了"的硬证据,不必因为 pid 活着而永久卡住。
112
+ * @param {number} pid
113
+ * @returns {number|null}
114
+ */
115
+ function processStartMs(pid) {
116
+ try {
117
+ return statSync(`/proc/${pid}`).ctimeMs
118
+ } catch {
119
+ return null
120
+ }
121
+ }
122
+
123
+ /** 进程是否还活着。EPERM = 存在但属于别人,按活着算。 */
124
+ function pidAlive(pid) {
125
+ if (!Number.isInteger(pid) || pid <= 0) return false
126
+ try {
127
+ process.kill(pid, 0)
128
+ return true
129
+ } catch (err) {
130
+ return err?.code === 'EPERM'
131
+ }
132
+ }
133
+
134
+ /**
135
+ * 锁是否可以回收(stale)。
136
+ *
137
+ * 三条规则,按可信度排序:
138
+ * 1. 同机 + 锁里有 pid + 进程活着 → **绝不回收**,哪怕 mtime 很老。旧实现只看 mtime,
139
+ * 一次 > 10s 的大 store 写入就会被第二个进程抢走,而原持有者 release 时还会删掉对方的锁
140
+ * (实测三者同时持锁)。
141
+ * 2. 同机 + pid 明确已死 → 立即回收。不必等 staleMs —— 这正是"崩溃残留锁 + 重试预算 8.3s
142
+ * < staleMs 10s"导致 save 静默跳过的原因。
143
+ * 3. 跨机(或没有 host 字段的旧锁)→ 只能按 mtime:超过 staleMs 回收;超过 hardStaleMs 的
144
+ * 一律回收,兜住 pid 复用(同机也适用)。
145
+ * @param {{meta: object, ageMs: number}} state
146
+ * @param {number} staleMs
147
+ * @param {number} hardStaleMs
148
+ * @returns {boolean}
149
+ */
150
+ function lockIsStale(state, staleMs, hardStaleMs) {
151
+ if (!state) return true
152
+ const { meta, ageMs } = state
153
+ const sameHost = !meta.host || meta.host === LOCK_HOST
154
+ if (!sameHost || !Number.isInteger(meta.pid)) {
155
+ // 跨机 / 旧格式没有 pid:只能按 mtime,hardStaleMs 是最后兜底。
156
+ return ageMs > staleMs || ageMs > hardStaleMs
157
+ }
158
+ if (!pidAlive(meta.pid)) return true
159
+ // 活着:正常情况绝不回收。唯一的例外是 pid 被复用(新进程的启动时刻晚于旧锁)。
160
+ // 没有 `at` 的旧锁无法做这个判断 → 信任存活,宁可等也不能双写。
161
+ const started = processStartMs(meta.pid)
162
+ const at = Date.parse(meta.at || '')
163
+ if (started !== null && Number.isFinite(at) && started > at + 5000) return true
164
+ return false
165
+ }
166
+
167
+ /**
168
+ * 目录级写锁(跨进程)。写入前短暂持有,读改写之间不会交错。
169
+ *
170
+ * 锁文件是 `.write.lock`,内容 `{pid, host, token, at}`;**释放要校验 token**,绝不 unlink
171
+ * 别人的锁。拿不到锁返回 null(调用方必须把这一次写当成失败,而不是"等会儿会写")。
172
+ * @param {string} dir 目标目录(不存在则创建)
173
+ * @param {{timeoutMs?: number, staleMs?: number, hardStaleMs?: number}} [opts]
174
+ * @returns {null | (() => void)} 释放函数;拿不到锁返回 null
175
+ */
176
+ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000, hardStaleMs = 0, ensureDir = true } = {}) {
177
+ if (ensureDir) {
178
+ try {
179
+ mkdirSync(dir, { recursive: true })
180
+ } catch {
181
+ return null
182
+ }
183
+ }
184
+ const file = path.join(dir, LOCK_FILE)
185
+ const hardLimit = hardStaleMs > 0 ? hardStaleMs : staleMs * 10
186
+ const token = `${process.pid}-${Date.now().toString(36)}-${++lockSeq}-${randomUUID().slice(0, 8)}`
187
+ const payload = JSON.stringify({ pid: process.pid, host: LOCK_HOST, token, at: new Date().toISOString() })
55
188
  const deadline = Date.now() + timeoutMs
56
189
  const sleeper = new Int32Array(new SharedArrayBuffer(4))
57
190
  for (;;) {
58
191
  try {
59
192
  const fd = openSync(file, 'wx')
60
193
  try {
61
- writeFileSync(fd, String(process.pid))
194
+ writeFileSync(fd, payload)
62
195
  } finally {
63
196
  closeSync(fd)
64
197
  }
65
- return () => {
66
- try {
67
- unlinkSync(file)
68
- } catch {
69
- // 已被 stale 清理或目录不可写:不影响写入结果
70
- }
71
- }
198
+ return () => releaseDirLock(file, token)
72
199
  } catch (err) {
73
200
  if (err?.code !== 'EEXIST') return null
74
- try {
75
- if (Date.now() - statSync(file).mtimeMs > staleMs) {
76
- unlinkSync(file)
77
- continue
201
+ const state = readLockState(file)
202
+ if (!state) continue // 刚好被释放:下一轮直接抢
203
+ if (lockIsStale(state, staleMs, hardLimit)) {
204
+ // 只删"刚刚读到的那个内容":两次读之间锁可能已被别人抢到并重写。
205
+ try {
206
+ if (readFileSync(file, 'utf8') === state.text) unlinkSync(file)
207
+ } catch {
208
+ // 已被别处回收
78
209
  }
79
- } catch {
80
- // 锁刚好被释放:下一轮重试
210
+ continue
81
211
  }
82
212
  if (Date.now() >= deadline) return null
83
213
  Atomics.wait(sleeper, 0, 0, 10)
@@ -85,6 +215,51 @@ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000 } = {})
85
215
  }
86
216
  }
87
217
 
218
+ /**
219
+ * 释放锁:内容还是自己的 token 才删。旧格式(裸 pid)只在自己 pid 匹配时删。
220
+ * 抢锁逻辑已经保证"别人抢走后原持有者不会删它"——这里是第二道闸。
221
+ * @param {string} file
222
+ * @param {string} token
223
+ */
224
+ function releaseDirLock(file, token) {
225
+ try {
226
+ const text = readFileSync(file, 'utf8')
227
+ let meta = null
228
+ try {
229
+ const parsed = JSON.parse(text)
230
+ if (parsed && typeof parsed === 'object') meta = parsed
231
+ } catch {
232
+ // 旧格式
233
+ }
234
+ if (meta && typeof meta.token === 'string') {
235
+ if (meta.token !== token) return
236
+ } else if (text.trim() !== String(process.pid)) {
237
+ return
238
+ }
239
+ unlinkSync(file)
240
+ } catch {
241
+ // 已被回收或目录不可写:不影响调用方
242
+ }
243
+ }
244
+
245
+ /**
246
+ * 读锁状态(诊断/测试用):谁持有、多久了、是否会被当成 stale。
247
+ * @param {string} dir
248
+ * @param {{staleMs?: number, hardStaleMs?: number}} [opts]
249
+ * @returns {null | { pid: number|undefined, host: string|undefined, token: string|undefined, ageMs: number, stale: boolean }}
250
+ */
251
+ export function inspectDirLock(dir, { staleMs = 10000, hardStaleMs = 0 } = {}) {
252
+ const state = readLockState(path.join(dir, LOCK_FILE))
253
+ if (!state) return null
254
+ return {
255
+ pid: state.meta.pid,
256
+ host: state.meta.host,
257
+ token: state.meta.token,
258
+ ageMs: state.ageMs,
259
+ stale: lockIsStale(state, staleMs, hardStaleMs > 0 ? hardStaleMs : staleMs * 10),
260
+ }
261
+ }
262
+
88
263
  export function assertReadableFile(filePath, maxFileSizeMb) {
89
264
  if (typeof filePath !== 'string' || !filePath) {
90
265
  throw new Error('file_path must be a non-empty string')
@@ -271,6 +446,12 @@ export function walkDir(root, opts = {}) {
271
446
  // 扫描也该同意这一点;否则父根会把子项目的全部内容再存一份(实测一个父目录
272
447
  // 的 store 里 9075/9081 个文件是子根 store 的重复副本)。
273
448
  const nestedStoreName = opts.nestedStoreName || null
449
+ // `roots.exclude` 是子树级前缀匹配:命中的目录整棵剪掉,命中的文件直接不收。
450
+ const policy = isCompiledRootPolicy(opts.policy)
451
+ ? opts.policy
452
+ : isCompiledRootPolicy(opts.config)
453
+ ? opts.config
454
+ : opts.config ? compileRootPolicy(opts.config) : null
274
455
  const out = []
275
456
  const skipped = []
276
457
  const unreadable = []
@@ -295,6 +476,7 @@ export function walkDir(root, opts = {}) {
295
476
  const full = path.join(dir, entry.name)
296
477
  if (entry.isDirectory()) {
297
478
  if (ignoreNames.has(entry.name)) continue
479
+ if (policy && excludedEntryForAbs(full, policy)) continue
298
480
  if (nestedStoreName && hasOwnStore(full, nestedStoreName)) {
299
481
  skipped.push(full)
300
482
  continue
@@ -306,6 +488,7 @@ export function walkDir(root, opts = {}) {
306
488
  }
307
489
  stack.push([full, depth + 1])
308
490
  } else {
491
+ if (policy && excludedEntryForAbs(full, policy)) continue
309
492
  if (out.length >= maxFiles) {
310
493
  truncated = true
311
494
  capped = true
@@ -350,6 +533,11 @@ function gitListedFiles(root) {
350
533
  * @returns {{files: string[], truncated: boolean, capped: boolean, skipped: string[], unreadable: string[]}}
351
534
  */
352
535
  export function listProjectFiles(root, opts = {}) {
536
+ const policy = isCompiledRootPolicy(opts.policy)
537
+ ? opts.policy
538
+ : isCompiledRootPolicy(opts.config)
539
+ ? opts.config
540
+ : opts.config ? compileRootPolicy(opts.config) : null
353
541
  const listed = opts.gitAware === false ? null : gitListedFiles(root)
354
542
  if (listed === null) return walkDir(root, opts)
355
543
  const maxFiles = Number.isFinite(opts.maxFiles) && opts.maxFiles > 0 ? opts.maxFiles : Infinity
@@ -366,6 +554,11 @@ export function listProjectFiles(root, opts = {}) {
366
554
  if (!rel) continue
367
555
  const segs = rel.split('/')
368
556
  if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
557
+ const abs = path.join(root, rel)
558
+ // 与 walkDir 同一判据:exclude 是子树级前缀,git 清单里的文件同样要过这一关。
559
+ // 这一步必须在 maxDepth 之前:被排除文件不该把扫描标成 truncated(否则本轮
560
+ // 不会清理"未见到的旧条目",排除规则反而让旧索引留在盘上)。
561
+ if (policy && excludedEntryForAbs(abs, policy)) continue
369
562
  if (segs.length > maxDepth) {
370
563
  capped = true
371
564
  continue
@@ -379,7 +572,6 @@ export function listProjectFiles(root, opts = {}) {
379
572
  capped = true
380
573
  break
381
574
  }
382
- const abs = path.join(root, rel)
383
575
  try {
384
576
  if (!statSync(abs).isFile()) continue
385
577
  } catch {
@@ -615,57 +807,363 @@ const UNSAFE = collectUnsafeRootSets()
615
807
  const UNSAFE_DIRS = UNSAFE.unsafe
616
808
  const SHARED_TEMP_DIRS = UNSAFE.sharedTemp
617
809
 
618
- /** 判定依据文案:用于拒绝时告诉用户「为什么是它」。 */
619
- function unsafeReason(abs) {
620
- const key = storeKey(abs)
621
- const parsed = path.parse(abs)
622
- if (abs === parsed.root) return 'the filesystem root'
623
- let home = null
810
+ // ---------------------------------------------------------------------------
811
+ // 用户可配置的根名单(`roots.allow` / `roots.deny` / `roots.exclude`)。
812
+ //
813
+ // 三个字段的匹配口径刻意不同,别合并成一个:
814
+ // - allow / deny:**精确匹配**,只针对目录本身。`deny: /srv/shared` 不拒绝
815
+ // `/srv/shared/myproj`——它自己是一个合法项目根。
816
+ // - exclude:**路径边界前缀匹配**,整棵子树都算。子树里的文件一律不进索引,
817
+ // 也不能在这棵子树里推出新的项目根。
818
+ //
819
+ // 优先级:exclude > deny > allow > 内置名单。`allowUnsafeRoots: true` 保留为兼容,
820
+ // 只放开**内置名单**;deny / exclude 仍然优先。文件系统根永远不能当根(allow 也不行)。
821
+ // ---------------------------------------------------------------------------
822
+
823
+ const ROOT_POLICY_FIELDS = ['allow', 'deny', 'exclude']
824
+
825
+ /** 每条告警只打一次:配置在进程内是静态的,重复刷屏没有信息量。 */
826
+ const warnedRootPolicyEntries = new Set()
827
+
828
+ function warnRootPolicyOnce(key, message, warn) {
829
+ if (warnedRootPolicyEntries.has(key)) return
830
+ warnedRootPolicyEntries.add(key)
831
+ const log = typeof warn === 'function' ? warn : console.error
832
+ log(`[dsh-project-memory] ${message}`)
833
+ }
834
+
835
+ function expandHomeEntry(value, home, pathApi) {
836
+ if (value === '~') return home
837
+ if (value.startsWith('~/') || value.startsWith('~\\')) {
838
+ return home ? pathApi.resolve(home, value.slice(2)) : null
839
+ }
840
+ return value
841
+ }
842
+
843
+ function normalizeRootPolicyEntries(list, field, { platform, pathApi, home, warn }) {
844
+ const out = []
845
+ if (list === undefined || list === null) return out
846
+ if (!Array.isArray(list)) {
847
+ warnRootPolicyOnce(
848
+ `shape:${field}`,
849
+ `config.roots.${field} must be an array of absolute paths; ignoring it.`,
850
+ warn,
851
+ )
852
+ return out
853
+ }
854
+ for (const raw of list) {
855
+ if (typeof raw !== 'string') {
856
+ warnRootPolicyOnce(
857
+ `type:${field}:${typeof raw}`,
858
+ `config.roots.${field} contains a non-string entry; ignoring it (only absolute path strings are accepted).`,
859
+ warn,
860
+ )
861
+ continue
862
+ }
863
+ const value = raw.trim()
864
+ if (!value) continue
865
+ const expanded = expandHomeEntry(value, home, pathApi)
866
+ if (expanded === null) {
867
+ warnRootPolicyOnce(
868
+ `home:${field}:${value}`,
869
+ `config.roots.${field} entry ${JSON.stringify(value)} cannot be expanded: the home directory is unavailable.`,
870
+ warn,
871
+ )
872
+ continue
873
+ }
874
+ if (!pathApi.isAbsolute(expanded)) {
875
+ warnRootPolicyOnce(
876
+ `relative:${field}:${value}`,
877
+ `config.roots.${field} entry ignored (not an absolute path): ${JSON.stringify(value)}. ` +
878
+ 'Relative paths would be resolved against the host cwd and are unpredictable; use an absolute path or ~/...',
879
+ warn,
880
+ )
881
+ continue
882
+ }
883
+ let abs
884
+ try {
885
+ abs = pathApi.resolve(expanded)
886
+ } catch {
887
+ warnRootPolicyOnce(
888
+ `resolve:${field}:${value}`,
889
+ `config.roots.${field} entry ignored (cannot be resolved): ${JSON.stringify(value)}.`,
890
+ warn,
891
+ )
892
+ continue
893
+ }
894
+ out.push({ abs, key: storeKey(abs, platform), raw: value })
895
+ }
896
+ return out
897
+ }
898
+
899
+ function isCompiledRootPolicy(value) {
900
+ return Boolean(value && typeof value === 'object' && value.__rootPolicy === true)
901
+ }
902
+
903
+ /**
904
+ * 把插件 config 编译成一份可复用的根判定策略。
905
+ *
906
+ * 参数化(platform / pathApi / home / env)是为了在任意平台上验证 Windows 语义,
907
+ * 与 `collectUnsafeRootSets()` 的测试惯例一致;生产路径只用无参形式。
908
+ *
909
+ * @param {object} [config] 插件 config(只读 `config.roots` 与 `config.allowUnsafeRoots`)
910
+ * @param {{platform?: string, pathApi?: object, home?: string|null, env?: object, warn?: Function,
911
+ * allowUnsafe?: boolean, unsafeDirs?: Set<string>, sharedTemp?: Set<string>}} [opts]
912
+ * @returns {object} 策略对象(内部结构,调用方应通过 rootRejection/isUnsafeRoot/isExcludedPath 使用)
913
+ */
914
+ export function compileRootPolicy(config, opts = {}) {
915
+ const platform = opts.platform || process.platform
916
+ const pathApi = opts.pathApi || path
917
+ const home = Object.prototype.hasOwnProperty.call(opts, 'home') ? opts.home : safeHomedir()
918
+ const warn = opts.warn
919
+ const rawRoots = config && typeof config === 'object' ? config.roots : undefined
920
+ const roots = rawRoots && typeof rawRoots === 'object' && !Array.isArray(rawRoots) ? rawRoots : {}
921
+ if (rawRoots !== undefined && (typeof rawRoots !== 'object' || rawRoots === null || Array.isArray(rawRoots))) {
922
+ warnRootPolicyOnce(
923
+ 'shape:roots',
924
+ 'config.roots must be an object with `allow` / `deny` / `exclude` arrays; ignoring it.',
925
+ warn,
926
+ )
927
+ }
928
+
929
+ const entries = {}
930
+ for (const field of ROOT_POLICY_FIELDS) {
931
+ entries[field] = normalizeRootPolicyEntries(roots[field], field, { platform, pathApi, home, warn })
932
+ }
933
+
934
+ let builtin = opts.unsafeDirs || null
935
+ let sharedTemp = opts.sharedTemp || null
936
+ if (!builtin || !sharedTemp) {
937
+ // 只有"完全没传模拟参数"时才复用模块级集合。只要显式给了 platform / pathApi /
938
+ // home / tmp / env 中的任一个,就按这些参数重算——否则在 Linux 上模拟 Windows
939
+ // 或换一个 home 时,内置名单会悄悄沿用当前机器的那一份。
940
+ const simulated = ['platform', 'pathApi', 'home', 'tmp', 'env'].some((key) =>
941
+ Object.prototype.hasOwnProperty.call(opts, key),
942
+ )
943
+ if (!simulated && platform === process.platform) {
944
+ builtin = builtin || UNSAFE_DIRS
945
+ sharedTemp = sharedTemp || SHARED_TEMP_DIRS
946
+ } else {
947
+ const sets = collectUnsafeRootSets({
948
+ platform,
949
+ home,
950
+ tmp: Object.prototype.hasOwnProperty.call(opts, 'tmp') ? opts.tmp : os.tmpdir(),
951
+ env: opts.env || process.env,
952
+ pathApi,
953
+ })
954
+ builtin = builtin || sets.unsafe
955
+ sharedTemp = sharedTemp || sets.sharedTemp
956
+ }
957
+ }
958
+
959
+ const allowEntries = new Map(entries.allow.map((e) => [e.key, e.raw]))
960
+ const denyEntries = new Map(entries.deny.map((e) => [e.key, e.raw]))
961
+ return {
962
+ __rootPolicy: true,
963
+ platform,
964
+ pathApi,
965
+ home,
966
+ allowUnsafeRoots: config?.allowUnsafeRoots === true || opts.allowUnsafe === true,
967
+ allow: new Set(allowEntries.keys()),
968
+ deny: new Set(denyEntries.keys()),
969
+ exclude: entries.exclude,
970
+ allowEntries,
971
+ denyEntries,
972
+ builtin,
973
+ sharedTemp,
974
+ }
975
+ }
976
+
977
+ function policyFor(configOrPolicy, opts) {
978
+ if (isCompiledRootPolicy(configOrPolicy)) return configOrPolicy
979
+ return compileRootPolicy(configOrPolicy, opts)
980
+ }
981
+
982
+ /** `parent` 是否等于 `child` 或它的祖先(按路径分隔符,含子树)。 */
983
+ function isInsideKey(parentKey, childKey, sep) {
984
+ if (parentKey === childKey) return true
985
+ const prefix = parentKey.endsWith(sep) ? parentKey : `${parentKey}${sep}`
986
+ return childKey.startsWith(prefix)
987
+ }
988
+
989
+ function excludedEntryForAbs(abs, policy) {
990
+ if (!policy.exclude.length) return null
991
+ let absResolved
992
+ try {
993
+ absResolved = policy.pathApi.resolve(abs)
994
+ } catch {
995
+ return null
996
+ }
997
+ const key = storeKey(absResolved, policy.platform)
998
+ for (const entry of policy.exclude) {
999
+ if (isInsideKey(entry.key, key, policy.pathApi.sep)) return entry
1000
+ }
1001
+ return null
1002
+ }
1003
+
1004
+ /**
1005
+ * 某个文件/目录是否落在 `roots.exclude` 的子树里。
1006
+ * @returns {{abs: string, key: string, raw: string}|null} 命中的条目(用于报告),否则 null
1007
+ */
1008
+ export function excludedEntryForPath(filePath, configOrPolicy, opts) {
1009
+ if (typeof filePath !== 'string' || !filePath) return null
1010
+ const policy = policyFor(configOrPolicy, opts)
1011
+ let abs
624
1012
  try {
625
- home = storeKey(path.resolve(os.homedir()))
1013
+ abs = policy.pathApi.resolve(filePath)
626
1014
  } catch {
627
- home = null
1015
+ return null
1016
+ }
1017
+ return excludedEntryForAbs(abs, policy)
1018
+ }
1019
+
1020
+ /** 文案用的「为什么是它」。 */
1021
+ function unsafeReason(abs, policy = {}) {
1022
+ const platform = policy.platform || process.platform
1023
+ const pathApi = policy.pathApi || path
1024
+ const key = storeKey(abs, platform)
1025
+ const parsed = pathApi.parse(abs)
1026
+ if (key === storeKey(parsed.root, platform)) return 'the filesystem root'
1027
+ if (policy.home) {
1028
+ try {
1029
+ if (key === storeKey(pathApi.resolve(policy.home), platform)) return 'your home directory'
1030
+ } catch {
1031
+ // 家目录不可解析:继续按临时/系统目录归类
1032
+ }
1033
+ } else {
1034
+ try {
1035
+ if (key === storeKey(path.resolve(os.homedir()), platform)) return 'your home directory'
1036
+ } catch {
1037
+ // 同上
1038
+ }
628
1039
  }
629
- if (home && key === home) return 'your home directory'
630
- if (SHARED_TEMP_DIRS.has(key)) return 'the shared temp directory'
1040
+ const shared = policy.sharedTemp || SHARED_TEMP_DIRS
1041
+ if (shared.has(key)) return 'the shared temp directory'
631
1042
  return 'a system directory that is never a project root'
632
1043
  }
633
1044
 
634
- /** 这个目录能否当项目记忆根?纯判定,无副作用。 */
635
- export function isUnsafeRoot(root) {
636
- if (typeof root !== 'string' || !root) return true
1045
+ /**
1046
+ * 根判定的**唯一实现**:返回 null(可用)或一条命中记录。
1047
+ *
1048
+ * 命中记录带 `kind` / `field` / `entry` / `reason`,调用方据此生成"是哪条命中的、
1049
+ * 该改哪个字段"的拒绝文案。优先级在这里一眼可见:exclude → deny → 内置(allow
1050
+ * 与 allowUnsafeRoots 只作用于内置名单)→ 文件系统根永远拒绝。
1051
+ *
1052
+ * @param {string} root 候选根
1053
+ * @param {object} [configOrPolicy] 插件 config,或 `compileRootPolicy()` 的返回值
1054
+ */
1055
+ export function rootRejection(root, configOrPolicy, opts) {
1056
+ const policy = policyFor(configOrPolicy, opts)
1057
+ if (typeof root !== 'string' || !root) {
1058
+ return { kind: 'invalid', field: null, entry: null, reason: 'not a usable directory path' }
1059
+ }
637
1060
  let abs
638
1061
  try {
639
- abs = path.resolve(root)
1062
+ abs = policy.pathApi.resolve(root)
640
1063
  } catch {
641
- return true
1064
+ return { kind: 'invalid', field: null, entry: null, reason: 'not a usable directory path' }
1065
+ }
1066
+ const platform = policy.platform
1067
+ const key = storeKey(abs, platform)
1068
+ const parsed = policy.pathApi.parse(abs)
1069
+ if (!parsed.dir || key === storeKey(parsed.root, platform)) {
1070
+ return { kind: 'filesystem-root', abs, field: null, entry: null, reason: 'the filesystem root' }
1071
+ }
1072
+ const excluded = excludedEntryForAbs(abs, policy)
1073
+ if (excluded) {
1074
+ return {
1075
+ kind: 'exclude',
1076
+ abs,
1077
+ field: 'roots.exclude',
1078
+ entry: excluded.raw,
1079
+ reason: `inside the subtree excluded by ${JSON.stringify(excluded.raw)}`,
1080
+ }
1081
+ }
1082
+ if (policy.deny.has(key)) {
1083
+ return {
1084
+ kind: 'deny',
1085
+ abs,
1086
+ field: 'roots.deny',
1087
+ entry: policy.denyEntries.get(key) || null,
1088
+ reason: 'listed in roots.deny',
1089
+ }
1090
+ }
1091
+ if (policy.builtin.has(key) && !policy.allowUnsafeRoots && !policy.allow.has(key)) {
1092
+ return { kind: 'builtin', abs, field: 'roots.allow', entry: null, reason: unsafeReason(abs, policy) }
1093
+ }
1094
+ return null
1095
+ }
1096
+
1097
+ /** 这个目录能否当项目记忆根?纯判定,无副作用。 */
1098
+ export function isUnsafeRoot(root, configOrPolicy, opts) {
1099
+ return rootRejection(root, configOrPolicy, opts) !== null
1100
+ }
1101
+
1102
+ const CONFIG_LOCATION = 'under `- id: project-memory` → `config:`'
1103
+
1104
+ /** 把命中记录变成一句可执行的拒绝文案。 */
1105
+ function rootRejectionMessage(target, rejection) {
1106
+ const head = `Refusing to use ${target} as a project memory root: `
1107
+ switch (rejection.kind) {
1108
+ case 'filesystem-root':
1109
+ return (
1110
+ head +
1111
+ 'it is the filesystem root. That can never be a project memory root; pass a project directory instead.'
1112
+ )
1113
+ case 'exclude':
1114
+ return (
1115
+ head +
1116
+ `it is inside the subtree excluded by \`roots.exclude\` entry ${JSON.stringify(rejection.entry)}. ` +
1117
+ `Remove that entry from \`config.roots.exclude\` ${CONFIG_LOCATION} if this directory should be a root.`
1118
+ )
1119
+ case 'deny':
1120
+ return (
1121
+ head +
1122
+ `it is listed in \`roots.deny\`${rejection.entry ? ` as ${JSON.stringify(rejection.entry)}` : ''}. ` +
1123
+ `Remove that entry from \`config.roots.deny\` ${CONFIG_LOCATION} to allow it.`
1124
+ )
1125
+ case 'builtin':
1126
+ return (
1127
+ head +
1128
+ `it is ${rejection.reason}, a built-in protected root. Indexing or watching it would walk the whole ` +
1129
+ 'directory tree (hundreds of thousands of files) and exhaust memory. Pass a project directory instead, ' +
1130
+ `or add this exact directory to \`config.roots.allow\` ${CONFIG_LOCATION} if you really mean it ` +
1131
+ '(or set `allowUnsafeRoots: true` to allow every built-in protected directory).'
1132
+ )
1133
+ default:
1134
+ return head + `${rejection.reason}. Pass an absolute project directory instead.`
642
1135
  }
643
- const parsed = path.parse(abs)
644
- if (!parsed.dir || abs === parsed.root) return true
645
- return UNSAFE_DIRS.has(storeKey(abs))
646
1136
  }
647
1137
 
648
1138
  export class UnsafeRootError extends Error {
649
- constructor(root, requested) {
1139
+ constructor(root, requested, options = {}) {
650
1140
  const target = requested && String(requested).trim() ? String(requested) : String(root)
651
- super(
652
- `Refusing to use ${target} as a project memory root: it is ${unsafeReason(path.resolve(root))}. ` +
653
- 'Indexing or watching it would walk the whole directory tree (hundreds of thousands of files) and exhaust memory. ' +
654
- 'Pass a project directory instead, or set allowUnsafeRoots: true if you really mean it.',
655
- )
1141
+ const rejection = options.rejection || rootRejection(root, options.config)
1142
+ super(rootRejectionMessage(target, rejection))
656
1143
  this.name = 'UnsafeRootError'
657
1144
  this.root = root
1145
+ this.code = rejection.kind
1146
+ this.kind = rejection.kind
1147
+ this.reason = rejection.reason
1148
+ this.field = rejection.field
1149
+ this.entry = rejection.entry
658
1150
  }
659
1151
  }
660
1152
 
661
1153
  /**
662
1154
  * 校验「这个根可以当项目记忆根」。所有把目录当根写盘的入口都必须先过这一关:
663
1155
  * 写盘前拒绝,比事后清理 `.dsh-project-memory` 便宜得多。
1156
+ *
1157
+ * `allowUnsafe` 是旧的内部兼容参数,语义等同 `allowUnsafeRoots: true`——只放开内置
1158
+ * 名单,绝不会越过 `roots.deny` / `roots.exclude`。
664
1159
  */
665
- export function assertSafeRoot(root, { requested = root, allowUnsafe = false } = {}) {
666
- if (allowUnsafe) return root
667
- if (!isUnsafeRoot(root)) return root
668
- throw new UnsafeRootError(root, requested)
1160
+ export function assertSafeRoot(root, { requested = root, allowUnsafe = false, config } = {}) {
1161
+ const policy = isCompiledRootPolicy(config)
1162
+ ? (allowUnsafe && !config.allowUnsafeRoots ? { ...config, allowUnsafeRoots: true } : config)
1163
+ : compileRootPolicy(config, { allowUnsafe })
1164
+ const rejection = rootRejection(root, policy)
1165
+ if (!rejection) return root
1166
+ throw new UnsafeRootError(root, requested, { rejection })
669
1167
  }
670
1168
 
671
1169
  export function resolveIndexRoot(exec, explicitRoot) {
@@ -753,16 +1251,33 @@ function resolveDir(dir) {
753
1251
  }
754
1252
  }
755
1253
 
756
- function nearestMarker(absPath, markers, isUnsafe) {
1254
+ /**
1255
+ * 自底向上找最近的根标记。**一次遍历同时看 VCS 与 PROJECT**,语义仍是"VCS 优先于 PROJECT":
1256
+ * 先命中的 VCS 直接返回(它一定是最深的);没有 VCS 就返回最深的 PROJECT。
1257
+ *
1258
+ * 为什么合并:旧实现对两组标记各走一遍祖先链,每层还要对每个 marker 做一次 existsSync。
1259
+ * 11 个 marker × 7 层 × 2 组在 WSL/NTFS 上实测 ~119ms/次——而每次懒索引都要走一遍。
1260
+ * 现在每层只 readdir 一次(同时拿到所有名字),遍历也只走一趟。
1261
+ */
1262
+ function nearestRootByMarkers(absPath, vcsMarkers, projectMarkers, isUnsafe) {
1263
+ let project = null
757
1264
  let dir = path.dirname(absPath)
758
1265
  for (;;) {
759
1266
  // 撞到家目录/系统目录边界就停:既不把边界当根,也不再向上(上面只会更宽)。
760
- if (isUnsafe(dir)) return null
761
- for (const marker of markers) {
762
- if (existsSync(path.join(dir, marker))) return dir
1267
+ // 已经记录的 PROJECT 命中仍然有效——它就在边界下方;丢掉它会退化成"会话根"兜底。
1268
+ if (isUnsafe(dir)) return project
1269
+ let names = null
1270
+ try {
1271
+ names = new Set(readdirSync(dir))
1272
+ } catch {
1273
+ names = null
1274
+ }
1275
+ if (names) {
1276
+ if (vcsMarkers.some((marker) => names.has(marker))) return dir
1277
+ if (!project && projectMarkers.some((marker) => names.has(marker))) project = dir
763
1278
  }
764
1279
  const parent = path.dirname(dir)
765
- if (parent === dir) return null
1280
+ if (parent === dir) return project
766
1281
  dir = parent
767
1282
  }
768
1283
  }
@@ -770,11 +1285,16 @@ function nearestMarker(absPath, markers, isUnsafe) {
770
1285
  /**
771
1286
  * 项目根推导(**只认标记与显式声明,绝不从文件路径兜底**)。
772
1287
  *
1288
+ * `roots.exclude` 在这条链路里是最强的否定:文件落在被排除的子树里 → 直接 null,
1289
+ * 不再向上找标记,也不会退回会话工作目录(那棵树本来就不该进任何索引)。
1290
+ *
773
1291
  * @param {string} filePath 目标文件(也接受目录内探针文件路径)
774
- * @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean }} [opts]
1292
+ * @param {{ extraRoots?: Iterable<string>, sessionRoot?: string|null, isUnsafe?: (dir: string) => boolean,
1293
+ * config?: object, policy?: object }} [opts]
775
1294
  * `extraRoots`:显式登记过的根(watch_repo / watchManager)。
776
1295
  * `sessionRoot`:会话工作目录,作为**最后**一级推定——仅当文件确实在它里面、
777
1296
  * 且它是安全目录时采用。
1297
+ * `config`:插件 config;`roots.deny` / `roots.exclude` / `roots.allow` 由此生效。
778
1298
  * `isUnsafe`:危险根判定,默认 `isUnsafeRoot`。可注入是为了让"被拒前缀里有一个合法
779
1299
  * `.git`"这条反直觉输入能在任意平台上用一个临时目录复现(`/opt/homebrew` 正是被
780
1300
  * `.git` 主动选中的,不是兜底误判——issue #5 的现场复核结论)。
@@ -782,17 +1302,26 @@ function nearestMarker(absPath, markers, isUnsafe) {
782
1302
  */
783
1303
  export function findProjectRoot(filePath, opts = {}) {
784
1304
  if (typeof filePath !== 'string' || !filePath) return null
785
- const isUnsafe = typeof opts.isUnsafe === 'function' ? opts.isUnsafe : isUnsafeRoot
1305
+ const policy = isCompiledRootPolicy(opts.policy)
1306
+ ? opts.policy
1307
+ : isCompiledRootPolicy(opts.config)
1308
+ ? opts.config
1309
+ : compileRootPolicy(opts.config, { allowUnsafe: opts.allowUnsafe === true })
1310
+ const isUnsafe = typeof opts.isUnsafe === 'function'
1311
+ ? opts.isUnsafe
1312
+ : (dir) => rootRejection(dir, policy) !== null
786
1313
  let abs
787
1314
  try {
788
1315
  abs = path.resolve(filePath)
789
1316
  } catch {
790
1317
  return null
791
1318
  }
1319
+ if (excludedEntryForAbs(abs, policy)) return null
792
1320
  const explicit = longestRootContaining(opts.extraRoots || [], abs)
793
1321
  if (explicit) return isUnsafe(explicit) ? null : explicit
794
1322
 
795
- const byMarker = nearestMarker(abs, VCS_MARKERS, isUnsafe) || nearestMarker(abs, PROJECT_MARKERS, isUnsafe)
1323
+ // 标记优先于会话根兜底;VCS 优先于 PROJECT("a marker above the cwd still wins" 是既有契约)。
1324
+ const byMarker = nearestRootByMarkers(abs, VCS_MARKERS, PROJECT_MARKERS, isUnsafe)
796
1325
  if (byMarker) return byMarker
797
1326
 
798
1327
  const session = resolveDir(opts.sessionRoot)
@@ -803,11 +1332,12 @@ export function findProjectRoot(filePath, opts = {}) {
803
1332
  /**
804
1333
  * **会话记忆根**:本插件所有"这个会话的记忆放哪"的唯一答案。
805
1334
  * 声明优先(标记)→ 会话工作目录(安全时)→ null(家目录/系统目录,且没有标记)。
1335
+ * `config` 里的 `roots.*` 与 `allowUnsafeRoots` 与工具侧共用同一套判定。
806
1336
  */
807
- export function resolveProjectMemoryRoot(cwd) {
1337
+ export function resolveProjectMemoryRoot(cwd, config) {
808
1338
  const base = resolveDir(cwd) || resolveDir(process.cwd())
809
1339
  if (!base) return null
810
- return findProjectRoot(path.join(base, PROJECT_PROBE), { sessionRoot: base })
1340
+ return findProjectRoot(path.join(base, PROJECT_PROBE), { sessionRoot: base, config })
811
1341
  }
812
1342
 
813
1343
  /**
@@ -819,13 +1349,14 @@ export function resolveSafeIndexRoot(exec, explicitRoot, config) {
819
1349
  const allowUnsafe = config?.allowUnsafeRoots === true
820
1350
  const explicit = explicitRoot && String(explicitRoot).trim() ? String(explicitRoot) : null
821
1351
  if (explicit) {
822
- return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe })
1352
+ return assertSafeRoot(path.resolve(explicit), { requested: explicit, allowUnsafe, config })
823
1353
  }
824
1354
  const cwd = resolveIndexRoot(exec)
825
- const root = resolveProjectMemoryRoot(cwd)
1355
+ const root = resolveProjectMemoryRoot(cwd, config)
826
1356
  if (root) return root
827
- if (allowUnsafe) return cwd
828
- throw new UnsafeRootError(cwd, cwd)
1357
+ // allowUnsafeRoots 只放开内置名单;cwd 被 deny / exclude / 文件系统根命中时仍然拒绝。
1358
+ if (allowUnsafe && !rootRejection(cwd, config)) return cwd
1359
+ throw new UnsafeRootError(cwd, cwd, { config })
829
1360
  }
830
1361
 
831
1362
  /** 尽力而为的会话记忆根:拿不到就返回 null(用于审计镜像这类旁路,不抛错)。 */