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
package/src/tools.js ADDED
@@ -0,0 +1,727 @@
1
+ /**
2
+ * Agent-facing tools (FR-1.6, FR-4.2, FR-6.2, FR-5).
3
+ *
4
+ * These are the deliberate, gated interfaces for the operations dsh-vigil would
5
+ * otherwise have to do silently:
6
+ *
7
+ * - `vigil_scan` — static audit of a plugin package (never executes it)
8
+ * - `vigil_status` — what is active, what fired, where state lives
9
+ * - `vigil_quarantine` — list / restore / expire / permanently purge entries
10
+ * - `vigil_audit` — tail / verify hash chain / export JSON or CSV
11
+ * - `vigil_integrity` — self-integrity status, re-check, trusted rebaseline
12
+ *
13
+ * Every tool reads the *current* runtime generation through `getRuntime()`, so a
14
+ * value saved on the Settings page is visible to the next tool call without a
15
+ * plugin reload.
16
+ *
17
+ * All tools return plain JSON and render a short text card. They are plain
18
+ * `ToolDefinition` objects (no `defineTool` dependency) so the browser-facing
19
+ * half of the bundle stays independent of the Host tool package.
20
+ *
21
+ * @module dsh-vigil/tools
22
+ */
23
+
24
+ import { statSync } from 'node:fs'
25
+ import { join, resolve } from 'node:path'
26
+ import { scanPluginDirectory, formatReportCard } from './audit/scan.js'
27
+ import { describePackDir, getRulePack, pinRulePack, readRuleLock, reloadRulePack, verifyRulePack } from './rules/pack.js'
28
+ import { formatBytes, nowIso, resolvePath, truncate } from './util.js'
29
+
30
+ /** Shared JSON-schema fragment: an open object result. */
31
+ const OPEN_OBJECT = { type: 'object', properties: {}, additionalProperties: true }
32
+
33
+ /**
34
+ * @param {(args: unknown, value: unknown) => Array<{type:'text', text:string}>} render
35
+ * @param {object} schema
36
+ * @returns {{schema: object, render: typeof render}}
37
+ */
38
+ function output(schema, render) {
39
+ return { schema, render }
40
+ }
41
+
42
+ /**
43
+ * Register every dsh-vigil tool on the Harness tool registry.
44
+ *
45
+ * @param {any} ctx plugin context with the `tools` service
46
+ * @param {object} deps
47
+ * @param {() => any} deps.getRuntime current runtime generation
48
+ * @param {() => string[]} deps.getConfigWarnings latest config warnings
49
+ * @param {() => boolean} deps.isDisabled kill-switch probe
50
+ * @param {() => void} [deps.ensureFresh] refresh the runtime if config changed
51
+ * @param {() => Promise<any>} [deps.sageInstall] force a Sage download/retry
52
+ * @param {() => object} [deps.getSageUpdate] latest auto-update check state
53
+ * @param {() => Promise<any>} [deps.sageUpdate] force a Sage version check/upgrade
54
+ * @param {() => object} [deps.getInstallScan] install-watcher summary (last new-plugin audit)
55
+ * @param {string} deps.version
56
+ * @param {string} [deps.cwd]
57
+ * @returns {Array<() => void>} disposers
58
+ */
59
+ export function registerTools(ctx, deps) {
60
+ const disposers = []
61
+ // An empty effective cwd means "unknown" (the host runs inside the Harness
62
+ // home): relative scan paths must not silently resolve there.
63
+ const cwdOf = typeof deps.getCwd === 'function' ? deps.getCwd : () => deps.cwd ?? process.cwd()
64
+ const runtime = () => {
65
+ deps.ensureFresh?.()
66
+ return deps.getRuntime()
67
+ }
68
+ const register = definition => {
69
+ disposers.push(ctx.tools.register(definition))
70
+ }
71
+
72
+ register({
73
+ name: 'vigil_scan',
74
+ description: [
75
+ 'Statically audit a dsh plugin package before installing or trusting it.',
76
+ 'Reads package.json, cordis.patch.yml and source files with regular expressions, a comment/string-aware masker and (for JS) optional AST alias analysis via acorn; it NEVER imports or executes the scanned code.',
77
+ 'Returns findings with file and line evidence, a severity (blocker/review/notice/info), a "what this means" narrative, and one mitigation step. AST hit severity follows the scan.ast.level setting (low/medium/high).',
78
+ 'Paths may be outside the workspace; the scan is read-only.',
79
+ ].join(' '),
80
+ parameters: {
81
+ type: 'object',
82
+ additionalProperties: false,
83
+ properties: {
84
+ path: { type: 'string', description: 'Plugin package directory (absolute, or relative to the current workspace).' },
85
+ format: { type: 'string', enum: ['card', 'json'], description: 'card (default) renders the terminal card; json returns the full report.' },
86
+ },
87
+ required: ['path'],
88
+ },
89
+ output: output(
90
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' }, report: { ...OPEN_OBJECT } }, additionalProperties: true },
91
+ (_args, value) => {
92
+ const result = /** @type {any} */ (value)
93
+ if (result?.format === 'json' && result.report) {
94
+ return [{ type: 'text', text: JSON.stringify(result.report, null, 2) }]
95
+ }
96
+ return [{ type: 'text', text: result?.card ?? '扫描失败' }]
97
+ },
98
+ ),
99
+ async execute(args) {
100
+ const rawPath = typeof args?.path === 'string' ? args.path : ''
101
+ if (rawPath.trim() === '') throw new Error('vigil_scan 需要 path 参数')
102
+ const format = args?.format === 'json' ? 'json' : 'card'
103
+ const base = cwdOf()
104
+ const looksAbsolute = /^[A-Za-z]:[\\/]/.test(rawPath) || rawPath.startsWith('/') || rawPath.startsWith('\\\\') || rawPath.startsWith('~')
105
+ if (!looksAbsolute && !base) {
106
+ throw new Error('当前工作目录未知(宿主进程运行在 Harness 主目录内);vigil_scan 请传绝对路径')
107
+ }
108
+ const target = resolvePath(rawPath, base || process.cwd())
109
+ let isDirectory = false
110
+ try {
111
+ isDirectory = statSync(target).isDirectory()
112
+ } catch {
113
+ isDirectory = false
114
+ }
115
+ // A wrong path is an input error, not a security finding: do not report it
116
+ // as a `blocker` (that would read as "this plugin is dangerous").
117
+ if (!isDirectory) throw new Error(`vigil_scan 需要一个插件目录:${target} 不存在或不是目录`)
118
+ const report = await scanPluginDirectory(target, { ast: runtime().config.scan?.ast })
119
+ // Record only meaningful scans: a clean package does not need an audit
120
+ // entry per call, but findings and unreadable targets do.
121
+ const summary = report?.summary ?? {}
122
+ const unreadable = (report?.findings ?? []).some(finding => finding.ruleId === 'VG-SCAN-01')
123
+ if ((Number(summary.blocker) || 0) + (Number(summary.review) || 0) > 0 || unreadable) {
124
+ runtime().audit?.record({
125
+ kind: 'event',
126
+ event: 'scan',
127
+ tool: 'vigil_scan',
128
+ decision: 'none',
129
+ ruleIds: [],
130
+ reason: `静态审计 ${target}:blocker=${summary.blocker ?? 0},review=${summary.review ?? 0}${unreadable ? '(目标不可读)' : ''}`,
131
+ extra: { target, summary },
132
+ })
133
+ }
134
+ const card = formatReportCard(report)
135
+ return {
136
+ ok: true,
137
+ format,
138
+ card,
139
+ ...(format === 'json' ? { report: sanitizeJson(report) } : { summary: report?.summary ?? null }),
140
+ }
141
+ },
142
+ })
143
+
144
+ register({
145
+ name: 'vigil_status',
146
+ description: [
147
+ 'Report dsh-vigil runtime status: mode, kill switch, protected-root count, deletion scale counters, quarantine size, Sage engine state, integrity state, audit log location, and recent decisions.',
148
+ 'Settings changed on the 守夜人 page apply to the next call; this tool shows the live generation.',
149
+ ].join(' '),
150
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
151
+ output: output(
152
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' } }, additionalProperties: true },
153
+ (_args, value) => [{ type: 'text', text: /** @type {any} */ (value)?.card ?? '无状态' }],
154
+ ),
155
+ async execute(_args, exec) {
156
+ const current = runtime()
157
+ const sessionId = exec?.agent?.id ? String(exec.agent.id) : undefined
158
+ const stats = current.policy.sessionStats(sessionId)
159
+ const quarantine = current.quarantine.stats()
160
+ const audit = current.audit.stats()
161
+ const interceptor = current.interceptor.stats()
162
+ const integrity = { state: current.integrity.state, describe: current.integrity.describe() }
163
+ const status = {
164
+ ok: true,
165
+ version: deps.version,
166
+ mode: current.config.mode,
167
+ killSwitch: deps.isDisabled?.(),
168
+ session: sessionId ?? null,
169
+ configWarnings: deps.getConfigWarnings?.() ?? [],
170
+ interceptor: { ...interceptor, describe: current.interceptor.describe() },
171
+ deletion: {
172
+ thresholds: current.policy.thresholds,
173
+ session: stats,
174
+ protectedRootCount: current.policy.roots.criticalExact.length
175
+ + current.policy.roots.criticalContainers.length
176
+ + current.policy.roots.highExact.length,
177
+ },
178
+ quarantine: { ...quarantine, describe: current.quarantine.describe() },
179
+ audit: { ...audit, path: current.audit.dir, describe: current.audit.describe() },
180
+ sage: {
181
+ ...current.sage.status,
182
+ autoUpdate: current.config.sage.autoUpdate !== false,
183
+ updateIntervalMs: current.config.sage.updateIntervalMs,
184
+ update: deps.getSageUpdate?.(),
185
+ describe: current.sage.describe(),
186
+ },
187
+ integrity,
188
+ rules: {
189
+ sources: Array.isArray(current.rulePack?.sources) ? current.rulePack.sources : [],
190
+ warnings: Array.isArray(current.rulePack?.warnings) ? current.rulePack.warnings : [],
191
+ externalDir: current.config.rules?.dir || '',
192
+ },
193
+ scan: {
194
+ astEnabled: current.config.scan?.ast?.enabled !== false,
195
+ astLevel: ['low', 'medium', 'high'].includes(current.config.scan?.ast?.level) ? current.config.scan.ast.level : 'medium',
196
+ },
197
+ installScan: deps.getInstallScan?.() ?? null,
198
+ paths: current.config.paths,
199
+ checkedAt: nowIso(),
200
+ }
201
+ return { ok: true, ...sanitizeJson(status), card: renderStatusCard(status) }
202
+ },
203
+ })
204
+
205
+ register({
206
+ name: 'vigil_doctor',
207
+ description: [
208
+ 'Run a self-check of dsh-vigil and report one pass/fail line per subsystem: hook mount, self-protection guard, browser routes (feed/approval/quarantine/scan/update), inline approval, quarantine, integrity baseline/canary/heartbeat, rule-pack sources, Sage engine, install watcher, audit log and config warnings.',
209
+ 'Use it after installing or changing configuration when something looks inert; it never mutates state.',
210
+ ].join(' '),
211
+ parameters: { type: 'object', additionalProperties: false, properties: {} },
212
+ output: output(
213
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' }, checks: { type: 'array', items: { ...OPEN_OBJECT } } }, additionalProperties: true },
214
+ (_args, value) => {
215
+ const result = /** @type {any} */ (value)
216
+ return [{ type: 'text', text: result?.card ?? '自检失败' }]
217
+ },
218
+ ),
219
+ async execute() {
220
+ const current = runtime()
221
+ /** @type {Array<{ name: string, ok: boolean, detail: string }>} */
222
+ const checks = []
223
+ const push = (name, ok, detail) => checks.push({ name, ok: Boolean(ok), detail: String(detail ?? '') })
224
+ const killSwitch = deps.isDisabled?.() === true
225
+
226
+ push('插件', true, `v${deps.version} · 模式 ${current.config.mode}`)
227
+ push('停机开关', !killSwitch, killSwitch ? '已启用:所有拦截被跳过' : '未启用')
228
+ push('pre-execute 钩子', current.interceptor.enabled, current.interceptor.describe())
229
+
230
+ const approval = deps.getApproval?.()
231
+ const pending = typeof approval?.size === 'number' ? approval.size : 0
232
+ push('对话内审批', current.config.notify.inlineApproval !== false, `超时 ${Math.round((Number(current.config.notify.approvalTimeoutMs) || 120000) / 1000)}s · 待确认 ${pending}`)
233
+
234
+ const routes = deps.getRoutes?.() ?? {}
235
+ const routeNames = Object.keys(routes)
236
+ const badRoutes = routeNames.filter(name => routes[name] !== 'ok')
237
+ push('浏览器路由', routeNames.length > 0 && badRoutes.length === 0,
238
+ routeNames.length === 0 ? '未注册' : badRoutes.length === 0 ? `${routeNames.length} 条已注册` : `${badRoutes.map(name => `${name}=${routes[name]}`).join(',')}`)
239
+
240
+ const quarantine = current.quarantine.stats()
241
+ push('隔离区', quarantine.enabled, `${quarantine.count} 项 / ${formatBytes(quarantine.bytes)} · ${quarantine.dir}`)
242
+
243
+ const integrity = current.integrity.state
244
+ const integrityOk = integrity.baseline?.state === 'match' && integrity.canary?.state === 'ok' && integrity.heartbeat?.state === 'ok'
245
+ push('完整性', integrityOk, current.integrity.describe())
246
+
247
+ const rules = current.rulePack
248
+ push('规则包', (rules?.warnings?.length ?? 0) === 0, `${rules?.sources?.length ?? 0} 个来源${rules?.warnings?.length ? ` · ${rules.warnings.length} 条警告` : ''}`)
249
+
250
+ const sageEnabled = current.config.sage.enabled !== false
251
+ push('Sage', !sageEnabled || current.sage.status.state === 'ready',
252
+ sageEnabled ? current.sage.describe() : '未启用(可选)')
253
+
254
+ const install = deps.getInstallScan?.()
255
+ push('安装审计', !install?.lastError, install?.description ?? '不可用')
256
+
257
+ const auditStats = current.audit.stats()
258
+ const auditFiles = Array.isArray(auditStats.files) ? auditStats.files.length : Number(auditStats.files) || 0
259
+ push('审计日志', current.config.auditLog.enabled !== false, `${auditStats.total} 条 · ${auditFiles} 个文件 · ${formatBytes(auditStats.sizeBytes ?? 0)}`)
260
+ const anchor = typeof current.audit.anchorState === 'function' ? current.audit.anchorState() : null
261
+ if (anchor?.enabled) {
262
+ push('审计锚定', anchor.state === 'ok', anchor.state === 'ok'
263
+ ? `HMAC 锚点一致(seq ${anchor.seq ?? '?'})`
264
+ : `锚点状态:${anchor.state}${anchor.error ? `(${anchor.error})` : ''}`)
265
+ }
266
+
267
+ push('配置', (deps.getConfigWarnings?.() ?? []).length === 0,
268
+ (deps.getConfigWarnings?.() ?? []).length === 0 ? '无警告' : (deps.getConfigWarnings?.() ?? []).join(';'))
269
+
270
+ const failed = checks.filter(check => !check.ok)
271
+ const card = [
272
+ `守夜人自检:${checks.length - failed.length} / ${checks.length} 通过`,
273
+ ...checks.map(check => `${check.ok ? '✓' : '✗'} ${check.name} — ${check.detail}`),
274
+ ...(failed.length > 0 ? ['', '有项目未通过:先看对应说明;需要临时停用时创建 DISABLED 或设置 DSH_VIGIL_DISABLED=1。'] : []),
275
+ ].join('\n')
276
+ return { ok: failed.length === 0, checks, card }
277
+ },
278
+ })
279
+
280
+ register({
281
+ name: 'vigil_rules',
282
+ description: [
283
+ 'Inspect, verify or pin the external YAML rule pack (the operator directory, default <DSH_HOME>/vigil/rules).',
284
+ 'status lists which pack files are loaded and their hashes; verify compares them with the hash lock; pin trusts the current files by writing the lock used on the next load.',
285
+ 'Pinned files that change afterwards are rejected on load (fail-safe), so a tampered external pack cannot silently weaken detection.',
286
+ 'check fetches the configured rules.source manifest and reports whether a newer pack exists; update downloads, validates and installs it (same path as the settings page auto-update).',
287
+ ].join(' '),
288
+ parameters: {
289
+ type: 'object',
290
+ additionalProperties: false,
291
+ properties: {
292
+ action: { type: 'string', enum: ['status', 'verify', 'pin', 'check', 'update'], description: 'Operation to perform.' },
293
+ },
294
+ required: ['action'],
295
+ },
296
+ output: output(
297
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' } }, additionalProperties: true },
298
+ (_args, value) => [{ type: 'text', text: /** @type {any} */ (value)?.card ?? '' }],
299
+ ),
300
+ async execute(args) {
301
+ const current = runtime()
302
+ const action = String(args?.action ?? 'status')
303
+ const stateDir = typeof current.config.paths?.stateDir === 'string' ? current.config.paths.stateDir : ''
304
+ const configured = typeof current.config.rules?.dir === 'string' ? current.config.rules.dir : ''
305
+ const externalDir = configured !== '' ? resolvePath(configured, stateDir) : (stateDir ? join(stateDir, 'rules') : '')
306
+ const lockPath = stateDir ? join(stateDir, 'rules-lock.json') : ''
307
+ const describeFiles = info => (info.names.length === 0
308
+ ? '(无 .yaml 文件)'
309
+ : info.names.map(name => ` · ${name} sha256:${(info.files[name] ?? '').slice(0, 16)}…`).join('\n'))
310
+
311
+ if (action === 'check' || action === 'update') {
312
+ const run = deps.runRulesUpdate
313
+ if (typeof run !== 'function') return { ok: false, action, card: '规则库更新不可用(未挂载更新器)' }
314
+ const result = await run({ update: action === 'update' })
315
+ const source = typeof current.config.rules?.source === 'string' ? current.config.rules.source : ''
316
+ const state = /** @type {any} */ (result).state ?? {}
317
+ const card = result.ok === false
318
+ ? `规则库${action === 'update' ? '更新' : '检查'}失败:${result.error ?? '未知原因'}`
319
+ : action === 'update'
320
+ ? `规则库已更新到 ${result.version ?? '?'}(${(result.files ?? []).length} 个文件)`
321
+ : result.available
322
+ ? `发现新规则库:当前 ${result.currentVersion ?? '未安装'},最新 ${result.latestVersion}`
323
+ : `规则库已是最新(${result.latestVersion ?? '未知版本'})`
324
+ return {
325
+ ok: result.ok !== false,
326
+ action,
327
+ source,
328
+ ...result,
329
+ state,
330
+ card,
331
+ }
332
+ }
333
+
334
+ if (action === 'status') {
335
+ const info = describePackDir(externalDir)
336
+ const lock = readRuleLock(lockPath)
337
+ const pack = current.rulePack ?? getRulePack()
338
+ const card = [
339
+ '守夜人规则包:',
340
+ ` 外部目录:${externalDir || '未配置'}${info.exists ? '' : '(不存在)'}`,
341
+ ' 文件:',
342
+ describeFiles(info),
343
+ ` 规则锁:${lock ? `${Object.keys(lock.files).length} 个文件(${lock.pinnedAt ?? '未知时间'})` : '未建立'}`,
344
+ ` 当前生效来源:${(pack?.sources ?? []).length}`,
345
+ ...(info.error ? [` 错误:${info.error}`] : []),
346
+ ].join('\n')
347
+ return { ok: !info.error, action, dir: externalDir, files: info.files, locked: Boolean(lock), card }
348
+ }
349
+
350
+ if (action === 'verify') {
351
+ const result = verifyRulePack({ externalDir, lockPath })
352
+ const card = result.ok
353
+ ? `规则包与锁一致(${(result.files ?? []).length} 个文件)`
354
+ : [
355
+ `规则包校验失败:${result.state}`,
356
+ ...(result.error ? [` ${result.error}`] : []),
357
+ ...(result.mismatched?.length ? [` 内容被改动:${result.mismatched.join('、')}`] : []),
358
+ ...(result.unlisted?.length ? [` 未登记文件:${result.unlisted.join('、')}`] : []),
359
+ ...(result.missing?.length ? [` 锁中有但目录缺失:${result.missing.join('、')}`] : []),
360
+ ].join('\n')
361
+ return { ok: result.ok, action, ...result, card }
362
+ }
363
+
364
+ if (action !== 'pin') {
365
+ return {
366
+ ok: false,
367
+ action,
368
+ card: `未知操作:${action}(可用 status / verify / pin / check / update)`,
369
+ }
370
+ }
371
+
372
+ // pin
373
+ const pinned = pinRulePack({ externalDir, lockPath })
374
+ if (!pinned.ok) return { ok: false, action, card: `无法固定规则包:${pinned.error}` }
375
+ reloadRulePack({ externalDir, lockPath })
376
+ current.rulePack = getRulePack()
377
+ return {
378
+ ok: true,
379
+ action,
380
+ dir: externalDir,
381
+ lockPath,
382
+ files: pinned.files,
383
+ card: `已固定 ${pinned.files.length} 个规则文件;下次加载起,内容变化会被拒绝。`,
384
+ }
385
+ },
386
+ })
387
+
388
+ register({
389
+ name: 'vigil_quarantine',
390
+ description: [
391
+ 'Manage dsh-vigil\'s local quarantine of blocked deletions.',
392
+ 'action=list shows entries with original paths; action=restore moves one entry back (id required; force overwrites an occupied path by moving it aside); action=expire removes entries past their TTL; action=purge permanently deletes ONE entry and requires confirm=true.',
393
+ 'The quarantine never contains wildcard or unparseable targets: those were refused without movement, by design.',
394
+ ].join(' '),
395
+ parameters: {
396
+ type: 'object',
397
+ additionalProperties: false,
398
+ properties: {
399
+ action: { type: 'string', enum: ['list', 'restore', 'expire', 'purge'], description: 'Operation to perform.' },
400
+ id: { type: 'string', description: 'Quarantine entry id (required for restore and purge).' },
401
+ force: { type: 'boolean', description: 'restore: overwrite an occupied original path by moving it aside first.' },
402
+ confirm: { type: 'boolean', description: 'purge: must be true; the entry is permanently destroyed.' },
403
+ },
404
+ required: ['action'],
405
+ },
406
+ output: output(
407
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' } }, additionalProperties: true },
408
+ (_args, value) => [{ type: 'text', text: /** @type {any} */ (value)?.card ?? '' }],
409
+ ),
410
+ async execute(args) {
411
+ const current = runtime()
412
+ const action = args?.action
413
+ if (action === 'list') {
414
+ const entries = current.quarantine.entries()
415
+ return {
416
+ ok: true,
417
+ entries,
418
+ stats: current.quarantine.stats(),
419
+ card: entries.length === 0
420
+ ? `隔离区为空(${current.quarantine.dir})`
421
+ : [
422
+ `隔离区共 ${entries.length} 条:`,
423
+ ...entries.map(entry => `- ${entry.id} ${entry.kind === 'directory' ? '[目录]' : '[文件]'} ${entry.originalPath} (${formatBytes(entry.bytes)}) ${entry.createdAt}`),
424
+ '恢复:vigil_quarantine action=restore id=<id>',
425
+ ].join('\n'),
426
+ }
427
+ }
428
+ if (action === 'restore') {
429
+ const id = typeof args?.id === 'string' ? args.id : ''
430
+ if (id === '') throw new Error('restore 需要 id 参数')
431
+ const result = current.quarantine.restore(id, { force: args?.force === true })
432
+ current.audit?.record({
433
+ kind: 'quarantine',
434
+ event: 'restore',
435
+ tool: 'vigil_quarantine',
436
+ decision: result.ok ? 'allow' : 'deny',
437
+ ruleIds: [],
438
+ reason: result.ok ? `已恢复 ${id} → ${result.restoredTo}` : `恢复失败 ${id}:${result.error}`,
439
+ })
440
+ return {
441
+ ok: result.ok,
442
+ ...result,
443
+ card: result.ok
444
+ ? `已恢复:${result.restoredTo}${result.conflictPath ? `(原位置已有内容,已移到 ${result.conflictPath})` : ''}`
445
+ : `恢复失败:${result.error}`,
446
+ }
447
+ }
448
+ if (action === 'expire') {
449
+ const result = current.quarantine.expire()
450
+ current.audit?.record({
451
+ kind: 'quarantine',
452
+ event: 'expire',
453
+ tool: 'vigil_quarantine',
454
+ decision: 'none',
455
+ ruleIds: [],
456
+ reason: `清理过期隔离条目 ${result.expired.length} 个`,
457
+ })
458
+ return { ok: true, ...result, card: `已清理 ${result.expired.length} 个过期条目${result.expired.length ? `:${result.expired.join('、')}` : ''}` }
459
+ }
460
+ if (action === 'purge') {
461
+ const id = typeof args?.id === 'string' ? args.id : ''
462
+ if (id === '') throw new Error('purge 需要 id 参数')
463
+ const result = current.quarantine.purge(id, { confirm: args?.confirm === true })
464
+ current.audit?.record({
465
+ kind: 'quarantine',
466
+ event: 'purge',
467
+ tool: 'vigil_quarantine',
468
+ decision: result.ok ? 'allow' : 'deny',
469
+ ruleIds: [],
470
+ reason: result.ok ? `永久删除隔离条目 ${id}` : `未永久删除 ${id}:${result.error}`,
471
+ })
472
+ return { ok: result.ok, ...result, card: result.ok ? `已永久删除 ${id}` : `未删除:${result.error}` }
473
+ }
474
+ throw new Error(`未知 action:${String(action)}`)
475
+ },
476
+ })
477
+
478
+ register({
479
+ name: 'vigil_audit',
480
+ description: [
481
+ 'Inspect dsh-vigil\'s hash-chained audit log.',
482
+ 'action=tail shows the newest records; action=verify walks the chain and reports the first broken link; action=json / action=csv export records for team review.',
483
+ 'Records contain scrubbed argument summaries only: no file contents, and secret-shaped values are redacted.',
484
+ ].join(' '),
485
+ parameters: {
486
+ type: 'object',
487
+ additionalProperties: false,
488
+ properties: {
489
+ action: { type: 'string', enum: ['tail', 'verify', 'json', 'csv'], description: 'Operation to perform.' },
490
+ limit: { type: 'integer', description: 'Maximum records to read/export (tail default 20, json/csv default 200; capped at 200/1000).' },
491
+ },
492
+ required: ['action'],
493
+ },
494
+ output: output(
495
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' } }, additionalProperties: true },
496
+ (_args, value) => {
497
+ const result = /** @type {any} */ (value)
498
+ // `action=json` is an export: the model has to receive the records, not
499
+ // a sentence saying how many were exported.
500
+ if (result?.exported && Array.isArray(result.exported.entries)) {
501
+ return [{ type: 'text', text: JSON.stringify(result.exported, null, 2) }]
502
+ }
503
+ return [{ type: 'text', text: result?.card ?? '' }]
504
+ },
505
+ ),
506
+ async execute(args) {
507
+ const current = runtime()
508
+ const action = args?.action
509
+ const requested = Number(args?.limit)
510
+ const limit = Number.isFinite(requested) && requested > 0
511
+ ? Math.min(Math.floor(requested), action === 'tail' ? 200 : 1000)
512
+ : undefined
513
+ if (action === 'verify') {
514
+ const result = current.audit.verify()
515
+ const anchor = result.anchor ?? { enabled: false, state: 'disabled' }
516
+ const anchorLabel = {
517
+ disabled: '未启用',
518
+ ok: '锚点一致',
519
+ missing: '锚点缺失',
520
+ 'no-key': '缺少密钥',
521
+ 'bad-mac': 'MAC 不匹配',
522
+ mismatch: '链头哈希与锚点不符',
523
+ ahead: '锚点超前(链被回滚?)',
524
+ gap: '锚点序号不在链上',
525
+ corrupt: '锚点文件损坏',
526
+ }[anchor.state] ?? anchor.state
527
+ return {
528
+ ok: result.ok,
529
+ ...result,
530
+ card: (result.ok
531
+ ? `审计链校验通过:${result.entries} 条记录,无断裂`
532
+ : `审计链断裂:${result.reason}(第 ${result.firstBad?.seq ?? '?'} 条,文件 ${result.firstBad?.file ?? '?'})`)
533
+ + `;锚点:${anchorLabel}${anchor.enabled && anchor.seq ? `(seq ${anchor.seq})` : ''}`,
534
+ }
535
+ }
536
+ if (action === 'json') {
537
+ const exported = current.audit.exportJson({ limit: limit ?? 200 })
538
+ return { ok: true, exported, card: `已导出 ${exported.entries.length} 条 JSON 记录(共 ${current.audit.stats().total} 条)` }
539
+ }
540
+ if (action === 'csv') {
541
+ const csv = current.audit.exportCsv({ limit: limit ?? 200 })
542
+ return { ok: true, csv, card: csv.split('\n').slice(0, 30).join('\n') }
543
+ }
544
+ const entries = current.audit.read({ limit: limit ?? 20 })
545
+ return {
546
+ ok: true,
547
+ entries,
548
+ card: entries.length === 0
549
+ ? '审计日志为空(尚未评估过任何调用)'
550
+ : [
551
+ `最近 ${entries.length} 条审计记录:`,
552
+ ...entries.map(entry => `- ${entry.ts} ${entry.tool ?? '-'} ${entry.decision}${entry.wouldBe ? `(wouldBe=${entry.wouldBe})` : ''} ${(entry.ruleIds ?? []).join(',')} ${truncate(entry.reason ?? '', 120)}`),
553
+ ].join('\n'),
554
+ }
555
+ },
556
+ })
557
+
558
+ register({
559
+ name: 'vigil_sage',
560
+ description: [
561
+ 'Inspect, install, or upgrade dsh-vigil\'s optional Sage engine.',
562
+ 'Enabling Sage on the 守夜人 settings page downloads the newest stable engine (@gendigital/sage-core) and rule set (@gendigital/sage-omp resources) into <DSH_HOME>/vigil/sage automatically; with auto-update on it re-checks on an interval and installs newer pairs after verifying they load.',
563
+ 'action=status reports the install and last update check; action=install forces a download/repair of the newest pair; action=update forces a version check and upgrade now.',
564
+ ].join(' '),
565
+ parameters: {
566
+ type: 'object',
567
+ additionalProperties: false,
568
+ properties: {
569
+ action: { type: 'string', enum: ['status', 'install', 'update'], description: 'Operation to perform.' },
570
+ },
571
+ required: ['action'],
572
+ },
573
+ timeoutMs: 300000,
574
+ output: output(
575
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' } }, additionalProperties: true },
576
+ (_args, value) => [{ type: 'text', text: /** @type {any} */ (value)?.card ?? '' }],
577
+ ),
578
+ async execute(args) {
579
+ const current = runtime()
580
+ if (args?.action === 'install') {
581
+ if (typeof deps.sageInstall !== 'function') throw new Error('当前会话无法触发 Sage 下载')
582
+ const result = await deps.sageInstall()
583
+ const location = result?.location ?? null
584
+ return {
585
+ ok: Boolean(result?.ok),
586
+ result: sanitizeJson(result),
587
+ card: result?.ok
588
+ ? `Sage 已就绪:${location?.rules ?? 0} 条规则(引擎 ${location?.version ?? '?'}),目录 ${result?.dir ?? ''}`
589
+ : `Sage 下载失败:${result?.error ?? result?.skipped ?? '未知原因'}(尝试:${(result?.attempts ?? []).map(item => `${item.kind}:${item.ok ? 'ok' : 'fail'}`).join(', ') || '无'})`,
590
+ }
591
+ }
592
+ if (args?.action === 'update') {
593
+ if (typeof deps.sageUpdate !== 'function') throw new Error('当前会话无法触发 Sage 更新检查')
594
+ const result = await deps.sageUpdate()
595
+ const installed = runtime().sage.status.version ?? '?'
596
+ return {
597
+ ok: Boolean(result?.ok),
598
+ result: sanitizeJson(result),
599
+ update: sanitizeJson(deps.getSageUpdate?.() ?? null),
600
+ card: result?.checked === false
601
+ ? `近期已检查过(间隔未到);当前引擎 ${installed}。可用 vigil_sage action=update 前修改 updateIntervalMs,或等待下次。`
602
+ : result?.updated
603
+ ? `Sage 已更新:${result?.latestVersion ?? '?'}`
604
+ : result?.ok
605
+ ? `Sage 已是最新:${result?.latestVersion ?? installed}(当前 ${installed})`
606
+ : `Sage 更新失败:${result?.error ?? '未知原因'}(当前 ${installed})`,
607
+ }
608
+ }
609
+ const sageStatus = sanitizeJson({
610
+ ...current.sage.status,
611
+ autoUpdate: current.config.sage.autoUpdate !== false,
612
+ updateIntervalMs: current.config.sage.updateIntervalMs,
613
+ update: deps.getSageUpdate?.(),
614
+ })
615
+ return {
616
+ ok: true,
617
+ sage: sageStatus,
618
+ card: [
619
+ current.sage.describe(),
620
+ `自动更新:${current.config.sage.autoUpdate === false ? '关闭' : `开启(每 ${Math.round((Number(current.config.sage.updateIntervalMs) || 0) / 3600000)} 小时检查)`}`,
621
+ deps.getSageUpdate?.()?.checkedAt ? `上次检查:${deps.getSageUpdate().checkedAt}${deps.getSageUpdate().updateAvailable ? '(发现新版本)' : ''}` : '尚未检查更新',
622
+ ].join('\n'),
623
+ }
624
+ },
625
+ })
626
+
627
+ register({
628
+ name: 'vigil_integrity',
629
+ description: [
630
+ 'Inspect or refresh dsh-vigil\'s self-integrity state: shipped-file baseline hash, canary file, optional Ed25519 signature, and hook heartbeat tags.',
631
+ 'action=status reads the current state; action=check forces a re-check; action=rebaseline rewrites the baseline after a trusted upgrade or local change.',
632
+ 'This detects replacement; it cannot prevent it (a privileged attacker runs at the same privilege level).',
633
+ ].join(' '),
634
+ parameters: {
635
+ type: 'object',
636
+ additionalProperties: false,
637
+ properties: {
638
+ action: { type: 'string', enum: ['status', 'check', 'rebaseline'], description: 'Operation to perform.' },
639
+ },
640
+ required: ['action'],
641
+ },
642
+ output: output(
643
+ { type: 'object', properties: { ok: { type: 'boolean' }, card: { type: 'string' } }, additionalProperties: true },
644
+ (_args, value) => [{ type: 'text', text: /** @type {any} */ (value)?.card ?? '' }],
645
+ ),
646
+ async execute(args) {
647
+ const current = runtime()
648
+ const action = args?.action
649
+ if (action === 'rebaseline') {
650
+ const result = current.integrity.rebaseline()
651
+ current.audit?.record({
652
+ kind: 'integrity',
653
+ event: 'rebaseline',
654
+ tool: 'vigil_integrity',
655
+ decision: result.ok ? 'allow' : 'deny',
656
+ ruleIds: ['VG-INT-00'],
657
+ reason: result.ok ? `重建完整性基线 v${result.version},${result.files} 个文件` : `重建基线失败:${result.error}`,
658
+ })
659
+ return { ok: result.ok, ...result, state: current.integrity.state, card: result.ok ? `基线已重建:v${result.version},${result.files} 个文件` : `重建失败:${result.error}` }
660
+ }
661
+ if (action === 'check') current.integrity.check({ force: true })
662
+ const state = current.integrity.state
663
+ const alerts = current.integrity.alerts
664
+ return {
665
+ ok: true,
666
+ state,
667
+ alerts,
668
+ card: [
669
+ current.integrity.describe(),
670
+ `插件目录:${current.integrity.pluginDir}`,
671
+ ...(alerts.length > 0 ? ['告警:', ...alerts.map(item => `- ${item}`)] : []),
672
+ ].join('\n'),
673
+ }
674
+ },
675
+ })
676
+
677
+ return disposers
678
+ }
679
+
680
+ /**
681
+ * @param {any} status
682
+ * @returns {string}
683
+ */
684
+ function renderStatusCard(status) {
685
+ const lines = [
686
+ `dsh-vigil v${status.version} — 模式 ${status.mode}`,
687
+ `哨兵:${status.interceptor.describe}`,
688
+ `删除防护:单次阈值 ${status.deletion.thresholds.maxFiles} 个文件 / ${formatBytes(status.deletion.thresholds.maxBytes)};保护根 ${status.deletion.protectedRootCount} 个`,
689
+ `本会话累计(估算):${status.deletion.session.files} 个文件 / ${formatBytes(status.deletion.session.bytes)}`,
690
+ status.quarantine.describe,
691
+ status.audit.describe,
692
+ status.sage.describe,
693
+ `规则包:${status.rules.sources.length} 个来源${status.rules.externalDir ? `(外部目录 ${status.rules.externalDir})` : '(仅内置)'}`,
694
+ `静态审计:AST 别名分析${status.scan?.astEnabled === false ? '已关闭' : `已启用 · 命中等级 ${status.scan?.astLevel ?? 'medium'}`}`,
695
+ status.installScan?.description ?? null,
696
+ status.integrity.describe,
697
+ `状态目录:${status.paths.stateDir}`,
698
+ ]
699
+ if (status.killSwitch) lines.push('⚠ 停机开关已启用:所有拦截被跳过')
700
+ if (status.configWarnings?.length) {
701
+ lines.push('配置警告:', ...status.configWarnings.map(warning => `- ${warning}`))
702
+ }
703
+ const recent = status.interceptor.recent ?? []
704
+ if (recent.length > 0) {
705
+ lines.push('最近决策:', ...recent.slice(-5).map(entry => `- ${entry.ts} ${entry.tool} → ${entry.decision}${entry.ruleIds?.length ? ` (${entry.ruleIds.join(',')})` : ''}`))
706
+ }
707
+ return lines.join('\n')
708
+ }
709
+
710
+ /**
711
+ * Strip values that are not valid JSON (functions, symbols) from a report before
712
+ * returning it through a tool result.
713
+ * @param {unknown} value
714
+ * @returns {unknown}
715
+ */
716
+ function sanitizeJson(value) {
717
+ try {
718
+ return JSON.parse(JSON.stringify(value ?? null))
719
+ } catch {
720
+ return null
721
+ }
722
+ }
723
+
724
+ /** @returns {string} absolute workspace path for tool-relative paths */
725
+ export function resolveToolPath(value, cwd = process.cwd()) {
726
+ return resolve(resolvePath(value, cwd))
727
+ }