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/index.js ADDED
@@ -0,0 +1,1134 @@
1
+ /**
2
+ * dsh-vigil Host plugin entry point.
3
+ *
4
+ * A bundle installs this package as one Loader row. `apply` builds a mutable
5
+ * runtime from the row's live `Config`:
6
+ *
7
+ * 1. `tools/pre-execute` — the interception waterfall (FR-2, FR-3, FR-4);
8
+ * 2. `ctx.tools.guard()` — the monotonic self-protection invariant (FR-5.5);
9
+ * 3. `vigil_*` tools — scan / status / quarantine / audit / integrity;
10
+ * 4. the Settings page policy — the bundle ships its own 守夜人 page, so the
11
+ * auto-generated plugin form is disabled.
12
+ *
13
+ * Config values are volatile references (`config.field.get()`); `snapshotConfig`
14
+ * turns them into a plain object and the runtime is rebuilt in place when a
15
+ * Settings save changes that snapshot. No bundle restart is needed for the
16
+ * switches and thresholds; a few subsystems (Sage module path, audit directory)
17
+ * still re-initialize on the next reload, which the page states.
18
+ *
19
+ * Everything is best-effort at activation: a malformed config or an unavailable
20
+ * optional engine produces warnings and a degraded-but-working plugin, never a
21
+ * failed bundle mount. Decisions themselves are fail-closed (see hook.js).
22
+ *
23
+ * @module dsh-vigil
24
+ */
25
+
26
+ import { existsSync } from 'node:fs'
27
+ import { dirname, join, resolve } from 'node:path'
28
+ import { fileURLToPath } from 'node:url'
29
+ import { acquireAuditLog, createAuditLog } from './audit-log.js'
30
+ import { createAuditFeedRoute } from './audit-feed.js'
31
+ import { createAuditClearRoute } from './audit-clear-route.js'
32
+ import { createSageActionRoute } from './sage-action-route.js'
33
+ import { createApprovalQueue, createApprovalRoute } from './approval.js'
34
+ import { createQuarantineRoute } from './quarantine-route.js'
35
+ import { createInstallScanRoute } from './install-scan-route.js'
36
+ import { createUpdateCheckRoute } from './update-check.js'
37
+ import { applyRulesUpdate, checkRulesUpdate, createRulesUpdateRoute } from './rules/update.js'
38
+ import { createArtworkRoute } from './artwork-route.js'
39
+ import { createAlertWindowRoute } from './alert-route.js'
40
+ import { createInstallWatcher } from './install-watch.js'
41
+ import { createInterceptor } from './sentinel/hook.js'
42
+ import { createSelfGuard } from './sentinel/guard.js'
43
+ import { createSageEngine } from './sentinel/sage.js'
44
+ import {
45
+ SAGE_DEFAULT_UPDATE_INTERVAL_MS,
46
+ checkSageUpdate,
47
+ locateSage,
48
+ provisionSage,
49
+ readProvisionReceipt,
50
+ writeProvisionReceipt,
51
+ } from './sage-provision.js'
52
+ import { createIntegrity } from './integrity.js'
53
+ import { createQuarantine } from './delete/quarantine.js'
54
+ import { createDeletePolicy } from './delete/policy.js'
55
+ import { resolveConfig, killSwitchState } from './config.js'
56
+ import { Config } from './config-schema.js'
57
+ import { configFingerprint, snapshotConfig } from './live-config.js'
58
+ import { registerTools } from './tools.js'
59
+ import { getRulePack, reloadRulePack } from './rules/pack.js'
60
+ import { isWithin, readJson, resolvePath, truncate } from './util.js'
61
+
62
+ /** Loader-visible plugin name. */
63
+ export const name = 'dsh-vigil'
64
+
65
+ /** Required Host services. `tools` is the only hard dependency. */
66
+ export const inject = ['tools']
67
+
68
+ /** Declared Config schema; every leaf is volatile so Settings can edit it live. */
69
+ export { Config }
70
+
71
+ const PLUGIN_DIR = dirname(dirname(fileURLToPath(import.meta.url)))
72
+
73
+ /** @returns {string} installed package version, or '0.0.0' when unreadable. */
74
+ function packageVersion() {
75
+ const manifest = readJson(join(PLUGIN_DIR, 'package.json'))
76
+ return typeof manifest?.version === 'string' ? manifest.version : '0.0.0'
77
+ }
78
+
79
+ /**
80
+ * Minimal logger: the plugin must not depend on a logging service that a
81
+ * profile without it would remove.
82
+ * @returns {{ warn: (message: string) => void, info: (message: string) => void }}
83
+ */
84
+ function createLogger() {
85
+ return {
86
+ warn(message) {
87
+ try {
88
+ console.warn(message)
89
+ } catch {
90
+ // console may be unavailable in exotic hosts
91
+ }
92
+ },
93
+ info(message) {
94
+ try {
95
+ console.info(message)
96
+ } catch {
97
+ // ignore
98
+ }
99
+ },
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Fallback integrity monitor so a failed baseline setup cannot disable the whole
105
+ * guard chain; it reports the failure through the status tool.
106
+ * @param {string} message
107
+ * @param {string} version
108
+ * @returns {any}
109
+ */
110
+ function degradedIntegrity(message, version) {
111
+ return {
112
+ enabled: false,
113
+ pluginDir: PLUGIN_DIR,
114
+ state: {
115
+ baseline: { state: 'error', changed: [], added: [], missing: [], version, checkedAt: null },
116
+ canary: { state: 'error', reason: '初始化失败' },
117
+ signature: { state: 'disabled', reason: null },
118
+ heartbeat: { state: 'unchecked', reason: null },
119
+ },
120
+ get alerts() {
121
+ return [`完整性监控初始化失败:${message}`]
122
+ },
123
+ check() {},
124
+ markHeartbeat: fn => fn,
125
+ verifyHeartbeat: () => {},
126
+ writeBaseline: () => ({ ok: false, version, files: 0, error: '初始化失败' }),
127
+ startTimer: () => () => {},
128
+ rebaseline: () => ({ ok: false, version, files: 0, error: '初始化失败' }),
129
+ describe: () => '完整性:初始化失败',
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Build one complete runtime generation from a plain config snapshot.
135
+ * Each subsystem degrades independently; the caller swaps the generation only
136
+ * after everything that can be built has been built.
137
+ * @param {unknown} plain plain config snapshot
138
+ * @param {{ logger: any, version: string, isDisabled: () => boolean, pluginDir: string, cwd: string }} deps
139
+ * @returns {Promise<any>}
140
+ */
141
+ async function buildRuntime(plain, deps) {
142
+ const { config, warnings } = resolveConfig(plain)
143
+ const { logger, version } = deps
144
+ // Relative delete targets and the `high` project root need the *workspace*,
145
+ // not the host process cwd (the Desktop app runs from the profile directory).
146
+ // An explicit `deleteGuard.projectRoot` wins; otherwise the host cwd is used
147
+ // only when it is a real workspace, never when it lives inside the Harness
148
+ // home. Unknown stays unknown so the policy asks instead of guessing.
149
+ const hostCwd = resolve(deps.hostCwd ?? process.cwd())
150
+ const configuredRoot = config.deleteGuard.projectRoot
151
+ ? resolvePath(config.deleteGuard.projectRoot, hostCwd)
152
+ : ''
153
+ const baseCwd = configuredRoot || (isWithin(config.paths.dshHome, hostCwd) ? '' : hostCwd)
154
+ // Rule data (credential paths, secret shapes, egress APIs, …) lives in YAML
155
+ // packs so it can be updated without shipping a plugin release. The shipped
156
+ // pack is read from the package; `rules.dir` overrides it on top.
157
+ let rulePack = null
158
+ try {
159
+ const externalDir = config.rules.dir
160
+ ? resolvePath(config.rules.dir, config.paths.stateDir)
161
+ : join(config.paths.stateDir, 'rules')
162
+ rulePack = reloadRulePack({ externalDir, lockPath: join(config.paths.stateDir, 'rules-lock.json'), logger })
163
+ for (const warning of rulePack.warnings) warnings.push(`规则包:${warning}`)
164
+ } catch (error) {
165
+ logger.warn(`[dsh-vigil] 规则包加载失败,继续使用内置规则:${String(error)}`)
166
+ }
167
+ // One sink per log directory per process: rebuilds and HMR replacements must
168
+ // not race two chain heads over the same JSONL file.
169
+ const audit = typeof deps.acquireAudit === 'function' ? deps.acquireAudit(config, logger) : createAuditLog(config, logger)
170
+
171
+ /** @type {any} */
172
+ let quarantine
173
+ try {
174
+ quarantine = createQuarantine(config, logger)
175
+ } catch (error) {
176
+ logger.warn(`[dsh-vigil] 隔离区初始化失败,已禁用可逆化删除:${String(error)}`)
177
+ quarantine = createQuarantine({ ...config, quarantine: { ...config.quarantine, enabled: false } }, logger)
178
+ }
179
+
180
+ const policy = createDeletePolicy(config, { quarantine, logger, cwd: baseCwd })
181
+
182
+ /** @type {any} */
183
+ let integrity
184
+ try {
185
+ integrity = createIntegrity(config, {
186
+ logger,
187
+ pluginDir: deps.pluginDir,
188
+ record: entry => audit.record({
189
+ kind: 'integrity',
190
+ event: entry.event,
191
+ tool: null,
192
+ decision: 'none',
193
+ ruleIds: entry.ruleIds ?? [],
194
+ reason: entry.reason,
195
+ }),
196
+ })
197
+ } catch (error) {
198
+ logger.warn(`[dsh-vigil] 完整性监控初始化失败:${String(error)}`)
199
+ integrity = degradedIntegrity(String(error), version)
200
+ }
201
+
202
+ /** @type {any} */
203
+ let sage
204
+ try {
205
+ sage = await createSageEngine(config, logger)
206
+ } catch (error) {
207
+ logger.warn(`[dsh-vigil] Sage 适配器初始化失败:${String(error)}`)
208
+ sage = {
209
+ status: { state: 'error', reason: String(error), rules: 0 },
210
+ evaluate: async () => (config.sage.required
211
+ ? { kind: 'deny', reason: 'Sage 不可用', ruleIds: ['VG-SAGE-ERR'], sage: { source: 'sage', error: true } }
212
+ : null),
213
+ ready: false,
214
+ describe: () => `Sage:初始化失败(${String(error)})`,
215
+ attribution: threatId => `规则 ${threatId} 来自 Sage`,
216
+ }
217
+ }
218
+
219
+ const interceptor = createInterceptor({
220
+ config,
221
+ audit,
222
+ policy,
223
+ sage,
224
+ integrity,
225
+ approval: deps.approval ?? null,
226
+ logger,
227
+ isDisabled: deps.isDisabled,
228
+ cwd: baseCwd,
229
+ pluginDir: deps.pluginDir,
230
+ })
231
+ const guard = createSelfGuard({
232
+ config,
233
+ pluginDir: deps.pluginDir,
234
+ isDisabled: deps.isDisabled,
235
+ logger,
236
+ })
237
+
238
+ return {
239
+ config,
240
+ warnings,
241
+ baseCwd,
242
+ rulePack,
243
+ audit,
244
+ quarantine,
245
+ policy,
246
+ integrity,
247
+ sage,
248
+ interceptor,
249
+ guard,
250
+ fingerprint: configFingerprint(plain),
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Activate the plugin for the current Loader row.
256
+ * @param {any} ctx plugin context whose service set includes `tools`
257
+ * @param {unknown} config the Loader row's live Config (volatile references)
258
+ * @returns {Promise<void>}
259
+ */
260
+ export async function apply(ctx, config) {
261
+ const logger = createLogger()
262
+ const version = packageVersion()
263
+ const hostCwd = process.cwd()
264
+ const entryId = readEntryId(ctx)
265
+ const packageManager = readPackageManager(ctx)
266
+
267
+ /** @type {any} */
268
+ let runtime
269
+ let refreshing = null
270
+ let rebuildQueued = false
271
+ /** Fingerprint whose Sage provisioning attempt already ran (avoids retry loops). */
272
+ let sageAttemptFingerprint = null
273
+ /** @type {Promise<any>|null} */
274
+ let sageProvisioning = null
275
+ /** @type {Promise<any>|null} */
276
+ let sageUpdateCheck = null
277
+ /** @type {{ state: string, latestVersion: string|null, checkedAt: string|null, error: string|null, updateAvailable: boolean|null, updatedTo: string|null }} */
278
+ let sageUpdateState = { state: 'idle', latestVersion: null, checkedAt: null, error: null, updateAvailable: null, updatedTo: null }
279
+ /** @type {Array<() => void>} */
280
+ const disposers = []
281
+ /** Remote rule-pack update state, shared by the route, tool and settings page. */
282
+ let rulesUpdateState = {
283
+ state: 'idle',
284
+ currentVersion: null,
285
+ latestVersion: null,
286
+ checkedAt: null,
287
+ updatedAt: null,
288
+ error: null,
289
+ available: null,
290
+ }
291
+ /** @type {Promise<any>|null} */
292
+ let rulesUpdateRun = null
293
+ /** @type {'check'|'update'|null} */
294
+ let rulesUpdateRunMode = null
295
+ const rulesDirFor = cfg => (cfg.rules.dir ? resolvePath(cfg.rules.dir, cfg.paths.stateDir) : join(cfg.paths.stateDir, 'rules'))
296
+ const rulesLockFor = cfg => join(cfg.paths.stateDir, 'rules-lock.json')
297
+ const rulesVersionFor = cfg => join(cfg.paths.stateDir, 'rules-version.json')
298
+
299
+ /**
300
+ * Check (and optionally install) remote rule packs. Serialized: a double click
301
+ * on the settings button and the auto timer share one run.
302
+ * @param {{ update?: boolean }} [options]
303
+ */
304
+ async function runRulesUpdate(options = {}) {
305
+ const update = options.update === true
306
+ const mode = update ? 'update' : 'check'
307
+ // Coalesce only identical requests. An in-flight background *check* must
308
+ // not be handed back for an explicit *update*: that used to report success
309
+ // with an unknown version (`更新到 ?`) while installing nothing.
310
+ if (rulesUpdateRun && rulesUpdateRunMode === mode) return rulesUpdateRun
311
+ if (rulesUpdateRun) await rulesUpdateRun.catch(() => {})
312
+ const current = runtime?.config ?? config
313
+ const source = typeof current.rules?.source === 'string' ? current.rules.source.trim() : ''
314
+ if (source === '') return { ok: false, error: '未配置规则库更新源(rules.source)', state: rulesUpdateState }
315
+ rulesUpdateRunMode = mode
316
+ rulesUpdateRun = (async () => {
317
+ rulesUpdateState = { ...rulesUpdateState, state: update ? 'updating' : 'checking', error: null }
318
+ try {
319
+ const check = await checkRulesUpdate({ source, versionFile: rulesVersionFor(current) })
320
+ if (!check.ok) {
321
+ rulesUpdateState = { ...rulesUpdateState, state: 'error', error: check.error ?? '规则库检查失败', checkedAt: new Date().toISOString() }
322
+ runtime?.audit?.record({ kind: 'event', event: 'rules-update', tool: 'vigil_rules', decision: 'none', ruleIds: ['VG-RULES-01'], reason: `规则库检查失败:${check.error ?? '未知原因'}` })
323
+ return { ok: false, error: check.error, state: rulesUpdateState }
324
+ }
325
+ if (!update || !check.available) {
326
+ rulesUpdateState = {
327
+ ...rulesUpdateState,
328
+ state: 'idle',
329
+ currentVersion: check.currentVersion,
330
+ latestVersion: check.latestVersion,
331
+ available: check.available,
332
+ checkedAt: new Date().toISOString(),
333
+ }
334
+ runtime?.audit?.record({
335
+ kind: 'event', event: 'rules-update', tool: 'vigil_rules', decision: 'none', ruleIds: ['VG-RULES-01'],
336
+ reason: `规则库检查:当前 ${check.currentVersion ?? '未知'},最新 ${check.latestVersion}${check.available ? '(有更新)' : '(已是最新)'}`,
337
+ })
338
+ return { ok: true, ...check, state: rulesUpdateState }
339
+ }
340
+ const applied = await applyRulesUpdate({
341
+ source,
342
+ targetDir: rulesDirFor(current),
343
+ versionFile: rulesVersionFor(current),
344
+ lockPath: rulesLockFor(current),
345
+ logger,
346
+ })
347
+ if (!applied.ok) {
348
+ rulesUpdateState = { ...rulesUpdateState, state: 'error', error: applied.error ?? '规则库更新失败', checkedAt: new Date().toISOString() }
349
+ runtime?.audit?.record({ kind: 'event', event: 'rules-update', tool: 'vigil_rules', decision: 'none', ruleIds: ['VG-RULES-01'], reason: `规则库更新失败:${applied.error ?? '未知原因'}` })
350
+ return { ok: false, error: applied.error, state: rulesUpdateState }
351
+ }
352
+ if (runtime) runtime.rulePack = getRulePack()
353
+ rulesUpdateState = {
354
+ state: 'idle',
355
+ currentVersion: applied.version,
356
+ latestVersion: applied.version,
357
+ available: false,
358
+ checkedAt: new Date().toISOString(),
359
+ updatedAt: new Date().toISOString(),
360
+ error: null,
361
+ }
362
+ runtime?.audit?.record({
363
+ kind: 'event', event: 'rules-update', tool: 'vigil_rules', decision: 'none', ruleIds: ['VG-RULES-01'],
364
+ reason: `规则库已更新到 ${applied.version}(${(applied.files ?? []).length} 个文件)`,
365
+ })
366
+ return { ok: true, ...applied, state: rulesUpdateState }
367
+ } catch (error) {
368
+ rulesUpdateState = { ...rulesUpdateState, state: 'error', error: error instanceof Error ? error.message : String(error) }
369
+ return { ok: false, error: rulesUpdateState.error, state: rulesUpdateState }
370
+ } finally {
371
+ rulesUpdateRun = null
372
+ rulesUpdateRunMode = null
373
+ }
374
+ })()
375
+ return rulesUpdateRun
376
+ }
377
+ /** Auto-update timer: only checks when enabled and a source is configured. */
378
+ const scheduleRulesAutoUpdate = () => {
379
+ const runIfEnabled = () => {
380
+ const cfg = runtime?.config
381
+ if (cfg?.rules?.autoUpdate !== true || !cfg.rules.source) return
382
+ void runRulesUpdate({ update: true }).catch(() => {})
383
+ }
384
+ // The first tick must respect autoUpdate too; previously it always ran and
385
+ // could download a rule pack for users who had explicitly disabled it.
386
+ const first = setTimeout(runIfEnabled, 15000)
387
+ if (typeof first.unref === 'function') first.unref()
388
+ disposers.push(() => clearTimeout(first))
389
+ const timer = setInterval(runIfEnabled, 5 * 60 * 1000)
390
+ if (typeof timer.unref === 'function') timer.unref()
391
+ disposers.push(() => clearInterval(timer))
392
+ }
393
+ /** Authenticated browser routes and whether each one registered. */
394
+ const ROUTE_LABELS = [
395
+ '审计数据路由',
396
+ '审计清理路由',
397
+ 'Sage 维护路由',
398
+ '对话内审批路由',
399
+ '隔离区路由',
400
+ '手动插件扫描路由',
401
+ '插件更新检查路由',
402
+ '规则库更新路由',
403
+ '插图资源路由',
404
+ '审批提醒路由',
405
+ ]
406
+ /** @type {Map<string, string>} */
407
+ const routeStatus = new Map(ROUTE_LABELS.map(label => [label, 'pending']))
408
+
409
+ const snapshot = () => snapshotConfig(config)
410
+ const isDisabled = () => Boolean(runtime) && killSwitchState(runtime.config, { existsSync }).active
411
+ const acquireAudit = (nextConfig, logger) => acquireAuditLog(nextConfig, logger)
412
+ // One queue for the plugin lifetime: pending 允许/拒绝 answers must survive a
413
+ // volatile-config rebuild, and its timeout follows the live config.
414
+ const approvalQueue = createApprovalQueue({
415
+ logger,
416
+ getTimeoutMs: () => Number(runtime?.config?.notify?.approvalTimeoutMs) || 120000,
417
+ // The queue survives runtime rebuilds, so resolve the current sink lazily.
418
+ audit: {
419
+ record: entry => {
420
+ try {
421
+ runtime?.audit?.record?.(entry)
422
+ } catch {
423
+ // audit failures never change an approval outcome
424
+ }
425
+ },
426
+ },
427
+ })
428
+ disposers.push(() => approvalQueue.dispose())
429
+ // Install-time static audit for every install surface: the watcher diffs the
430
+ // profiles' dependency sets and scans newly added bundles after the fact.
431
+ const installWatcher = createInstallWatcher({
432
+ logger,
433
+ // The raw Config leaves are volatile getters; hand the watcher a snapshot
434
+ // so its background scans see the user's current AST setting as plain data.
435
+ getAst: () => snapshotConfig(config).scan?.ast,
436
+ record: entry => {
437
+ try {
438
+ runtime?.audit?.record(entry)
439
+ } catch {
440
+ // auditing is best-effort
441
+ }
442
+ },
443
+ })
444
+ disposers.push(() => installWatcher.stop())
445
+
446
+ /**
447
+ * Rebuild the runtime from the live config snapshot.
448
+ * @param {string} reason
449
+ * @returns {Promise<void>}
450
+ */
451
+ async function rebuild(reason) {
452
+ if (refreshing) {
453
+ rebuildQueued = true
454
+ await refreshing
455
+ return
456
+ }
457
+ refreshing = (async () => {
458
+ try {
459
+ const next = await buildRuntime(snapshot(), { logger, version, isDisabled, acquireAudit, approval: approvalQueue, pluginDir: PLUGIN_DIR, hostCwd })
460
+ const previous = runtime
461
+ runtime = next
462
+ // The registered wrappers outlive a generation: re-tag them so the new
463
+ // heartbeat monitor sees its own guards, then record the transition.
464
+ try {
465
+ runtime.integrity.markHeartbeat(hookWrapper)
466
+ runtime.integrity.markHeartbeat(guardWrapper)
467
+ runtime.integrity.verifyHeartbeat()
468
+ } catch {
469
+ // integrity is advisory; a failure here must not undo the swap
470
+ }
471
+ runtime.audit.record({
472
+ kind: 'event',
473
+ event: 'config-reload',
474
+ tool: null,
475
+ decision: 'none',
476
+ ruleIds: [],
477
+ reason: `配置已重新加载(${reason}):mode=${runtime.config.mode}`,
478
+ extra: { warnings: runtime.warnings },
479
+ })
480
+ scheduleSageProvision()
481
+ scheduleSageUpdate()
482
+ if (previous?.quarantine && previous.quarantine !== runtime.quarantine) {
483
+ // The old facade only closes over config; nothing to release.
484
+ }
485
+ } catch (error) {
486
+ logger.warn(`[dsh-vigil] 重新加载配置失败,继续使用上一代运行时:${String(error)}`)
487
+ try {
488
+ runtime?.audit?.record({
489
+ kind: 'event',
490
+ event: 'config-reload-failed',
491
+ tool: null,
492
+ decision: 'none',
493
+ ruleIds: ['VG-INT-10'],
494
+ reason: `重新加载配置失败:${String(error)}`,
495
+ })
496
+ } catch {
497
+ // ignore
498
+ }
499
+ } finally {
500
+ refreshing = null
501
+ if (rebuildQueued) {
502
+ rebuildQueued = false
503
+ void rebuild('queued')
504
+ }
505
+ }
506
+ })()
507
+ await refreshing
508
+ }
509
+
510
+ /**
511
+ * Download Sage when the feature was just enabled (or the attempt failed and
512
+ * the operator changed the configuration again). Never blocks a tool call: the
513
+ * running generation keeps using the built-in rules until the swap.
514
+ * @returns {void}
515
+ */
516
+ function scheduleSageProvision() {
517
+ try {
518
+ const current = runtime
519
+ if (!current?.config?.sage?.enabled) return
520
+ if (!current.sage?.status?.needsProvision) return
521
+ if (sageProvisioning) return
522
+ if (sageAttemptFingerprint === current.fingerprint) return
523
+ void runSageProvision({ force: false }).catch(() => {})
524
+ } catch {
525
+ // provisioning is best-effort; a throw here must not break the hook path
526
+ }
527
+ }
528
+
529
+ /**
530
+ * Run one provisioning (install or update) attempt and record its outcome.
531
+ * @param {{ force?: boolean, targetVersion?: string, reason?: 'install'|'update' }} [options]
532
+ * @returns {Promise<any>}
533
+ */
534
+ async function runSageProvision(options = {}) {
535
+ const current = runtime
536
+ if (!current?.config?.sage?.enabled) return { ok: false, skipped: 'disabled' }
537
+ const fingerprint = current.fingerprint
538
+ if (!options.force && sageAttemptFingerprint === fingerprint) return { ok: false, skipped: 'already-attempted' }
539
+ if (sageProvisioning) return sageProvisioning
540
+ sageAttemptFingerprint = fingerprint
541
+ const updating = options.reason === 'update'
542
+ try {
543
+ current.sage.status.provisioningState = updating ? 'updating' : 'downloading'
544
+ current.sage.status.reason = updating
545
+ ? `正在更新 Sage${options.targetVersion ? ` 到 ${options.targetVersion}` : '(检查最新版本)'}…`
546
+ : '正在从 npm 下载 Sage(引擎与规则)…'
547
+ } catch {
548
+ // status is advisory
549
+ }
550
+ sageProvisioning = (async () => {
551
+ let result
552
+ try {
553
+ result = await provisionSage({
554
+ config: current.config,
555
+ packageManager,
556
+ logger,
557
+ targetVersion: options.targetVersion,
558
+ reason: options.reason,
559
+ })
560
+ } catch (error) {
561
+ result = { ok: false, dir: '', location: null, attempts: [], output: '', error: error instanceof Error ? error.message : String(error) }
562
+ }
563
+ const installed = result?.location?.version ?? null
564
+ try {
565
+ current.audit?.record({
566
+ kind: 'event',
567
+ event: updating ? 'sage-update' : 'sage-provision',
568
+ tool: options.force ? 'vigil_sage' : null,
569
+ decision: result.ok ? 'allow' : result.rolledBack ? 'ask' : 'deny',
570
+ ruleIds: result.ok || result.rolledBack ? [] : ['VG-SAGE-PROVISION'],
571
+ reason: result.ok
572
+ ? `${updating ? 'Sage 已更新' : 'Sage 已下载并启用'}:${installed ?? '?'},${result.location?.rules ?? 0} 条规则`
573
+ : result.rolledBack
574
+ ? `Sage ${result.targetVersion ?? '新版本'} 安装/验证失败,已回滚到 ${installed ?? '上一版本'}:${result.error ?? ''}`
575
+ : `Sage 自动下载失败:${result.error ?? '未知原因'}`,
576
+ extra: {
577
+ dir: result.dir,
578
+ targetVersion: result.targetVersion ?? options.targetVersion ?? null,
579
+ installedVersion: installed,
580
+ rolledBack: result.rolledBack === true,
581
+ attempts: Array.isArray(result.attempts) ? result.attempts.map(item => ({ kind: item.kind, ok: item.ok, error: item.error })) : [],
582
+ },
583
+ })
584
+ } catch {
585
+ // audit failures never block provisioning
586
+ }
587
+ if (result.ok) {
588
+ sageAttemptFingerprint = null
589
+ sageUpdateState = {
590
+ state: 'idle',
591
+ latestVersion: installed,
592
+ checkedAt: new Date().toISOString(),
593
+ error: null,
594
+ updateAvailable: false,
595
+ updatedTo: updating ? installed : sageUpdateState.updatedTo,
596
+ }
597
+ try {
598
+ await rebuild(updating ? 'sage-updated' : 'sage-ready')
599
+ } catch {
600
+ // rebuild reports its own failure
601
+ }
602
+ } else if (result.rolledBack && result.location?.available) {
603
+ // The previous pair is usable again: rebuild so the sentinel regains Sage.
604
+ try {
605
+ await rebuild('sage-rollback')
606
+ } catch {
607
+ // ignore
608
+ }
609
+ try {
610
+ current.sage.status.provisioningState = 'rolled-back'
611
+ current.sage.status.reason = `更新失败,已回滚到 ${installed ?? '上一版本'}:${result.error ?? ''}`
612
+ } catch {
613
+ // ignore
614
+ }
615
+ } else {
616
+ try {
617
+ current.sage.status.provisioningState = 'failed'
618
+ current.sage.status.provisionError = result.error ?? '未知原因'
619
+ current.sage.status.provisionAttempts = result.attempts
620
+ current.sage.status.reason = `自动下载失败:${result.error ?? '未知原因'}`
621
+ } catch {
622
+ // ignore
623
+ }
624
+ sageUpdateState = {
625
+ ...sageUpdateState,
626
+ state: 'error',
627
+ checkedAt: new Date().toISOString(),
628
+ error: result.error ?? '未知原因',
629
+ }
630
+ }
631
+ return result
632
+ })().finally(() => {
633
+ sageProvisioning = null
634
+ })
635
+ return sageProvisioning
636
+ }
637
+
638
+ /**
639
+ * Check the registry for a newer Sage pair and upgrade when allowed.
640
+ * Never blocks a tool call: the running generation keeps the current engine
641
+ * until the verified download swaps in.
642
+ * @param {{ force?: boolean }} [options]
643
+ * @returns {Promise<any>}
644
+ */
645
+ async function maybeCheckSageUpdate(options = {}) {
646
+ const current = runtime
647
+ if (!current?.config?.sage?.enabled) return { ok: false, skipped: 'disabled' }
648
+ if (current.config.sage.autoUpdate === false && !options.force) return { ok: false, skipped: 'auto-update-off' }
649
+ const dir = current.sage.status.installDir
650
+ // Read the installed metadata fresh: the running generation's status may be
651
+ // stale after a manual repair or a half-finished upgrade.
652
+ const freshLocation = dir ? locateSage(dir) : null
653
+ const installedVersion = freshLocation?.version ?? current.sage?.status?.version ?? null
654
+ if (!installedVersion) return { ok: false, skipped: 'not-installed' }
655
+ if (sageUpdateCheck) return sageUpdateCheck
656
+ const receipt = dir ? readProvisionReceipt(dir) : undefined
657
+ const intervalMs = Number(current.config.sage.updateIntervalMs) || SAGE_DEFAULT_UPDATE_INTERVAL_MS
658
+ sageUpdateCheck = (async () => {
659
+ sageUpdateState = { ...sageUpdateState, state: 'checking', error: null }
660
+ const check = await checkSageUpdate({
661
+ installedVersion,
662
+ receipt,
663
+ intervalMs,
664
+ force: options.force === true,
665
+ logger,
666
+ })
667
+ if (!check.checked) {
668
+ sageUpdateState = { ...sageUpdateState, state: 'idle' }
669
+ return { ok: true, checked: false, skipped: check.reason ?? 'interval', installedVersion }
670
+ }
671
+ const checkedAt = new Date().toISOString()
672
+ if (!check.ok) {
673
+ sageUpdateState = { state: 'error', latestVersion: null, checkedAt, error: check.error, updateAvailable: null, updatedTo: null }
674
+ try {
675
+ current.audit?.record({
676
+ kind: 'event',
677
+ event: 'sage-update-check',
678
+ tool: options.force ? 'vigil_sage' : null,
679
+ decision: 'none',
680
+ ruleIds: ['VG-SAGE-UPDATE'],
681
+ reason: `Sage 版本检查失败:${check.error ?? '未知原因'}`,
682
+ })
683
+ } catch {
684
+ // ignore
685
+ }
686
+ return { ok: false, checked: true, error: check.error, installedVersion }
687
+ }
688
+ if (dir && receipt) writeProvisionReceipt(dir, { ...receipt, lastCheckedAt: checkedAt })
689
+ sageUpdateState = {
690
+ state: check.updateAvailable ? 'update-available' : 'up-to-date',
691
+ latestVersion: check.latestVersion,
692
+ checkedAt,
693
+ error: null,
694
+ updateAvailable: check.updateAvailable,
695
+ updatedTo: sageUpdateState.updatedTo,
696
+ }
697
+ if (!check.updateAvailable) return { ok: true, checked: true, updated: false, installedVersion, latestVersion: check.latestVersion }
698
+ const update = await runSageProvision({ force: true, targetVersion: check.latestVersion ?? undefined, reason: 'update' })
699
+ if (update?.ok) {
700
+ sageUpdateState = { state: 'up-to-date', latestVersion: update.location?.version ?? check.latestVersion, checkedAt, error: null, updateAvailable: false, updatedTo: update.location?.version ?? null }
701
+ } else {
702
+ sageUpdateState = {
703
+ state: update?.rolledBack ? 'rolled-back' : 'error',
704
+ latestVersion: check.latestVersion,
705
+ checkedAt,
706
+ error: update?.error ?? '更新失败',
707
+ updateAvailable: !update?.rolledBack,
708
+ updatedTo: null,
709
+ }
710
+ }
711
+ return { ok: Boolean(update?.ok), checked: true, updated: Boolean(update?.ok), installedVersion, latestVersion: check.latestVersion, update }
712
+ })().finally(() => {
713
+ sageUpdateCheck = null
714
+ })
715
+ return sageUpdateCheck
716
+ }
717
+
718
+ /**
719
+ * Kick off a due update check in the background.
720
+ * @returns {void}
721
+ */
722
+ function scheduleSageUpdate() {
723
+ try {
724
+ const current = runtime
725
+ if (!current?.config?.sage?.enabled) return
726
+ if (current.config.sage.autoUpdate === false) return
727
+ if (!current.sage?.status?.version) return
728
+ if (sageUpdateCheck || sageProvisioning) return
729
+ const intervalMs = Number(current.config.sage.updateIntervalMs) || SAGE_DEFAULT_UPDATE_INTERVAL_MS
730
+ const dir = current.sage.status.installDir
731
+ const receipt = dir ? readProvisionReceipt(dir) : undefined
732
+ if (receipt?.lastCheckedAt && Date.now() - Date.parse(receipt.lastCheckedAt) < intervalMs) return
733
+ void maybeCheckSageUpdate({ force: false }).catch(() => {})
734
+ } catch {
735
+ // update checks are best-effort
736
+ }
737
+ }
738
+
739
+ /** Rebuild when the live snapshot no longer matches the running generation. */
740
+ function ensureFresh() {
741
+ try {
742
+ const plain = snapshot()
743
+ if (runtime && configFingerprint(plain) !== runtime.fingerprint) void rebuild('settings-change')
744
+ } catch {
745
+ // A snapshot failure falls back to the running generation.
746
+ }
747
+ }
748
+
749
+ // Initial generation. It must exist before the wrappers below can run.
750
+ runtime = await buildRuntime(snapshot(), { logger, version, isDisabled, acquireAudit, approval: approvalQueue, pluginDir: PLUGIN_DIR, hostCwd })
751
+
752
+ const hookWrapper = async (exec, next) => {
753
+ ensureFresh()
754
+ const endEvaluation = typeof approvalQueue.beginEvaluation === 'function'
755
+ ? approvalQueue.beginEvaluation()
756
+ : null
757
+ try {
758
+ return await runtime.interceptor.handlePreExecute(exec, next)
759
+ } finally {
760
+ if (endEvaluation) endEvaluation()
761
+ }
762
+ }
763
+ const guardWrapper = exec => {
764
+ ensureFresh()
765
+ return runtime.guard(exec)
766
+ }
767
+ try {
768
+ runtime.integrity.markHeartbeat(hookWrapper)
769
+ runtime.integrity.markHeartbeat(guardWrapper)
770
+ runtime.integrity.verifyHeartbeat()
771
+ } catch (error) {
772
+ // A monitor problem must never prevent the guard chain from mounting.
773
+ logger.warn(`[dsh-vigil] 完整性心跳注册失败:${String(error)}`)
774
+ }
775
+
776
+ // ---- 1. runtime interception (waterfall) ------------------------------
777
+ try {
778
+ disposers.push(ctx.on('tools/pre-execute', hookWrapper))
779
+ } catch (error) {
780
+ logger.warn(`[dsh-vigil] 无法注册 tools/pre-execute:${String(error)}`)
781
+ }
782
+
783
+ // ---- 2. monotonic self-protection guard -------------------------------
784
+ try {
785
+ disposers.push(ctx.tools.guard(guardWrapper))
786
+ } catch (error) {
787
+ logger.warn(`[dsh-vigil] 无法注册自保护 guard:${String(error)}`)
788
+ }
789
+
790
+ // ---- 2b. conversation lifecycle keeps the audit chain in sync ----------
791
+ // archiving a conversation moves its records to <log>/archive/, unarchiving
792
+ // restores them, and deleting a conversation drops them.
793
+ try {
794
+ const auditOf = () => runtime?.audit
795
+ disposers.push(ctx.on('workspace/session-archived', request => {
796
+ try {
797
+ auditOf()?.archiveSession?.(request?.sessionId)
798
+ } catch (error) {
799
+ logger.warn(`[dsh-vigil] 归档会话审计日志失败:${String(error)}`)
800
+ }
801
+ }))
802
+ disposers.push(ctx.on('workspace/session-unarchiving', request => {
803
+ try {
804
+ auditOf()?.restoreSession?.(request?.sessionId)
805
+ } catch (error) {
806
+ logger.warn(`[dsh-vigil] 恢复会话审计日志失败:${String(error)}`)
807
+ }
808
+ }))
809
+ disposers.push(ctx.on('api-session/removed', sessionId => {
810
+ try {
811
+ auditOf()?.removeSession?.(typeof sessionId === 'string' ? sessionId : sessionId?.id)
812
+ } catch (error) {
813
+ logger.warn(`[dsh-vigil] 删除会话审计日志失败:${String(error)}`)
814
+ }
815
+ }))
816
+ } catch (error) {
817
+ logger.warn(`[dsh-vigil] 无法注册会话生命周期同步:${String(error)}`)
818
+ }
819
+
820
+ // ---- 3. agent-facing tools -------------------------------------------
821
+ if (runtime.config.tools.enabled !== false && typeof ctx.tools.register === 'function') {
822
+ try {
823
+ disposers.push(...registerTools(ctx, {
824
+ getRuntime: () => runtime,
825
+ getConfigWarnings: () => runtime.warnings,
826
+ version,
827
+ isDisabled,
828
+ ensureFresh,
829
+ sageInstall: () => runSageProvision({ force: true }),
830
+ getSageUpdate: () => sageUpdateState,
831
+ sageUpdate: () => maybeCheckSageUpdate({ force: true }),
832
+ getInstallScan: () => ({
833
+ description: installWatcher.describe(),
834
+ lastCheckAt: installWatcher.lastCheckAt,
835
+ lastError: installWatcher.lastError,
836
+ recent: installWatcher.list().slice(-3),
837
+ }),
838
+ getApproval: () => approvalQueue,
839
+ getCwd: () => runtime.baseCwd,
840
+ getRoutes: () => Object.fromEntries(routeStatus),
841
+ runRulesUpdate,
842
+ getRulesUpdateState: () => rulesUpdateState,
843
+ }))
844
+ } catch (error) {
845
+ logger.warn(`[dsh-vigil] 无法注册 vigil_* 工具:${String(error)}`)
846
+ }
847
+ }
848
+
849
+ // ---- 3b. authenticated browser routes: audit feed + approval answers ----
850
+ // On a cold boot the `connection` service can be provided after this
851
+ // plugin's apply, so register through ctx.inject instead of reading it once.
852
+ try {
853
+ const registerBrowserRoutes = connection => {
854
+ if (!connection || !connection.fetch || typeof connection.fetch.register !== 'function') {
855
+ for (const label of ROUTE_LABELS) routeStatus.set(label, 'no-connection')
856
+ logger.warn('[dsh-vigil] 当前宿主没有 connection.fetch,对话内审计与审批界面将不可用')
857
+ return undefined
858
+ }
859
+ /**
860
+ * Register one route with a retry window: a restarted entry can briefly
861
+ * overlap the previous generation's exact path.
862
+ * @param {any} route
863
+ * @param {string} label
864
+ */
865
+ const registerRoute = (route, label) => {
866
+ let disposed = false
867
+ let stop = null
868
+ let attempts = 0
869
+ const attempt = () => {
870
+ if (disposed || stop) return
871
+ try {
872
+ stop = connection.fetch.register(route)
873
+ routeStatus.set(label, 'ok')
874
+ } catch (error) {
875
+ attempts += 1
876
+ if (attempts >= 12) {
877
+ routeStatus.set(label, `failed: ${error instanceof Error ? error.message : String(error)}`)
878
+ logger.warn(`[dsh-vigil] ${label}注册失败:${String(error)}`)
879
+ return
880
+ }
881
+ setTimeout(attempt, 250)
882
+ }
883
+ }
884
+ attempt()
885
+ return () => {
886
+ disposed = true
887
+ try {
888
+ const result = stop?.()
889
+ if (result && typeof result.catch === 'function') result.catch(() => {})
890
+ } catch {
891
+ // route already gone
892
+ }
893
+ }
894
+ }
895
+ return [
896
+ registerRoute(createAuditFeedRoute({
897
+ getRuntime: () => runtime,
898
+ isDisabled,
899
+ limit: 300,
900
+ approval: approvalQueue,
901
+ installWatcher,
902
+ }), '审计数据路由'),
903
+ registerRoute(createAuditClearRoute({ getRuntime: () => runtime }), '审计清理路由'),
904
+ registerRoute(createSageActionRoute({
905
+ getRuntime: () => runtime,
906
+ rebuild: reason => rebuild(reason),
907
+ }), 'Sage 维护路由'),
908
+ registerRoute(createApprovalRoute({
909
+ getQueue: () => approvalQueue,
910
+ getWatcher: () => installWatcher,
911
+ }), '对话内审批路由'),
912
+ registerRoute(createQuarantineRoute({ getQuarantine: () => runtime?.quarantine }), '隔离区路由'),
913
+ registerRoute(createInstallScanRoute({ getWatcher: () => installWatcher }), '手动插件扫描路由'),
914
+ registerRoute(createRulesUpdateRoute({
915
+ getState: () => rulesUpdateState,
916
+ run: runRulesUpdate,
917
+ logger,
918
+ }), '规则库更新路由'),
919
+ registerRoute(createUpdateCheckRoute({
920
+ pluginDir: PLUGIN_DIR,
921
+ currentVersion: version,
922
+ getPluginManager: () => (typeof ctx.get === 'function' ? ctx.get('pluginManager') : undefined),
923
+ logger,
924
+ }), '插件更新检查路由'),
925
+ registerRoute(createArtworkRoute({ pluginDir: PLUGIN_DIR }), '插图资源路由'),
926
+ registerRoute(createAlertWindowRoute(), '审批提醒路由'),
927
+ ]
928
+ }
929
+ if (typeof ctx.inject === 'function') {
930
+ ctx.inject(['connection'], child => {
931
+ try {
932
+ const stops = registerBrowserRoutes(typeof child.get === 'function' ? child.get('connection') : undefined)
933
+ if (stops) child.effect(() => () => { for (const stop of stops) stop() })
934
+ } catch (error) {
935
+ logger.warn(`[dsh-vigil] 无法注册浏览器数据路由:${String(error)}`)
936
+ }
937
+ })
938
+ } else {
939
+ const stops = registerBrowserRoutes(typeof ctx.get === 'function' ? ctx.get('connection') : undefined)
940
+ if (stops) disposers.push(...stops)
941
+ }
942
+ } catch (error) {
943
+ logger.warn(`[dsh-vigil] 无法注册浏览器数据路由:${String(error)}`)
944
+ }
945
+ // Install scanning is independent of the browser channel: a CLI-only host
946
+ // still gets the audit records (and the notice once a page attaches).
947
+ try {
948
+ installWatcher.start()
949
+ } catch (error) {
950
+ logger.warn(`[dsh-vigil] 安装审计监听启动失败:${String(error)}`)
951
+ }
952
+ // Plugin-manager operations complete long before the 20s polling interval;
953
+ // scan the changed profile immediately so the audit dialog is not delayed.
954
+ try {
955
+ disposers.push(ctx.on('plugin-manager/changed', () => {
956
+ void installWatcher.check().catch(error => {
957
+ logger.warn(`[dsh-vigil] 插件变更后即时审计失败:${String(error)}`)
958
+ })
959
+ }))
960
+ } catch (error) {
961
+ logger.warn(`[dsh-vigil] 无法订阅插件变更事件:${String(error)}`)
962
+ }
963
+ // Remote rule-pack updates are optional; the timer re-reads the live config,
964
+ // so enabling them on the settings page takes effect without a reload.
965
+ try {
966
+ scheduleRulesAutoUpdate()
967
+ } catch (error) {
968
+ logger.warn(`[dsh-vigil] 规则库自动更新启动失败:${String(error)}`)
969
+ }
970
+
971
+ // ---- 4. settings integration -----------------------------------------
972
+ // Ship our own page: suppress the schema-derived auto page for this entry.
973
+ try {
974
+ if (typeof ctx.inject === 'function') {
975
+ ctx.inject(['settings'], child => {
976
+ try {
977
+ child.effect(() => child.settings.configure({ auto: false }, ctx.fiber))
978
+ } catch (error) {
979
+ logger.warn(`[dsh-vigil] 无法设置设置页策略:${String(error)}`)
980
+ }
981
+ })
982
+ }
983
+ } catch (error) {
984
+ logger.warn(`[dsh-vigil] settings 服务注入失败:${String(error)}`)
985
+ }
986
+ try {
987
+ disposers.push(ctx.on('settings/document-updated', ns => {
988
+ if (entryId && ns !== entryId && !String(ns).endsWith('dsh-vigil')) return
989
+ ensureFresh()
990
+ }))
991
+ } catch {
992
+ // The event is not available in every composition; the per-call check covers it.
993
+ }
994
+
995
+ // ---- 5. periodic integrity checks ------------------------------------
996
+ try {
997
+ const timer = setInterval(() => {
998
+ try {
999
+ runtime.integrity.check({ force: true })
1000
+ } catch {
1001
+ // monitoring failure must never crash the host
1002
+ }
1003
+ }, Math.max(60000, Number(runtime.config.integrity.intervalMs) || 1800000))
1004
+ if (typeof timer.unref === 'function') timer.unref()
1005
+ disposers.push(() => clearInterval(timer))
1006
+ } catch (error) {
1007
+ logger.warn(`[dsh-vigil] 无法启动完整性定时检查:${String(error)}`)
1008
+ }
1009
+
1010
+ // Auto-upgrade timer: checks the registry on the configured interval and swaps
1011
+ // in a verified newer pair. The receipt remembers the last check, so restarts
1012
+ // do not hammer the registry.
1013
+ try {
1014
+ const updateTimer = setInterval(() => {
1015
+ try {
1016
+ scheduleSageUpdate()
1017
+ } catch {
1018
+ // best effort
1019
+ }
1020
+ }, Math.max(3600000, Number(runtime.config.sage.updateIntervalMs) || SAGE_DEFAULT_UPDATE_INTERVAL_MS))
1021
+ if (typeof updateTimer.unref === 'function') updateTimer.unref()
1022
+ disposers.push(() => clearInterval(updateTimer))
1023
+ } catch (error) {
1024
+ logger.warn(`[dsh-vigil] 无法启动 Sage 自动更新检查:${String(error)}`)
1025
+ }
1026
+
1027
+ // Quarantine housekeeping: expired entries are deleted on activation and every
1028
+ // six hours, so a blocked deletion does not accumulate forever when nobody
1029
+ // opens the audit dialog.
1030
+ const expireQuarantine = () => {
1031
+ try {
1032
+ const result = runtime.quarantine.expire()
1033
+ if (Array.isArray(result?.expired) && result.expired.length > 0) {
1034
+ runtime.audit.record({
1035
+ kind: 'quarantine',
1036
+ event: 'expire',
1037
+ tool: null,
1038
+ decision: 'none',
1039
+ ruleIds: [],
1040
+ reason: `自动清理过期隔离条目 ${result.expired.length} 个`,
1041
+ })
1042
+ }
1043
+ } catch {
1044
+ // housekeeping must never break activation or the hook path
1045
+ }
1046
+ }
1047
+ expireQuarantine()
1048
+ try {
1049
+ const expireTimer = setInterval(expireQuarantine, 6 * 3600 * 1000)
1050
+ if (typeof expireTimer.unref === 'function') expireTimer.unref()
1051
+ disposers.push(() => clearInterval(expireTimer))
1052
+ } catch (error) {
1053
+ logger.warn(`[dsh-vigil] 无法启动隔离区清理定时器:${String(error)}`)
1054
+ }
1055
+
1056
+ // ---- activation record ----------------------------------------------
1057
+ const killSwitch = isDisabled()
1058
+ runtime.audit.record({
1059
+ kind: 'event',
1060
+ event: 'activate',
1061
+ tool: null,
1062
+ decision: 'none',
1063
+ ruleIds: [],
1064
+ reason: `dsh-vigil v${version} 已挂载(mode=${runtime.config.mode})${killSwitch ? ';停机开关已启用' : ''}`,
1065
+ extra: {
1066
+ mode: runtime.config.mode,
1067
+ configWarnings: runtime.warnings,
1068
+ sage: runtime.sage.status,
1069
+ integrity: runtime.integrity.state,
1070
+ settingsEntryId: entryId,
1071
+ },
1072
+ })
1073
+ if (runtime.warnings.length > 0) logger.warn(`[dsh-vigil] 配置警告:${runtime.warnings.join(';')}`)
1074
+ if (killSwitch) logger.warn('[dsh-vigil] 停机开关已启用:所有拦截被跳过')
1075
+
1076
+ // Enabling Sage in the config (YAML or the Settings page) downloads the engine
1077
+ // and rules in the background; the running generation uses the built-in rules
1078
+ // until the swap.
1079
+ scheduleSageProvision()
1080
+ scheduleSageUpdate()
1081
+
1082
+ // ---- unload ----------------------------------------------------------
1083
+ const cleanup = () => {
1084
+ for (const dispose of disposers.splice(0)) {
1085
+ try {
1086
+ dispose()
1087
+ } catch {
1088
+ // best effort: a failed disposer must not block the rest
1089
+ }
1090
+ }
1091
+ }
1092
+ try {
1093
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
1094
+ else ctx.on('dispose', cleanup)
1095
+ } catch (error) {
1096
+ logger.warn(`[dsh-vigil] 无法注册卸载清理:${truncate(String(error), 200)}`)
1097
+ }
1098
+ }
1099
+
1100
+ /**
1101
+ * The settings namespace is the Loader entry id; the client page finds the same
1102
+ * descriptor by matching it.
1103
+ * @param {any} ctx
1104
+ * @returns {string|null}
1105
+ */
1106
+ function readEntryId(ctx) {
1107
+ try {
1108
+ const id = ctx?.fiber?.entry?.options?.id
1109
+ return typeof id === 'string' && id !== '' ? id : null
1110
+ } catch {
1111
+ return null
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ * The profile's bundled package manager, used for the Sage download because a
1117
+ * packaged Harness may not ship npm on PATH.
1118
+ * @param {any} ctx
1119
+ * @returns {{ command: string, args: string[], env: Record<string, string> }|undefined}
1120
+ */
1121
+ function readPackageManager(ctx) {
1122
+ try {
1123
+ const profile = typeof ctx?.get === 'function' ? ctx.get('profileContext') : undefined
1124
+ const manager = profile?.packageManager
1125
+ if (!manager || typeof manager.command !== 'string' || manager.command === '') return undefined
1126
+ return {
1127
+ command: manager.command,
1128
+ args: Array.isArray(manager.args) ? manager.args.map(String) : [],
1129
+ env: manager.env && typeof manager.env === 'object' ? { ...manager.env } : {},
1130
+ }
1131
+ } catch {
1132
+ return undefined
1133
+ }
1134
+ }