dsh-vigil 0.0.1

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 (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,680 @@
1
+ /**
2
+ * Deletion policy: protected-root grading, scale metering, and decision merge
3
+ * (FR-3.2 – FR-3.6, FR-4 integration).
4
+ *
5
+ * Decisions are computed as "the strictest requirement wins":
6
+ * 1. a critical root (or an ancestor of one) is never allowed to disappear;
7
+ * 2. a single call or the session's accumulated estimate over the threshold is
8
+ * stopped and reports what has already been deleted;
9
+ * 3. an intent that could not be parsed trusts nothing (configurable);
10
+ * 4. recursion, wildcards, and the highest target grade apply their configured
11
+ * decisions;
12
+ * 5. only then does the call pass.
13
+ *
14
+ * Scale numbers are estimates from a bounded directory walk, not guarantees:
15
+ * files created between the walk and the command, and deletions performed by
16
+ * other processes, are invisible to a pre-execution hook. The plugin states this
17
+ * limit in its output instead of pretending to be exact.
18
+ *
19
+ * @module dsh-vigil/delete-policy
20
+ */
21
+
22
+ import { lstatSync, readdirSync, statSync } from 'node:fs'
23
+ import { basename, join, resolve } from 'node:path'
24
+ import { strictestDecision } from '../config.js'
25
+ import { canonicalizePath, formatBytes, getHomeDir, isWithin, isWithinCanonical, pathKey, samePath } from '../util.js'
26
+
27
+ /** @typedef {'critical'|'high'|'medium'|'low'} TargetLevel */
28
+ /** @typedef {{ path: string, label: string }} ProtectedRoot */
29
+ /**
30
+ * @typedef {object} ProtectedRoots
31
+ * @property {ProtectedRoot[]} criticalTrees roots whose *descendants* are critical too
32
+ * @property {ProtectedRoot[]} criticalBoundary roots that are only protected as themselves (or as an ancestor of the root)
33
+ * @property {ProtectedRoot[]} criticalContainers roots protected in both directions (credential/state stores)
34
+ * @property {ProtectedRoot[]} criticalExact union of trees + boundary (kept for reporting)
35
+ * @property {ProtectedRoot[]} highExact
36
+ * @property {ProtectedRoot[]} mediumContainers
37
+ * @property {Set<string>} mediumNames
38
+ */
39
+
40
+ /**
41
+ * Collect the protected roots for this machine and configuration.
42
+ *
43
+ * Three kinds are deliberately distinguished, because "critical" means
44
+ * different things for them:
45
+ *
46
+ * - **tree** (`C:\Windows`, `Program Files`, `/etc`): the directory and
47
+ * everything under it is system material, so a descendant is critical too;
48
+ * - **boundary** (`C:\`, `C:\Users`, `/`): only the directory itself (and an
49
+ * ancestor of it) is the protected thing. Treating these as trees would
50
+ * make every user file critical;
51
+ * - **container** (`~/.dsh`, `~/.ssh`): protected in both directions — the
52
+ * directory, its contents, and any ancestor that would take it down with it.
53
+ *
54
+ * @param {any} config
55
+ * @param {{ cwd?: string, platform?: string, env?: Record<string, string|undefined> }} [options]
56
+ * @returns {ProtectedRoots}
57
+ */
58
+ export function buildProtectedRoots(config, options = {}) {
59
+ const platform = options.platform ?? process.platform
60
+ const env = options.env ?? process.env
61
+ const home = getHomeDir()
62
+ // An empty `cwd` means "unknown": do not invent a project root, and do not add
63
+ // one to the high list. This happens when the host process runs inside the
64
+ // Harness home (the Desktop app runs from the profile directory).
65
+ const rawCwd = options.cwd
66
+ const cwd = typeof rawCwd === 'string' && rawCwd === ''
67
+ ? ''
68
+ : resolve(rawCwd ?? process.cwd())
69
+ const dshHome = config?.paths?.dshHome ?? join(home, '.dsh')
70
+
71
+ /** @type {ProtectedRoot[]} */
72
+ const criticalTrees = []
73
+ /** @type {ProtectedRoot[]} */
74
+ const criticalBoundary = []
75
+ /** @type {ProtectedRoot[]} */
76
+ const criticalContainers = []
77
+ /** @type {ProtectedRoot[]} */
78
+ const highExact = []
79
+ /** @type {ProtectedRoot[]} */
80
+ const mediumContainers = []
81
+
82
+ /** @param {ProtectedRoot[]} list @param {string|undefined} path @param {string} label */
83
+ const push = (list, path, label) => {
84
+ if (typeof path === 'string' && path.trim() !== '') list.push({ path: resolve(path), label })
85
+ }
86
+
87
+ if (platform === 'win32') {
88
+ const systemDrive = env.SystemDrive || home.slice(0, 3)
89
+ // System directories: their contents are system files.
90
+ push(criticalTrees, env.SystemRoot || env.WINDIR, 'Windows 系统目录')
91
+ push(criticalTrees, env.ProgramFiles, 'Program Files')
92
+ push(criticalTrees, env['ProgramFiles(x86)'], 'Program Files (x86)')
93
+ push(criticalTrees, env.ProgramData || env.ALLUSERSPROFILE, 'ProgramData')
94
+ // Boundaries: deleting them removes every account, but their contents are
95
+ // ordinary user data (the home directory has its own `high` root).
96
+ push(criticalBoundary, systemDrive ? `${systemDrive}\\` : undefined, '系统盘根目录')
97
+ push(criticalBoundary, env.USERPROFILE ? resolve(env.USERPROFILE, '..') : undefined, '用户目录的上级(C:\\Users)')
98
+ push(criticalBoundary, env.PUBLIC ? resolve(env.PUBLIC, '..') : undefined, '公共目录的上级')
99
+ } else {
100
+ for (const [path, label] of [
101
+ ['/etc', '系统配置'],
102
+ ['/usr', '系统程序目录'],
103
+ ['/bin', '系统命令目录'],
104
+ ['/sbin', '系统管理命令目录'],
105
+ ['/lib', '系统库目录'],
106
+ ['/lib64', '系统库目录'],
107
+ ['/boot', '启动目录'],
108
+ ['/dev', '设备目录'],
109
+ ['/proc', '内核接口'],
110
+ ['/sys', '内核接口'],
111
+ ['/var', '系统数据目录'],
112
+ ['/opt', '系统可选软件目录'],
113
+ ['/Applications', '应用程序目录'],
114
+ ['/System', 'macOS 系统目录'],
115
+ ['/Library', 'macOS 库目录'],
116
+ ['/private', 'macOS 私有目录'],
117
+ ['/Volumes', '挂载卷'],
118
+ ]) {
119
+ push(criticalTrees, path, label)
120
+ }
121
+ // `/` itself: deleting it is catastrophic, but every path is under it, so it
122
+ // must stay a boundary rather than a tree.
123
+ push(criticalBoundary, '/', '文件系统根目录')
124
+ push(criticalBoundary, resolve(home, '..'), '用户目录的上级')
125
+ }
126
+
127
+ for (const [path, label] of [
128
+ [dshHome, 'Harness 主目录(会话、凭据、插件状态)'],
129
+ [join(dshHome, 'vigil'), 'dsh-vigil 自己的状态目录'],
130
+ [join(home, '.ssh'), 'SSH 私钥与授权'],
131
+ [join(home, '.aws'), 'AWS 凭据'],
132
+ [join(home, '.gnupg'), 'GPG 密钥'],
133
+ [join(home, '.pi'), 'Pi 配置'],
134
+ [join(home, '.config', 'dsh'), 'dsh 用户配置'],
135
+ [join(home, '.npmrc'), 'npm 凭据占位(文件级)'],
136
+ ]) {
137
+ push(criticalContainers, path, label)
138
+ }
139
+
140
+ push(highExact, home, '用户主目录')
141
+ if (config?.deleteGuard?.includeProjectRootAsHigh !== false && cwd !== '') push(highExact, cwd, '当前项目根目录')
142
+
143
+ for (const [path, label] of [
144
+ [join(home, 'Downloads'), '下载目录'],
145
+ [join(home, 'Desktop'), '桌面'],
146
+ [join(home, 'Documents'), '文档目录'],
147
+ [env.TEMP, '临时目录'],
148
+ [env.TMP, '临时目录'],
149
+ [join(home, '.cache'), '缓存目录'],
150
+ ]) {
151
+ push(mediumContainers, path, label)
152
+ }
153
+
154
+ for (const raw of config?.deleteGuard?.extraCriticalRoots ?? []) push(criticalContainers, raw, '用户配置的关键保护根')
155
+ for (const raw of config?.deleteGuard?.extraHighRoots ?? []) push(highExact, raw, '用户配置的高风险保护根')
156
+
157
+ return {
158
+ criticalTrees: dedupeRoots(criticalTrees),
159
+ criticalBoundary: dedupeRoots(criticalBoundary),
160
+ criticalContainers: dedupeRoots(criticalContainers),
161
+ criticalExact: dedupeRoots([...criticalTrees, ...criticalBoundary]),
162
+ highExact: dedupeRoots(highExact),
163
+ mediumContainers: dedupeRoots(mediumContainers),
164
+ mediumNames: new Set(['node_modules', '.git', '.svn', '.hg', 'dist', 'build', 'target', 'venv', '.venv']),
165
+ }
166
+ }
167
+
168
+ /**
169
+ * @param {ProtectedRoot[]} roots
170
+ * @returns {ProtectedRoot[]}
171
+ */
172
+ function dedupeRoots(roots) {
173
+ const seen = new Set()
174
+ /** @type {ProtectedRoot[]} */
175
+ const out = []
176
+ for (const root of roots) {
177
+ const key = pathKey(root.path)
178
+ if (seen.has(key)) continue
179
+ seen.add(key)
180
+ out.push(root)
181
+ }
182
+ return out
183
+ }
184
+
185
+ /**
186
+ * Classify one resolved target.
187
+ *
188
+ * Comparison is canonical: `~`, `%VAR%`, `$env:VAR`, 8.3 short names,
189
+ * junctions and `\\?\` prefixes all resolve to the same protected root before
190
+ * the level is decided, so an agent cannot rename the protection away at the
191
+ * string level.
192
+ *
193
+ * @param {string} targetPath absolute path
194
+ * @param {ProtectedRoots} roots
195
+ * @returns {{ level: TargetLevel, label: string }}
196
+ */
197
+ export function classifyPath(targetPath, roots) {
198
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') {
199
+ return { level: 'low', label: '普通路径' }
200
+ }
201
+ for (const root of roots.criticalTrees ?? []) {
202
+ if (isWithinCanonical(root.path, targetPath)) return { level: 'critical', label: root.label }
203
+ }
204
+ for (const root of roots.criticalBoundary ?? []) {
205
+ if (samePath(root.path, targetPath) || isWithinCanonical(targetPath, root.path)) {
206
+ return { level: 'critical', label: root.label }
207
+ }
208
+ }
209
+ for (const root of roots.criticalContainers ?? []) {
210
+ if (samePath(root.path, targetPath)
211
+ || isWithinCanonical(root.path, targetPath)
212
+ || isWithinCanonical(targetPath, root.path)) {
213
+ return { level: 'critical', label: root.label }
214
+ }
215
+ }
216
+ for (const root of roots.highExact ?? []) {
217
+ if (samePath(root.path, targetPath)) return { level: 'high', label: root.label }
218
+ }
219
+ for (const root of roots.mediumContainers ?? []) {
220
+ if (samePath(root.path, targetPath) || isWithinCanonical(root.path, targetPath)) {
221
+ return { level: 'medium', label: root.label }
222
+ }
223
+ }
224
+ const name = basename(canonicalizePath(targetPath)).toLowerCase()
225
+ if (roots.mediumNames?.has(name)) {
226
+ return { level: 'medium', label: `高频大目录 ${basename(targetPath)}` }
227
+ }
228
+ return { level: 'low', label: '普通路径' }
229
+ }
230
+
231
+ /**
232
+ * Bound the work of one scale estimate. Counting stops once the count or the byte
233
+ * total is enough to prove the threshold is crossed.
234
+ * @param {string} root
235
+ * @param {{ maxFiles: number, maxBytes: number, cap: number }} limits
236
+ * @returns {{ path: string, files: number, bytes: number, filesAtLeast: boolean, bytesAtLeast: boolean, exists: boolean, truncated: boolean, unknown: boolean, error: string|null }}
237
+ */
238
+ export function estimateScale(root, limits) {
239
+ const result = {
240
+ path: root,
241
+ files: 0,
242
+ bytes: 0,
243
+ filesAtLeast: false,
244
+ bytesAtLeast: false,
245
+ exists: false,
246
+ truncated: false,
247
+ unknown: false,
248
+ error: null,
249
+ }
250
+ let stat
251
+ try {
252
+ stat = lstatSync(root)
253
+ } catch {
254
+ return result
255
+ }
256
+ result.exists = true
257
+ if (stat.isFile()) {
258
+ result.files = 1
259
+ result.bytes = stat.size
260
+ return result
261
+ }
262
+ if (!stat.isDirectory()) {
263
+ return result
264
+ }
265
+ const cap = Math.max(1, Math.min(limits.cap, limits.maxFiles + 1))
266
+ // The pre-execute hook is synchronous: bound the walk even when a tree has
267
+ // millions of empty directories and no file can push us over the file cap.
268
+ const deadline = Date.now() + 200
269
+ const maxVisits = Math.max(512, cap * 8)
270
+ let visits = 0
271
+ /** @type {string[]} */
272
+ const stack = [root]
273
+ try {
274
+ while (stack.length > 0) {
275
+ const current = /** @type {string} */ (stack.pop())
276
+ visits += 1
277
+ if (visits > maxVisits || Date.now() > deadline) {
278
+ result.truncated = true
279
+ result.unknown = !result.filesAtLeast && !result.bytesAtLeast
280
+ stack.length = 0
281
+ break
282
+ }
283
+ let entries
284
+ try {
285
+ entries = readdirSync(current, { withFileTypes: true })
286
+ } catch {
287
+ continue
288
+ }
289
+ for (const entry of entries) {
290
+ const full = join(current, entry.name)
291
+ if (entry.isSymbolicLink()) continue
292
+ if (entry.isDirectory()) {
293
+ stack.push(full)
294
+ continue
295
+ }
296
+ if (!entry.isFile()) continue
297
+ let size = 0
298
+ try {
299
+ size = lstatSync(full).size
300
+ } catch {
301
+ continue
302
+ }
303
+ result.files += 1
304
+ result.bytes += size
305
+ if (result.files >= cap) {
306
+ result.filesAtLeast = true
307
+ result.truncated = true
308
+ stack.length = 0
309
+ break
310
+ }
311
+ if (result.bytes > limits.maxBytes) {
312
+ result.bytesAtLeast = true
313
+ result.truncated = true
314
+ stack.length = 0
315
+ break
316
+ }
317
+ }
318
+ }
319
+ } catch (error) {
320
+ result.error = error instanceof Error ? error.message : String(error)
321
+ }
322
+ return result
323
+ }
324
+
325
+ /**
326
+ * Cheap "is this a regular file, and how big is it" probe used when a call has a
327
+ * single non-recursive target: directory walks are expensive, one lstat is not.
328
+ * @param {string} targetPath
329
+ * @returns {{ isFile: boolean, bytes: number }}
330
+ */
331
+ export function estimateFile(targetPath) {
332
+ try {
333
+ const stat = lstatSync(targetPath)
334
+ if (stat.isFile()) return { isFile: true, bytes: stat.size }
335
+ } catch {
336
+ // missing target: nothing to meter
337
+ }
338
+ return { isFile: false, bytes: 0 }
339
+ }
340
+
341
+ /**
342
+ * Create the deletion policy facade for one activation.
343
+ * @param {any} config
344
+ * @param {{ quarantine?: any, logger?: { warn?: (message: string) => void }, cwd?: string, platform?: string, env?: Record<string, string|undefined> }} [options]
345
+ * @returns {DeletePolicy}
346
+ */
347
+ export function createDeletePolicy(config, options = {}) {
348
+ const rawCwd = options.cwd
349
+ const cwd = typeof rawCwd === 'string' && rawCwd === ''
350
+ ? ''
351
+ : resolve(rawCwd ?? process.cwd())
352
+ const roots = buildProtectedRoots(config, {
353
+ cwd,
354
+ platform: options.platform,
355
+ env: options.env,
356
+ })
357
+ const thresholds = {
358
+ maxFiles: Math.max(1, Number(config?.deleteGuard?.thresholds?.maxFiles) || 1000),
359
+ maxBytes: Math.max(1, Number(config?.deleteGuard?.thresholds?.maxBytes) || 314572800),
360
+ perCallMaxFiles: Math.max(1, Number(config?.deleteGuard?.thresholds?.perCallMaxFiles) || 20000),
361
+ }
362
+ /** @type {Map<string, { files: number, bytes: number, calls: number, at: string, samples: Array<{ ts: string, tool: string|null, target: string, files: number, bytes: number }> }>} */
363
+ const sessions = new Map()
364
+
365
+ /**
366
+ * @param {string} sessionId
367
+ * @returns {{ files: number, bytes: number, calls: number, samples: Array<{ ts: string, tool: string|null, target: string, files: number, bytes: number }> }}
368
+ */
369
+ function sessionState(sessionId) {
370
+ const key = sessionId || 'unknown'
371
+ let state = sessions.get(key)
372
+ if (!state) {
373
+ state = { files: 0, bytes: 0, calls: 0, at: new Date().toISOString(), samples: [] }
374
+ sessions.set(key, state)
375
+ }
376
+ return state
377
+ }
378
+
379
+ /**
380
+ * Decide one parsed delete intent.
381
+ * @param {any} intent result of `parseDeleteIntent`
382
+ * @param {{ sessionId?: string|null, tool?: string|null, ruleIds?: string[] }} [context]
383
+ * @returns {DeleteAssessment}
384
+ */
385
+ function assess(intent, context = {}) {
386
+ /** @type {string[]} */
387
+ const ruleIds = []
388
+ /** @type {string[]} */
389
+ const reasons = []
390
+ /** @type {string[]} */
391
+ const extraNotes = []
392
+ /** @type {Array<{ raw: string, resolvedPath: string|null, level: TargetLevel, label: string, hasGlob: boolean, rootLike: boolean, withinQuarantine: boolean }>} */
393
+ const targets = (intent?.targets ?? []).map(target => {
394
+ const resolvedPath = typeof target?.resolvedPath === 'string' ? target.resolvedPath : null
395
+ const classification = resolvedPath
396
+ ? classifyPath(resolvedPath, roots)
397
+ : { level: /** @type {TargetLevel} */ ('low'), label: '无法解析的目标' }
398
+ return {
399
+ raw: target?.raw ?? '',
400
+ resolvedPath,
401
+ level: classification.level,
402
+ label: classification.label,
403
+ hasGlob: Boolean(target?.hasGlob),
404
+ rootLike: Boolean(target?.rootLike),
405
+ withinQuarantine: Boolean(resolvedPath && config?.paths?.quarantineDir && isWithin(config.paths.quarantineDir, resolvedPath)),
406
+ }
407
+ })
408
+
409
+ const maxLevel = targets.reduce((worst, target) => {
410
+ const rank = { critical: 4, high: 3, medium: 2, low: 1 }
411
+ return rank[target.level] > rank[worst] ? target.level : worst
412
+ }, /** @type {TargetLevel} */ ('low'))
413
+
414
+ let kind = /** @type {'allow'|'ask'|'deny'} */ ('allow')
415
+
416
+ if (!intent || intent.isDelete !== true) {
417
+ return baseAssessment(kind, null, ruleIds, reasons, targets, null, null, extraNotes)
418
+ }
419
+ if (intent.dryRun) {
420
+ return baseAssessment('allow', null, ruleIds, ['dry-run 调用不会真正删除'], targets, null, null, extraNotes)
421
+ }
422
+
423
+ /** @type {{ files: number, bytes: number, filesAtLeast: boolean, bytesAtLeast: boolean } | null} */
424
+ let scale = null
425
+
426
+ if (targets.some(target => target.level === 'critical')) {
427
+ const first = targets.find(target => target.level === 'critical')
428
+ ruleIds.push('VG-DEL-01')
429
+ reasons.push(`目标是关键保护根(${first?.label ?? '关键目录'}):${first?.raw ?? ''}`)
430
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.critical, 'deny'))
431
+ }
432
+
433
+ if (intent.unparsed) {
434
+ ruleIds.push('VG-DEL-02')
435
+ reasons.push('无法可靠解析删除目标,按不可信处理')
436
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.unknownTarget, 'ask'))
437
+ }
438
+ if (intent.deleteKind === 'truncate') {
439
+ reasons.push('该命令会清空或覆盖文件原有内容(截断写入)')
440
+ }
441
+
442
+ const quarantineDir = config?.paths?.quarantineDir
443
+ // A deletion whose targets come from a pipeline (`Get-ChildItem … |
444
+ // Remove-Item`) has the same blast radius as a wildcard even when the
445
+ // command carries no `-Recurse`: measure it and ask like a wildcard.
446
+ const pipelineLike = Array.isArray(intent.riskSignals) && intent.riskSignals.includes('pipeline-generic')
447
+ const measurable = target => Boolean(target.resolvedPath)
448
+ && target.level !== 'critical'
449
+ && !(quarantineDir && isWithin(quarantineDir, /** @type {string} */ (target.resolvedPath)))
450
+ const shouldWalk = (intent.recursive || intent.wildcard || pipelineLike || targets.length > 1)
451
+ && targets.every(target => target.level !== 'critical')
452
+ if (shouldWalk) {
453
+ const scalars = targets.filter(measurable).map(target => estimateScale(/** @type {string} */ (target.resolvedPath), {
454
+ maxFiles: thresholds.maxFiles,
455
+ maxBytes: thresholds.maxBytes,
456
+ cap: thresholds.perCallMaxFiles,
457
+ }))
458
+ scale = {
459
+ files: scalars.reduce((sum, item) => sum + item.files, 0),
460
+ bytes: scalars.reduce((sum, item) => sum + item.bytes, 0),
461
+ filesAtLeast: scalars.some(item => item.filesAtLeast),
462
+ bytesAtLeast: scalars.some(item => item.bytesAtLeast),
463
+ unknown: scalars.some(item => item.unknown === true),
464
+ }
465
+ } else {
466
+ // One literal file still counts: a 5 GiB file exceeds maxBytes even though
467
+ // it is "a single file", and repeated single-file deletes must accumulate
468
+ // toward the session threshold instead of escaping it forever.
469
+ const files = targets
470
+ .filter(measurable)
471
+ .map(target => estimateFile(/** @type {string} */ (target.resolvedPath)))
472
+ .filter(item => item.isFile)
473
+ if (files.length > 0) {
474
+ scale = {
475
+ files: files.length,
476
+ bytes: files.reduce((sum, item) => sum + item.bytes, 0),
477
+ filesAtLeast: false,
478
+ bytesAtLeast: false,
479
+ }
480
+ }
481
+ }
482
+ if (scale) {
483
+ const exceeds = scale.files > thresholds.maxFiles || scale.bytes > thresholds.maxBytes
484
+ if (exceeds) {
485
+ ruleIds.push('VG-DEL-03')
486
+ reasons.push(
487
+ `本次删除预计涉及 ${scale.filesAtLeast ? '≥' : ''}${scale.files} 个文件 / ${formatBytes(scale.bytes)},`
488
+ + `超过阈值 ${thresholds.maxFiles} 个 / ${formatBytes(thresholds.maxBytes)}`,
489
+ )
490
+ kind = strictestDecision(kind, 'deny')
491
+ }
492
+ if (scale.unknown === true) {
493
+ ruleIds.push('VG-DEL-11')
494
+ reasons.push('目录规模估算超时/超预算,实际删除范围无法确认')
495
+ kind = strictestDecision(kind, 'ask')
496
+ }
497
+ }
498
+
499
+ const session = sessionState(context.sessionId ?? null)
500
+ if (config?.deleteGuard?.observeScale !== false && scale) {
501
+ const projectedFiles = session.files + scale.files
502
+ const projectedBytes = session.bytes + scale.bytes
503
+ if (projectedFiles > thresholds.maxFiles || projectedBytes > thresholds.maxBytes) {
504
+ ruleIds.push('VG-DEL-04')
505
+ reasons.push(
506
+ `本会话累计删除将达 ${projectedFiles} 个文件 / ${formatBytes(projectedBytes)},超过会话阈值`,
507
+ )
508
+ if (session.samples.length > 0) {
509
+ const listed = session.samples.slice(-5).map(sample => `- ${sample.target}(${sample.files} 个文件)`)
510
+ extraNotes.push(`本会话已放行的删除:\n${listed.join('\n')}`)
511
+ } else {
512
+ extraNotes.push('本会话此前没有放行的删除记录')
513
+ }
514
+ kind = strictestDecision(kind, 'deny')
515
+ }
516
+ }
517
+
518
+ if (intent.wildcard) {
519
+ ruleIds.push('VG-DEL-05')
520
+ reasons.push('目标含通配符')
521
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.wildcard, 'ask'))
522
+ }
523
+ if (intent.recursive) {
524
+ ruleIds.push('VG-DEL-06')
525
+ reasons.push('递归删除')
526
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.recursive, 'ask'))
527
+ }
528
+ if (maxLevel === 'high') {
529
+ ruleIds.push('VG-DEL-07')
530
+ reasons.push(`目标是高风险目录(${targets.find(target => target.level === 'high')?.label ?? '用户主目录 / 项目根'})`)
531
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.high, 'ask'))
532
+ } else if (maxLevel === 'medium') {
533
+ ruleIds.push('VG-DEL-08')
534
+ reasons.push(`目标是高频大目录(${targets.find(target => target.level === 'medium')?.label ?? ''})`)
535
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.medium, 'allow'))
536
+ }
537
+ if (intent.riskSignals?.includes('mirror-delete')) {
538
+ ruleIds.push('VG-DEL-09')
539
+ reasons.push('robocopy /MIR 会删除目标端多余文件')
540
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.recursive, 'ask'))
541
+ }
542
+ if (pipelineLike) {
543
+ ruleIds.push('VG-DEL-10')
544
+ reasons.push('删除目标来自管道上游,可能一次删除整批文件')
545
+ kind = strictestDecision(kind, normalizeAction(config?.deleteGuard?.wildcard, 'ask'))
546
+ }
547
+
548
+ // Reversible deletion only for decisions that actually block the command,
549
+ // and only for literal single targets: a wildcard target can never be moved
550
+ // back unambiguously (FR-4.4). A high-level root is never captured either:
551
+ // moving a whole project or home directory into quarantine is itself a
552
+ // destructive act, and an ancestor of the workspace must be refused as a
553
+ // move, not relocated.
554
+ let quarantineResult = null
555
+ if (kind === 'deny' && config?.mode === 'enforce' && options.quarantine?.enabled) {
556
+ const capturable = targets.filter(target =>
557
+ target.resolvedPath
558
+ && intent.deleteKind !== 'truncate'
559
+ && !target.hasGlob
560
+ && !target.rootLike
561
+ && (target.level === 'low' || target.level === 'medium')
562
+ && !target.withinQuarantine
563
+ && pathKey(target.resolvedPath) !== pathKey(cwd))
564
+ if (capturable.length > 0 && capturable.length === targets.length) {
565
+ quarantineResult = options.quarantine.capture(capturable, {
566
+ tool: context.tool ?? null,
567
+ session: context.sessionId ?? null,
568
+ reason: reasons.join(';'),
569
+ ruleIds,
570
+ })
571
+ if (quarantineResult.quarantined.length > 0) {
572
+ reasons.push(
573
+ `已移入隔离区 ${quarantineResult.quarantined.length} 项(可用 vigil_quarantine action=restore 恢复)`,
574
+ )
575
+ }
576
+ }
577
+ }
578
+
579
+ if (scale && (kind === 'allow' || kind === 'ask') && config?.deleteGuard?.observeScale !== false) {
580
+ session.files += scale.files
581
+ session.bytes += scale.bytes
582
+ session.calls += 1
583
+ session.at = new Date().toISOString()
584
+ const sample = {
585
+ ts: session.at,
586
+ tool: context.tool ?? null,
587
+ target: targets.map(target => target.raw).join(' '),
588
+ files: scale.files,
589
+ bytes: scale.bytes,
590
+ }
591
+ session.samples.push(sample)
592
+ if (session.samples.length > 50) session.samples.shift()
593
+ }
594
+
595
+ return baseAssessment(kind, reasons.join(';') || null, ruleIds, reasons, targets, scale, quarantineResult, extraNotes, session)
596
+ }
597
+
598
+ return {
599
+ assess,
600
+ roots,
601
+ thresholds,
602
+ /** @param {string} [sessionId] */
603
+ sessionStats(sessionId) {
604
+ const state = sessionState(sessionId ?? null)
605
+ return {
606
+ session: sessionId ?? 'unknown',
607
+ files: state.files,
608
+ bytes: state.bytes,
609
+ calls: state.calls,
610
+ last: state.at,
611
+ thresholds: { ...thresholds },
612
+ }
613
+ },
614
+ reset() {
615
+ sessions.clear()
616
+ },
617
+ /** @returns {string[]} */
618
+ describeRoots() {
619
+ /** @type {string[]} */
620
+ const lines = []
621
+ for (const root of roots.criticalTrees) lines.push(`critical(目录树): ${root.path} — ${root.label}`)
622
+ for (const root of roots.criticalBoundary) lines.push(`critical(边界): ${root.path} — ${root.label}`)
623
+ for (const root of roots.criticalContainers) lines.push(`critical(内部): ${root.path} — ${root.label}`)
624
+ for (const root of roots.highExact) lines.push(`high: ${root.path} — ${root.label}`)
625
+ for (const root of roots.mediumContainers) lines.push(`medium: ${root.path} — ${root.label}`)
626
+ return lines
627
+ },
628
+ }
629
+ }
630
+
631
+ /** @typedef {ReturnType<typeof createDeletePolicy>} DeletePolicy */
632
+
633
+ /**
634
+ * @typedef {object} DeleteAssessment
635
+ * @property {'allow'|'ask'|'deny'} kind
636
+ * @property {string|null} reason
637
+ * @property {string[]} ruleIds
638
+ * @property {string[]} reasons
639
+ * @property {Array<object>} targets
640
+ * @property {{ files: number, bytes: number, filesAtLeast: boolean, bytesAtLeast: boolean } | null} scale
641
+ * @property {{ quarantined: Array<object>, skipped: Array<object> } | null} quarantine
642
+ * @property {string[]} notes
643
+ * @property {{ files: number, bytes: number, calls: number } | null} session
644
+ */
645
+
646
+ /**
647
+ * @param {'allow'|'ask'|'deny'} kind
648
+ * @param {string|null} reason
649
+ * @param {string[]} ruleIds
650
+ * @param {string[]} reasons
651
+ * @param {Array<object>} targets
652
+ * @param {DeleteAssessment['scale']} scale
653
+ * @param {DeleteAssessment['quarantine']} quarantine
654
+ * @param {string[]} notes
655
+ * @param {{ files: number, bytes: number, calls: number }|null} [session]
656
+ * @returns {DeleteAssessment}
657
+ */
658
+ function baseAssessment(kind, reason, ruleIds, reasons, targets, scale, quarantine, notes, session = null) {
659
+ const composed = [...new Set([...(reasons ?? []), ...(notes ?? [])].filter(item => typeof item === 'string' && item.trim() !== ''))]
660
+ return {
661
+ kind,
662
+ reason: composed.length > 0 ? composed.join(';') : reason,
663
+ ruleIds: [...new Set(ruleIds)],
664
+ reasons: [...reasons],
665
+ targets,
666
+ scale,
667
+ quarantine,
668
+ notes: [...notes],
669
+ session: session ? { files: session.files, bytes: session.bytes, calls: session.calls } : null,
670
+ }
671
+ }
672
+
673
+ /**
674
+ * @param {unknown} value
675
+ * @param {'allow'|'ask'|'deny'} fallback
676
+ * @returns {'allow'|'ask'|'deny'}
677
+ */
678
+ function normalizeAction(value, fallback) {
679
+ return value === 'allow' || value === 'ask' || value === 'deny' ? value : fallback
680
+ }