@twinsearth/ai-prison-dsh-plugin 1.6.0 → 1.7.0

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.
@@ -1,107 +1,28 @@
1
1
  import fs from 'node:fs'
2
- import os from 'node:os'
3
2
  import path from 'node:path'
4
- import v8 from 'node:v8'
5
3
  import crypto from 'node:crypto'
6
- import { spawn } from 'node:child_process'
7
- import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
8
- import { probeBudget } from './budget-probe.js'
9
- import { createTamperMonitor } from './tamper-monitor.js'
10
- import { remediationFor } from './remediation.js'
11
- import { notify } from './notifier.js'
4
+ import { watchdogState } from './watchdog-state.js'
5
+ import { createBootWatch } from './boot-watch.js'
6
+ import { createTamperMonitor, normalizeTamperPolicy } from './tamper-monitor.js'
12
7
  import { startRssScannerV2 } from './rss-scan.js'
13
- import {
14
- attributeCrash,
15
- classifyWaterline,
16
- decideToolGuard,
17
- diffBaseline,
18
- escalationLevel,
19
- formatBytes,
20
- hotOperationTriggered,
21
- mergeEstimate,
22
- operationWeight,
23
- parseCrashLog,
24
- thresholdsFor,
25
- rankTopPlugins,
26
- topOperations,
27
- } from './watchdog-policy.js'
28
-
29
- const SAMPLE_MS = 5_000
30
- const FLUSH_MS = 30_000
31
- const CRASH_HEAD_BYTES = 256 * 1024
32
- const BASELINE_DELAY_MS = 60_000
33
- const PAUSE_GRACE_MS = 10 * 60_000
34
- const CRASH_WINDOW_MS = 10 * 60_000
35
- const MAX_JOURNAL_RECORDS = 4000
36
- const EXEMPT_TARGETS = new Set([
37
- 'dsh-base',
38
- 'dsh-web-app',
39
- '@deepseek-ai/dsh-base',
40
- '@deepseek-ai/dsh-web-app',
41
- '@twinsearth/ai-prison-dsh-plugin',
42
- ])
43
-
44
- function resolveProfileDir() {
45
- const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.trim()
46
- if (fromEnv) return fromEnv
47
- const name = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE.trim() ? process.env.DSH_PROFILE.trim() : 'desktop'
48
- return path.join(os.homedir(), '.dsh', 'profiles', name)
49
- }
50
-
51
- function resolveLogsDir() {
52
- const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
53
- return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'logs')
54
- }
55
-
56
- function resolveJournalDir() {
57
- const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
58
- return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'plugin-operations')
59
- }
60
-
61
- function readHead(file, bytes) {
62
- let fd
63
- try {
64
- fd = fs.openSync(file, 'r')
65
- const buffer = Buffer.alloc(bytes)
66
- const read = fs.readSync(fd, buffer, 0, bytes, 0)
67
- return buffer.subarray(0, read).toString('utf8')
68
- } catch {
69
- return ''
70
- } finally {
71
- if (fd !== undefined) {
72
- try {
73
- fs.closeSync(fd)
74
- } catch {
75
- // ignore
76
- }
77
- }
78
- }
79
- }
80
-
81
- function readJournalRecords(journalDir) {
82
- const records = []
83
- for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
84
- const file = path.join(journalDir, name)
85
- let text = ''
86
- try {
87
- text = fs.readFileSync(file, 'utf8')
88
- } catch {
89
- continue
90
- }
91
- for (const line of text.split('\n').slice(-MAX_JOURNAL_RECORDS)) {
92
- const trimmed = line.trim()
93
- if (!trimmed) continue
94
- try {
95
- records.push(JSON.parse(trimmed))
96
- } catch {
97
- // ignore partial line
98
- }
99
- }
100
- }
101
- return records
102
- }
103
-
104
- /** Read-only watchdog runtime. Enforcement never touches plugin files, only the manager API. */
8
+ import { decideToolGuard, prunePluginState } from './watchdog-policy.js'
9
+ import { BASELINE_DELAY_MS, EXEMPT_TARGETS, SAMPLE_MS, createLogger, resolveJournalDir, resolveLogsDir, resolveProfileDir } from './watchdog-core.js'
10
+ import { createPersistence } from './watchdog-persistence.js'
11
+ import { createEnforcement } from './watchdog-enforcement.js'
12
+ import { createCrash } from './watchdog-crash.js'
13
+ import { createBudget } from './watchdog-budget.js'
14
+ import { createSampler } from './watchdog-sampler.js'
15
+ import { registerWatchdogApi } from './watchdog-api.js'
16
+ import { watchdogSnapshot } from './watchdog-snapshot.js'
17
+
18
+ /**
19
+ * Watchdog orchestrator.
20
+ *
21
+ * Wires the durable state, sampler, operation enforcement, crash plans, budget
22
+ * probes, tamper monitor, startup watch and HTTP surface together. Every module
23
+ * receives only the dependencies it needs; this file keeps the registration and
24
+ * lifecycle logic (Cordis inject/effect) that must stay in one place.
25
+ */
105
26
  export function createWatchdog(ctx, config = {}, logger = {}) {
106
27
  const profileDir = config.profileDir ? path.resolve(String(config.profileDir)) : resolveProfileDir()
107
28
  const dataDir = config.dataDir ? path.resolve(String(config.dataDir)) : path.join(profileDir, '.ai-prison-watchdog')
@@ -110,10 +31,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
110
31
  const stateFile = path.join(dataDir, 'state.json')
111
32
  const incidentsFile = path.join(dataDir, 'incidents.jsonl')
112
33
  const baselineFile = path.join(dataDir, 'baseline.json')
113
- const log = {
114
- info: (...args) => (typeof logger.info === 'function' ? logger.info(...args) : undefined),
115
- warn: (...args) => (typeof logger.warn === 'function' ? logger.warn(...args) : undefined),
116
- }
34
+ const log = createLogger(logger)
117
35
  const refs = { manager: null, tools: null }
118
36
  const cleanups = []
119
37
  const effect = (fn, label) => {
@@ -142,22 +60,58 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
142
60
  watchdogState.baseline = null
143
61
  for (const plan of watchdogState.plans) plan.applied = false
144
62
 
145
- let lastFlush = 0
146
- let operationWindowUntil = 0
147
- let lastOperationAt = 0
148
- const operationWindows = []
149
- let tamperMigrationDone = false
150
- let tamper = null
151
- restoreState()
152
- readCrashLogs()
63
+ // ---- persistence, enforcement, crash, budget ---------------------------
64
+ const persistence = createPersistence({ watchdogState, stateFile, incidentsFile })
65
+ persistence.restoreState()
66
+
67
+ const enforcement = createEnforcement({
68
+ watchdogState,
69
+ refs,
70
+ dataDir,
71
+ journalDir,
72
+ exemptions: EXEMPT_TARGETS,
73
+ appendIncident: persistence.appendIncident,
74
+ persist: persistence.persist,
75
+ })
76
+
77
+ const crash = createCrash({
78
+ watchdogState,
79
+ logsDir,
80
+ journalDir,
81
+ refs,
82
+ exemptions: EXEMPT_TARGETS,
83
+ appendIncident: persistence.appendIncident,
84
+ persist: persistence.persist,
85
+ enforcement,
86
+ })
87
+
88
+ const budget = createBudget({
89
+ watchdogState,
90
+ refs,
91
+ profileDir,
92
+ journalDir,
93
+ exemptions: EXEMPT_TARGETS,
94
+ appendIncident: persistence.appendIncident,
95
+ persist: persistence.persist,
96
+ enforcement,
97
+ config,
98
+ })
99
+
100
+ // ---- startup watch -----------------------------------------------------
153
101
  let bootWatch = null
154
102
  try {
155
103
  bootWatch = createBootWatch({
156
104
  dataDir,
157
105
  watchdogState,
158
106
  onTrigger: (trigger) => {
159
- appendIncident({ kind: 'startup-memory', detail: '启动期内存失控:' + trigger.reason, rateMBps: trigger.rateMBps, totalMB: trigger.totalMB })
160
- writePendingBoot({ level: 'L3', reason: 'startup-memory', safeBoot: true, disable: [], keep: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@twinsearth/ai-prison-dsh-plugin'] })
107
+ persistence.appendIncident({ kind: 'startup-memory', detail: '启动期内存失控:' + trigger.reason, rateMBps: trigger.rateMBps, totalMB: trigger.totalMB })
108
+ enforcement.writePendingBoot({
109
+ level: 'L3',
110
+ reason: 'startup-memory',
111
+ safeBoot: true,
112
+ disable: [],
113
+ keep: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@twinsearth/ai-prison-dsh-plugin'],
114
+ })
161
115
  },
162
116
  onFinish: (summary) => {
163
117
  watchdogState.boot = summary
@@ -167,8 +121,11 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
167
121
  } catch (error) {
168
122
  watchdogState.degraded = 'boot watch: ' + String((error && error.message) || error)
169
123
  }
170
- setupTamperMonitor()
171
124
 
125
+ crash.readCrashLogs()
126
+
127
+ // ---- tamper monitor ----------------------------------------------------
128
+ let tamper = null
172
129
  function setupTamperMonitor() {
173
130
  if (config.tamperMonitor === false) {
174
131
  watchdogState.tamper = { enabled: false, policy: 'off', files: [], lastCheckAt: null, lastDiff: [], restored: [], incidents: 0 }
@@ -178,15 +135,12 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
178
135
  tamper = createTamperMonitor({
179
136
  profileDir,
180
137
  dataDir,
181
- policy: config.tamperPolicy === 'restore' ? 'restore' : config.tamperPolicy === 'alert' ? 'alert' : 'observe',
138
+ policy: normalizeTamperPolicy(config.tamperPolicy),
182
139
  graceMs: Number(config.tamperGraceMs) >= 0 ? Number(config.tamperGraceMs) : 15_000,
183
140
  intervalMs: Number(config.tamperIntervalMs) > 0 ? Number(config.tamperIntervalMs) : 30_000,
184
- shouldIgnore: () => Date.now() < operationWindowUntil || Date.now() - lastOperationAt < 120000,
185
- isWithinOperationWindow: (mtimeMs) => {
186
- const now = Date.now()
187
- return operationWindows.some((window) => mtimeMs >= window.startedAt - 5000 && mtimeMs <= (window.settledAt || now) + 5000)
188
- },
189
- onTamper: handleTamper,
141
+ shouldIgnore: () => enforcement.shouldIgnoreWrites(),
142
+ isWithinOperationWindow: (mtimeMs) => enforcement.isWithinOperationWindow(mtimeMs),
143
+ onTamper: (result) => enforcement.handleTamper(result),
190
144
  log: (message) => log.info('[ai-prison-watchdog] ' + message),
191
145
  })
192
146
  watchdogState.tamper = tamper.status()
@@ -196,254 +150,13 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
196
150
  watchdogState.degraded = 'tamper monitor: ' + String((error && error.message) || error)
197
151
  }
198
152
  }
153
+ setupTamperMonitor()
199
154
 
200
155
  function refreshTamperStatus() {
201
156
  if (tamper) watchdogState.tamper = tamper.status()
202
157
  }
203
158
 
204
- function handleTamper(result) {
205
- if (!result || !Array.isArray(result.diffs) || result.diffs.length === 0) return
206
- const files = result.diffs.map((diff) => diff.file)
207
- const policy = (watchdogState.tamper && watchdogState.tamper.policy) || 'observe'
208
- appendIncident({ kind: 'tamper', files, policy, restored: result.restored, detail: '配置漂移:' + files.join(', ') + (policy === 'observe' ? '(observe:仅记录,不恢复不关闭)' : '') })
209
- let target = null
210
- let evidence = []
211
- try {
212
- const records = readJournalRecords(journalDir).filter((record) => {
213
- const at = Date.parse((record && record.operation && record.operation.time) || 0)
214
- return Number.isFinite(at) && Date.now() - at < 6 * 3600 * 1000
215
- })
216
- const attribution = attributeCrash(records, { hostRunId: null })
217
- target = attribution.picked ? attribution.picked.target : null
218
- evidence = attribution.candidates
219
- } catch {
220
- target = null
221
- }
222
- const applied = Boolean(watchdogState.enforce && target && policy === 'restore')
223
- const plan = { at: new Date().toISOString(), level: 'L1', crash: null, reason: 'tamper', remediation: remediationFor('tamper'), target, inFlight: false, evidence: { files: result.diffs, candidates: evidence }, applied }
224
- watchdogState.plans.push(plan)
225
- if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
226
- if (applied) {
227
- watchdogState.quarantine.set(target, { reason: 'tamper', level: 'L1', at: plan.at, release: 'manual', evidence: '配置漂移:' + files.join(', '), remediation: remediationFor('tamper') })
228
- void disableTarget(target, 'tamper')
229
- writePendingBoot({ level: 'L1', reason: 'tamper', disable: [target], keep: [] })
230
- appendIncident({ kind: 'tamper-enforced', target, files, detail: '配置漂移后已隔离 ' + target })
231
- }
232
- persist(true)
233
- }
234
-
235
- const RSS_INTERVAL_MS = 60_000
236
- let rssTimer = null
237
- let rssScanning = false
238
-
239
- function scanChildRss() {
240
- if (process.platform !== 'win32' || rssScanning) return
241
- const manager = refs.manager
242
- if (!manager || typeof manager.listBundles !== 'function') return
243
- rssScanning = true
244
- const script = [
245
- "$ErrorActionPreference='SilentlyContinue'",
246
- "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine } | ForEach-Object { ($_.ProcessId.ToString() + '|' + [string]$_.WorkingSetSize + '|' + $_.CommandLine) }",
247
- ].join('; ')
248
- let output = ''
249
- const child = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })
250
- child.stdout.on('data', (chunk) => { output += String(chunk) })
251
- child.on('error', () => { rssScanning = false })
252
- child.on('exit', () => {
253
- rssScanning = false
254
- void manager
255
- .listBundles()
256
- .then((rows) => {
257
- const enabled = rows.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name)).map((row) => row.name)
258
- const totals = new Map()
259
- for (const line of output.split('\n')) {
260
- const parts = line.trim().split('|')
261
- if (parts.length < 3) continue
262
- const pid = Number(parts[0])
263
- const bytes = Number(parts[1]) || 0
264
- const commandLine = parts.slice(2).join('|')
265
- if (pid === process.pid || commandLine.includes('dsh-desktop-host')) continue
266
- for (const name of enabled) {
267
- const winNeedle = 'node_modules' + path.sep + name.split('/').join(path.sep)
268
- const posixNeedle = 'node_modules/' + name
269
- if (commandLine.includes(winNeedle) || commandLine.includes(posixNeedle)) {
270
- totals.set(name, (totals.get(name) || 0) + bytes)
271
- break
272
- }
273
- }
274
- }
275
- const rss = { ...(watchdogState.rss || {}) }
276
- for (const [name, bytes] of totals) rss[name] = bytes
277
- watchdogState.rss = rss
278
- watchdogState.rssAt = new Date().toISOString()
279
- })
280
- .catch(() => {})
281
- })
282
- }
283
-
284
- function startRssScanner() {
285
- if (rssTimer || process.platform !== 'win32' || watchdogState.config.rssScan !== true) return
286
- const timer = setTimeout(scanChildRss, 5000)
287
- if (typeof timer.unref === 'function') timer.unref()
288
- rssTimer = setInterval(scanChildRss, RSS_INTERVAL_MS)
289
- if (typeof rssTimer.unref === 'function') rssTimer.unref()
290
- }
291
- function persist(force = false) {
292
- const now = Date.now()
293
- if (!force && now - lastFlush < FLUSH_MS) return
294
- lastFlush = now
295
- const payload = {
296
- startedAt: watchdogState.startedAt,
297
- lastCrashScan: watchdogState.lastCrashScan,
298
- incidents: watchdogState.incidents.slice(-50),
299
- escalation: watchdogState.escalation,
300
- baseline: watchdogState.baseline,
301
- budgets: watchdogState.budgets,
302
- quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
303
- rss: watchdogState.rss || {},
304
- rssAt: watchdogState.rssAt || null,
305
- rssError: watchdogState.rssError || null,
306
- rssStats: watchdogState.rssStats || null,
307
- rssServiceError: watchdogState.rssServiceError || null,
308
- rssAttempts: watchdogState.rssAttempts || 0,
309
- migratedTamperQuarantine: tamperMigrationDone,
310
- }
311
- try {
312
- fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
313
- } catch {
314
- // ignore
315
- }
316
- }
317
-
318
- function restoreState() {
319
- try {
320
- const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
321
- watchdogState.lastCrashScan = Number(parsed.lastCrashScan) > 0 ? Number(parsed.lastCrashScan) : 0
322
- if (Array.isArray(parsed.incidents)) watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
323
- if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
324
- if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
325
- if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
326
- if (parsed.rss && typeof parsed.rss === 'object') watchdogState.rss = parsed.rss
327
- if (parsed.rssAt) watchdogState.rssAt = parsed.rssAt
328
- if (parsed.rssStats) watchdogState.rssStats = parsed.rssStats
329
- watchdogState.rssAttempts = Number(parsed.rssAttempts) || 0
330
- tamperMigrationDone = parsed.migratedTamperQuarantine === true
331
- if (Array.isArray(parsed.quarantine)) {
332
- let dropped = 0
333
- for (const entry of parsed.quarantine) {
334
- if (!tamperMigrationDone && entry && entry.reason === 'tamper') {
335
- dropped += 1
336
- continue
337
- }
338
- if (entry && typeof entry.target === 'string') watchdogState.quarantine.set(entry.target, { reason: entry.reason || 'crash', level: entry.level || 'L1', at: entry.at || new Date().toISOString(), release: entry.release || 'manual', evidence: entry.evidence || '' })
339
- }
340
- if (dropped > 0) {
341
- watchdogState.incidents.push({ at: new Date().toISOString(), mode: watchdogState.mode, kind: 'migration', detail: '清理 ' + dropped + ' 条 1.4.3/1.4.4 误判的 tamper 隔离(操作窗口归因已修复)' })
342
- }
343
- tamperMigrationDone = true
344
- }
345
- } catch {
346
- // first run or unreadable state: start clean
347
- }
348
- }
349
-
350
- function appendIncident(incident) {
351
- const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
352
- if (watchdogState.config && watchdogState.config.notify === true && ['freeze', 'pause', 'quarantine', 'tamper', 'crash-enforced', 'budget'].includes(record.kind)) {
353
- try {
354
- notify(record)
355
- } catch {
356
- // notifications are best effort
357
- }
358
- }
359
- watchdogState.incidents.push(record)
360
- if (watchdogState.incidents.length > MAX_INCIDENTS) watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
361
- try {
362
- fs.appendFileSync(incidentsFile, `${JSON.stringify(record)}\n`)
363
- const stat = fs.statSync(incidentsFile)
364
- if (stat.size > 1024 * 1024) {
365
- const lines = fs.readFileSync(incidentsFile, 'utf8').trim().split('\n').slice(-500)
366
- fs.writeFileSync(incidentsFile, `${lines.join('\n')}\n`)
367
- }
368
- } catch {
369
- // auditing is best-effort
370
- }
371
- return record
372
- }
373
-
374
- // ---- memory waterline ----------------------------------------------------
375
- function sample() {
376
- let heap
377
- try {
378
- heap = v8.getHeapStatistics()
379
- } catch {
380
- heap = { heap_size_limit: 0, used_heap_size: 0, total_heap_size: 0 }
381
- }
382
- const usage = process.memoryUsage()
383
- const heapLimit = Number(heap.heap_size_limit) > 0 ? Number(heap.heap_size_limit) : 4 * 1024 * 1024 * 1024
384
- const thresholds = thresholdsFor(heapLimit)
385
- watchdogState.thresholds = thresholds
386
- const heapUsed = Number(usage.heapUsed) > 0 ? Number(usage.heapUsed) : Number(heap.used_heap_size) || 0
387
- const previous = watchdogState.waterline
388
- const waterline = classifyWaterline(heapUsed, thresholds, previous)
389
- const record = {
390
- t: new Date().toISOString(),
391
- heapUsed,
392
- heapTotal: Number(usage.heapTotal) || Number(heap.total_heap_size) || 0,
393
- external: Number(usage.external) || 0,
394
- rss: Number(usage.rss) || 0,
395
- heapLimit,
396
- waterline,
397
- }
398
- watchdogState.latest = record
399
- watchdogState.waterline = waterline
400
- watchdogState.strongWarn = waterline !== 'ok' && heapUsed >= thresholds.opWarn
401
- watchdogState.samples.push(record)
402
- if (watchdogState.samples.length > MAX_SAMPLES) watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
403
-
404
- if (waterline === 'frost' && !watchdogState.frozenAt) {
405
- watchdogState.frozenAt = record.t
406
- const incident = appendIncident({
407
- kind: 'freeze',
408
- level: 'frost',
409
- heapUsed,
410
- heapLimit,
411
- detail: `heap ${formatBytes(heapUsed)} ≥ block ${formatBytes(thresholds.totalBlock)}:冻结插件操作`,
412
- remediation: remediationFor('freeze'),
413
- })
414
- log.warn(`[ai-prison-watchdog] ${incident.detail}`)
415
- persist(true)
416
- } else if (waterline === 'pause' && !watchdogState.pausedAt) {
417
- watchdogState.pausedAt = record.t
418
- appendIncident({
419
- kind: 'pause',
420
- level: 'pause',
421
- heapUsed,
422
- heapLimit,
423
- detail: `heap ${formatBytes(heapUsed)} ≥ pause ${formatBytes(thresholds.totalPause)}:插件操作需二次确认`,
424
- remediation: remediationFor('pause'),
425
- })
426
- persist(true)
427
- } else if (waterline === 'warn' && previous !== 'warn' && previous === 'ok') {
428
- appendIncident({ kind: 'waterline', level: 'warn', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ warn ${formatBytes(thresholds.totalWarn)}` })
429
- }
430
- if (waterline === 'ok') {
431
- watchdogState.pausedAt = null
432
- watchdogState.frozenAt = null
433
- watchdogState.graceUntil = null
434
- }
435
- if (waterline === 'warn') {
436
- watchdogState.frozenAt = null
437
- watchdogState.graceUntil = null
438
- }
439
- if (watchdogState.strongWarn && waterline === 'pause') {
440
- appendIncident({ kind: 'strong-warn', level: 'pause', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ 强警告 ${formatBytes(thresholds.opWarn)}` })
441
- }
442
- maybeWriteBaseline()
443
- refreshTamperStatus()
444
- }
445
-
446
- // ---- clean baseline (requirement 4, dry-run in P1) ----------------------
159
+ // ---- clean baseline ----------------------------------------------------
447
160
  function maybeWriteBaseline() {
448
161
  if (watchdogState.baseline && watchdogState.baseline.runId === watchdogState.runId) return
449
162
  if (!watchdogState.startedAt) return
@@ -475,374 +188,43 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
475
188
  } catch {
476
189
  // ignore
477
190
  }
478
- appendIncident({ kind: 'baseline', detail: `记录干净基线:${bundles.length} 个 bundle` })
479
- persist(true)
191
+ persistence.appendIncident({ kind: 'baseline', detail: `记录干净基线:${bundles.length} 个 bundle` })
192
+ persistence.persist(true)
480
193
  } catch (error) {
481
194
  watchdogState.degraded = `baseline: ${String((error && error.message) || error)}`
482
195
  }
483
196
  }
484
197
 
485
- // ---- plugin operation accounting / hot-op jail (requirement 2) ----------
486
- const inflight = new Map()
487
-
488
- function onOperation(operation) {
489
- try {
490
- if (!operation || typeof operation !== 'object') return
491
- const target = typeof operation.target === 'string' && operation.target ? operation.target : null
492
- if (!target) return
493
- if ((watchdogState.suppressUntil.get(target) || 0) > Date.now()) return
494
- const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
495
- if (operation.phase === 'started') {
496
- operationWindowUntil = Date.now() + 4000
497
- lastOperationAt = Date.now()
498
- operationWindows.push({ startedAt: Date.now(), settledAt: null })
499
- if (operationWindows.length > 20) operationWindows.shift()
500
- inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
501
- entry.lastAt = operation.time || entry.lastAt
502
- watchdogState.operations.set(target, entry)
503
- return
504
- }
505
- if (operation.phase !== 'settled') return
506
- operationWindowUntil = Date.now() + 4000
507
- lastOperationAt = Date.now()
508
- for (let i = operationWindows.length - 1; i >= 0; i -= 1) {
509
- if (operationWindows[i].settledAt === null) { operationWindows[i].settledAt = Date.now(); break }
510
- }
511
- const weight = operationWeight(operation)
512
- if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
513
- entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
514
- }
515
- const before = inflight.get(operation.id)
516
- inflight.delete(operation.id)
517
- if (before && watchdogState.latest && before.heapBefore > 0) {
518
- const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
519
- entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
520
- }
521
- entry.lastAt = operation.time || entry.lastAt
522
- entry.version = operation.version || entry.version
523
- entry.lastApplication = operation.application || null
524
- watchdogState.operations.set(target, entry)
525
- const additive = operation.stage === 'install' || (operation.stage === 'enable' && operation.enabled !== false)
526
- if (
527
- watchdogState.enforce &&
528
- additive &&
529
- target &&
530
- !EXEMPT_TARGETS.has(target) &&
531
- (watchdogState.waterline === 'frost' || watchdogState.waterline === 'pause') &&
532
- !(Number.isFinite(watchdogState.graceUntil) && Date.now() < watchdogState.graceUntil)
533
- ) {
534
- const level = watchdogState.waterline
535
- appendIncident({
536
- kind: level === 'frost' ? 'freeze-rollback' : 'pause-rollback',
537
- target,
538
- level,
539
- detail: (level === 'frost' ? '冻结' : '暂停') + '期间检测到面板/网页发起的增内存操作,已立即回滚关闭 ' + target,
540
- })
541
- void disableTarget(target, level + '-rollback')
542
- }
543
- if (operation.reason === 'remove' && operation.application === 'applied') {
544
- watchdogState.operations.delete(target)
545
- return
546
- }
547
- if (watchdogState.enforce && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target) && hotOperationTriggered(entry.count)) {
548
- watchdogState.quarantine.set(target, {
549
- reason: 'hot-ops',
550
- level: 'L2',
551
- at: new Date().toISOString(),
552
- release: 'restart',
553
- evidence: `本次运行内热操作计数 ${entry.count} > 5(安装/启用/热切换)`,
554
- remediation: remediationFor('hot-ops', { count: entry.count }),
555
- })
556
- appendIncident({ kind: 'quarantine', target, level: 'L2', reason: 'hot-ops', detail: `热操作 ${entry.count} 次 > 5,自动关闭` })
557
- persist(true)
558
- void disableTarget(target, 'hot-ops')
559
- }
560
- persist(true)
561
- } catch (error) {
562
- watchdogState.degraded = `operation handler: ${String((error && error.message) || error)}`
563
- }
564
- }
565
-
566
- async function disableTarget(target, reason) {
567
- const manager = refs.manager
568
- if (!manager || typeof manager.setBundleEnabled !== 'function') {
569
- watchdogState.degraded = `disable ${target}: pluginManager unavailable`
570
- return false
571
- }
572
- watchdogState.suppressUntil.set(target, Date.now() + 8000)
573
- for (let attempt = 0; attempt < 2; attempt += 1) {
574
- try {
575
- const rows = typeof manager.listBundles === 'function' ? await manager.listBundles() : []
576
- const row = rows.find((entry) => entry.name === target)
577
- if (row && row.enabled === false) return true
578
- await manager.setBundleEnabled(target, false)
579
- appendIncident({ kind: 'close', target, reason, detail: `已自动关闭 ${target}(${reason})` })
580
- return true
581
- } catch (error) {
582
- if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 500))
583
- else {
584
- appendIncident({ kind: 'close-failed', target, reason, detail: `自动关闭 ${target} 失败:${String((error && error.message) || error)}` })
585
- watchdogState.degraded = `disable ${target}: ${String((error && error.message) || error)}`
586
- return false
587
- }
588
- }
589
- }
590
- return false
591
- }
592
-
593
- function releaseTarget(target) {
594
- const entry = watchdogState.quarantine.get(target)
595
- if (!entry) return { ok: false, error: 'not quarantined' }
596
- watchdogState.quarantine.delete(target)
597
- watchdogState.suppressUntil.set(target, Date.now() + 5000)
598
- appendIncident({ kind: 'release', target, detail: `用户假释 ${target}(原因 ${entry.reason})` })
599
- persist(true)
600
- return { ok: true }
601
- }
602
-
603
- function writePendingBoot(payload) {
604
- try {
605
- fs.writeFileSync(path.join(dataDir, 'pending-boot.json'), JSON.stringify({ writtenAt: new Date().toISOString(), ...payload }, null, 2) + '\n')
606
- } catch {
607
- // wrapper reads this file; best effort
608
- }
609
- }
610
-
611
- async function disableMany(targets, reason) {
612
- const unique = [...new Set(targets)].filter((target) => target && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target))
613
- const disabled = []
614
- for (const target of unique) {
615
- watchdogState.quarantine.set(target, { reason, level: 'crash', at: new Date().toISOString(), release: 'manual', evidence: reason, remediation: remediationFor(reason) })
616
- if (await disableTarget(target, reason)) disabled.push(target)
617
- await new Promise((resolve) => setTimeout(resolve, 300))
618
- }
619
- return disabled
620
- }
621
-
622
- async function enforceCrashPlan(plan) {
623
- if (!plan || !plan.target || watchdogState.crashFallback !== 'enforce') return
624
- try {
625
- watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason, remediation: remediationFor('crash') })
626
- const disabled = [plan.target].filter((target) => !EXEMPT_TARGETS.has(target))
627
- await disableTarget(plan.target, 'crash-' + plan.level)
628
- let targets = [plan.target]
629
- if (plan.level === 'L2' || plan.level === 'L3') {
630
- const manager = refs.manager
631
- const rows = manager && typeof manager.listBundles === 'function' ? await manager.listBundles() : []
632
- const baselineNames = watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : []
633
- targets = plan.level === 'L3'
634
- ? rows.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name) && !baselineNames.includes(row.name)).map((row) => row.name)
635
- : diffBaseline(rows, watchdogState.baseline).changed.map((row) => row.name).concat(plan.target)
636
- disabled.push(...(await disableMany(targets, 'crash-' + plan.level)))
637
- }
638
- writePendingBoot({
639
- level: plan.level,
640
- reason: 'crash',
641
- attribution: plan.target,
642
- disable: [...new Set(targets)],
643
- keep: watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : [],
644
- })
645
- appendIncident({ kind: 'crash-enforced', level: plan.level, target: plan.target, detail: '已按 ' + plan.level + ' 隔离 ' + disabled.length + ' 个目标(pending-boot.json 供外部包装器下次启动前使用)' })
646
- persist(true)
647
- } catch (error) {
648
- watchdogState.degraded = 'crash enforce: ' + String((error && error.message) || error)
649
- }
650
- }
651
-
652
- async function reapplyQuarantine() {
653
- for (const [target, entry] of watchdogState.quarantine) {
654
- if (entry.release === 'restart') {
655
- watchdogState.quarantine.delete(target)
656
- continue
657
- }
658
- void disableTarget(target, 'boot-reapply')
659
- }
660
- }
661
-
662
- const probeFn = typeof config.probe === 'function' ? config.probe : probeBudget
663
- const probeMax = Number(config.probeMax) > 0 ? Number(config.probeMax) : 5
664
- const probeRetryMs = Number(config.probeRetryMs) > 0 ? Number(config.probeRetryMs) : 10 * 60 * 1000
665
- const probeMaxAgeMs = 7 * 24 * 3600 * 1000
666
-
667
- function budgetState(name, version) {
668
- const entry = watchdogState.budgets[name]
669
- if (!entry) return 'missing'
670
- if (entry.error) {
671
- const age = Date.now() - Date.parse(entry.measuredAt || 0)
672
- return age > probeRetryMs && (Number(entry.attempts) || 0) < 5 ? 'retry' : 'error'
673
- }
674
- if (entry.moduleLoadMB === undefined) return 'stale'
675
- if (!entry.version || (version && entry.version !== version)) return 'stale'
676
- if (Date.now() - Date.parse(entry.measuredAt || 0) > probeMaxAgeMs) return 'stale'
677
- return 'ok'
678
- }
679
-
680
- async function probeOne(name, version) {
681
- const previous = watchdogState.budgets[name] || {}
682
- watchdogState.probeProgress = { ...(watchdogState.probeProgress || { done: 0, total: 0 }), current: name }
683
- const result = await probeFn({ profileDir, packageName: name })
684
- if (!result || !result.ok) {
685
- watchdogState.budgets[name] = {
686
- error: String((result && result.error) || 'probe-failed').slice(0, 300),
687
- measuredAt: new Date().toISOString(),
688
- version: version || previous.version || null,
689
- attempts: (Number(previous.attempts) || 0) + 1,
690
- source: 'module-load-probe',
691
- }
692
- persist(true)
693
- return { ok: false }
694
- }
695
- watchdogState.budgets[name] = {
696
- moduleLoadMB: result.moduleLoadMB,
697
- rssMB: result.rssMB,
698
- ms: result.ms,
699
- measuredAt: new Date().toISOString(),
700
- version: version || null,
701
- attempts: (Number(previous.attempts) || 0) + 1,
702
- source: 'module-load-probe',
703
- }
704
- const thresholds = watchdogState.thresholds
705
- const mb = result.moduleLoadMB
706
- if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
707
- appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,禁止该插件' })
708
- if (watchdogState.enforce) {
709
- watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB', remediation: remediationFor('budget') })
710
- void disableTarget(name, 'budget-over-500MB')
711
- writePendingBoot({ level: 'L1', reason: 'budget', disable: [name], keep: [] })
712
- }
713
- } else if (thresholds && mb >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
714
- appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
715
- }
716
- persist(true)
717
- return { ok: true }
718
- }
719
-
720
- async function scheduleProbe({ force = false } = {}) {
721
- if (watchdogState.probeRunning) return watchdogState.probeProgress
722
- const manager = refs.manager
723
- if (!manager || typeof manager.listBundles !== 'function') return null
724
- let rows
725
- try {
726
- rows = await manager.listBundles()
727
- } catch {
728
- return null
729
- }
730
- const recent = new Set()
731
- const cutoff = Date.now() - 30 * 60 * 1000
732
- for (const record of readJournalRecords(journalDir)) {
733
- const operation = record && record.operation
734
- if (!operation || !operation.target) continue
735
- if (operation.stage !== 'install' && operation.stage !== 'enable') continue
736
- if (Date.parse(operation.time || 0) < cutoff) continue
737
- recent.add(operation.target)
738
- }
739
- const candidates = rows
740
- .filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name))
741
- .map((row) => ({ name: row.name, version: row.version ? String(row.version) : '', state: budgetState(row.name, row.version ? String(row.version) : '') }))
742
- .filter((candidate) => candidate.state !== 'ok')
743
- .sort((a, b) => (recent.has(b.name) ? 1 : 0) - (recent.has(a.name) ? 1 : 0))
744
- .slice(0, force ? Math.max(probeMax, Number(config.probeMaxForce) > 0 ? Number(config.probeMaxForce) : 15) : probeMax)
745
- watchdogState.probeProgress = { done: 0, total: candidates.length, current: null, finishedAt: null }
746
- if (candidates.length === 0) return watchdogState.probeProgress
747
- watchdogState.probeRunning = true
748
- for (const candidate of candidates) {
749
- if (watchdogState.waterline !== 'ok') break
750
- const outcome = await probeOne(candidate.name, candidate.version)
751
- watchdogState.probeProgress = { ...watchdogState.probeProgress, done: watchdogState.probeProgress.done + 1, current: candidate.name, lastOk: Boolean(outcome && outcome.ok) }
752
- if (candidates.length > 1) await new Promise((resolve) => setTimeout(resolve, Number(config.probeGapMs) >= 0 ? Number(config.probeGapMs) : 1500))
753
- }
754
- watchdogState.probeProgress = { ...watchdogState.probeProgress, current: null, finishedAt: new Date().toISOString() }
755
- watchdogState.probeRunning = false
756
- persist(true)
757
- return watchdogState.probeProgress
758
- }
759
-
760
- // ---- crash attribution and dry-run plans (requirements 3 & 4) -----------
761
- function readCrashLogs() {
762
- let entries
763
- try {
764
- entries = fs.readdirSync(logsDir, { withFileTypes: true })
765
- } catch {
766
- return
767
- }
768
- let newest = watchdogState.lastCrashScan
769
- const crashes = []
770
- for (const entry of entries) {
771
- if (!entry.isFile() || !/^crash-.*-host\.log$/.test(entry.name)) continue
772
- const file = path.join(logsDir, entry.name)
773
- let stat
774
- try {
775
- stat = fs.statSync(file)
776
- } catch {
777
- continue
778
- }
779
- if (stat.mtimeMs <= watchdogState.lastCrashScan) continue
780
- const text = readHead(file, CRASH_HEAD_BYTES)
781
- const parsed = parseCrashLog(text)
782
- if (!parsed.valid) continue
783
- crashes.push({ file: entry.name, mtimeMs: stat.mtimeMs, parsed })
784
- if (stat.mtimeMs > newest) newest = stat.mtimeMs
785
- }
786
- if (crashes.length === 0) return
787
- const records = readJournalRecords(journalDir)
788
- for (const crash of crashes) {
789
- watchdogState.escalation.crashes.push(Date.now())
790
- const recent = watchdogState.escalation.crashes.filter((at) => Date.now() - at <= CRASH_WINDOW_MS)
791
- watchdogState.escalation.crashes = recent
792
- const level = escalationLevel(recent.length)
793
- watchdogState.escalation.level = level
794
- const attribution = attributeCrash(records, crash.parsed)
795
- watchdogState.hostRunId = crash.parsed.hostRunId || null
796
- const plan = {
797
- at: new Date().toISOString(),
798
- level,
799
- remediation: remediationFor('crash'),
800
- crash: { file: crash.file, time: crash.parsed.time, phase: crash.parsed.phase, oom: crash.parsed.oom, hostExitCode: crash.parsed.hostExitCode },
801
- hostRunId: crash.parsed.hostRunId,
802
- target: attribution.picked ? attribution.picked.target : null,
803
- inFlight: attribution.picked ? Boolean(attribution.picked.inFlight) : false,
804
- evidence: attribution.candidates,
805
- reason: attribution.reason,
806
- applied: false,
807
- }
808
- watchdogState.plans.push(plan)
809
- if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
810
- appendIncident({
811
- kind: 'crash',
812
- file: crash.file,
813
- time: crash.parsed.time,
814
- phase: crash.parsed.phase,
815
- hostExitCode: crash.parsed.hostExitCode,
816
- oom: crash.parsed.oom,
817
- level,
818
- target: plan.target,
819
- inFlight: plan.inFlight,
820
- detail: plan.target
821
- ? `崩溃归因:${plan.target}${plan.inFlight ? '(崩溃时操作仍在途)' : ''};${watchdogState.enforce ? 'enforce' : 'dry-run'}`
822
- : '崩溃归因失败:本 run 无安装/启用记录,不自动关闭',
823
- })
824
- if (watchdogState.enforce && watchdogState.crashFallback === 'enforce') void enforceCrashPlan(plan)
825
- }
826
- if (newest > watchdogState.lastCrashScan) {
827
- watchdogState.lastCrashScan = newest
828
- persist(true)
829
- }
830
- }
198
+ // ---- sampler -----------------------------------------------------------
199
+ const sampler = createSampler({
200
+ watchdogState,
201
+ persist: persistence.persist,
202
+ appendIncident: persistence.appendIncident,
203
+ log,
204
+ onAfterSample: () => {
205
+ maybeWriteBaseline()
206
+ refreshTamperStatus()
207
+ },
208
+ })
831
209
 
832
- // ---- registration --------------------------------------------------------
210
+ // ---- registration ------------------------------------------------------
833
211
  try {
834
212
  if (typeof ctx.inject === 'function') {
835
213
  ctx.inject(['pluginManager'], (child) => {
836
214
  refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
837
215
  if (refs.manager) {
838
216
  if (bootWatch && typeof refs.manager.listBundles === 'function') {
839
- void refs.manager.listBundles().then((rows) => bootWatch.setBundleCount(rows.length)).catch(() => {})
217
+ void refs.manager.listBundles().then((rows) => {
218
+ bootWatch.setBundleCount(rows.length)
219
+ const removed = prunePluginState(watchdogState, rows)
220
+ if (Object.values(removed).some((targets) => targets.length > 0)) persistence.persist(true)
221
+ }).catch(() => {})
840
222
  }
841
- void reapplyQuarantine()
842
- startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets: EXEMPT_TARGETS })
223
+ void enforcement.reapplyQuarantine()
224
+ startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident: persistence.appendIncident, exemptTargets: EXEMPT_TARGETS })
843
225
  if (config.probeAuto === true) {
844
226
  const probeTimer = setTimeout(() => {
845
- void scheduleProbe()
227
+ void budget.scheduleProbe()
846
228
  }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
847
229
  if (typeof probeTimer.unref === 'function') probeTimer.unref()
848
230
  }
@@ -880,13 +262,13 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
880
262
  const interval = Number(config.sampleMs) > 0 ? Number(config.sampleMs) : SAMPLE_MS
881
263
  if (typeof ctx.effect === 'function') {
882
264
  effect(() => {
883
- sample()
884
- const timer = setInterval(sample, interval)
265
+ sampler.sample()
266
+ const timer = setInterval(sampler.sample, interval)
885
267
  return () => clearInterval(timer)
886
268
  }, 'ai-prison-watchdog: sampler')
887
269
  } else {
888
- sample()
889
- setInterval(sample, interval)
270
+ sampler.sample()
271
+ setInterval(sampler.sample, interval)
890
272
  }
891
273
  } catch (error) {
892
274
  watchdogState.degraded = `sampler: ${String((error && error.message) || error)}`
@@ -895,102 +277,46 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
895
277
  try {
896
278
  if (typeof ctx.on === 'function') {
897
279
  if (typeof ctx.effect === 'function') {
898
- effect(() => ctx.on('plugin-manager/operation', onOperation), 'ai-prison-watchdog: operations')
280
+ effect(() => ctx.on('plugin-manager/operation', enforcement.onOperation), 'ai-prison-watchdog: operations')
899
281
  } else {
900
- ctx.on('plugin-manager/operation', onOperation)
282
+ ctx.on('plugin-manager/operation', enforcement.onOperation)
901
283
  }
902
284
  }
903
285
  } catch (error) {
904
286
  watchdogState.degraded = `operations: ${String((error && error.message) || error)}`
905
287
  }
906
288
 
907
- try {
908
- if (typeof ctx.inject === 'function') {
909
- ctx.inject(['connection'], (child) => {
910
- try {
911
- child.effect(
912
- () =>
913
- child.connection.fetch.register({
914
- path: '/api/ai-prison/watchdog/status',
915
- methods: ['GET'],
916
- requestBody: 'buffered',
917
- fetch: async () => Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
918
- }),
919
- 'ai-prison-watchdog: status api',
920
- )
921
- child.effect(
922
- () =>
923
- child.connection.fetch.register({
924
- path: '/api/ai-prison/watchdog/action',
925
- methods: ['POST'],
926
- requestBody: 'buffered',
927
- fetch: async (request) => {
928
- let body = {}
929
- try {
930
- body = await request.json()
931
- } catch {
932
- body = {}
933
- }
934
- const action = typeof body.action === 'string' ? body.action : ''
935
- const target = typeof body.target === 'string' ? body.target : ''
936
- if (action === 'heap6g') {
937
- const enabled = body.enabled === true
938
- const flagPath = path.join('E:/ToFuture/tools', 'heap6g.flag')
939
- try {
940
- if (enabled) fs.writeFileSync(flagPath, JSON.stringify({ enabled: true, at: new Date().toISOString() }, null, 2) + '\n')
941
- else fs.rmSync(flagPath, { force: true })
942
- watchdogState.heap6g = enabled
943
- appendIncident({ kind: 'heap6g', detail: enabled ? '已请求下次启动使用 6GB 堆(由 AI Prison Guard 应用)' : '已取消 6GB 堆请求' })
944
- } catch (error) {
945
- return Response.json({ ok: false, error: String((error && error.message) || error) }, { status: 500 })
946
- }
947
- return Response.json({ ok: true, enabled })
948
- }
949
- if (action === 'probe') {
950
- const progress = await scheduleProbe({ force: true })
951
- return Response.json({ ok: true, progress })
952
- }
953
- if (action === 'confirm-pause') {
954
- watchdogState.graceUntil = Date.now() + PAUSE_GRACE_MS
955
- appendIncident({ kind: 'pause-confirmed', detail: `用户二次确认继续插件操作(宽限 10 分钟)` })
956
- return Response.json({ ok: true })
957
- }
958
- if (action === 'release') return Response.json(releaseTarget(target))
959
- if (action === 'close') {
960
- const ok = await disableTarget(target, 'manual-close')
961
- return Response.json({ ok })
962
- }
963
- return Response.json({ ok: false, error: 'unknown action' }, { status: 400 })
964
- },
965
- }),
966
- 'ai-prison-watchdog: action api',
967
- )
968
- } catch (error) {
969
- watchdogState.degraded = `status api: ${String((error && error.message) || error)}`
970
- }
971
- })
972
- }
973
- } catch (error) {
974
- watchdogState.degraded = `connection: ${String((error && error.message) || error)}`
975
- }
289
+ const apiRegistered = registerWatchdogApi({
290
+ ctx,
291
+ watchdogState,
292
+ getSnapshot: watchdogSnapshot,
293
+ actions: {
294
+ scheduleProbe: budget.scheduleProbe,
295
+ releaseTarget: enforcement.releaseTarget,
296
+ disableTarget: enforcement.disableTarget,
297
+ appendIncident: persistence.appendIncident,
298
+ },
299
+ logger,
300
+ })
301
+ if (!apiRegistered) watchdogState.degraded = 'status api: not registered'
976
302
 
977
303
  log.info(`[ai-prison-watchdog] ${watchdogState.mode} 模式已启动(数据目录 ${dataDir})`)
978
304
  return {
979
305
  snapshot: watchdogSnapshot,
980
- sample,
981
- readCrashLogs,
982
- probeNow: (options) => scheduleProbe(options),
306
+ sample: sampler.sample,
307
+ readCrashLogs: crash.readCrashLogs,
308
+ probeNow: (options) => budget.scheduleProbe(options),
983
309
  tamperCheck: (options) => {
984
310
  if (!tamper) return null
985
311
  const result = tamper.checkNow(options)
986
312
  refreshTamperStatus()
987
313
  return result
988
314
  },
989
- disableTarget,
990
- releaseTarget,
315
+ disableTarget: enforcement.disableTarget,
316
+ releaseTarget: enforcement.releaseTarget,
991
317
  dispose() {
992
- if (rssTimer) clearInterval(rssTimer)
993
- rssTimer = null
318
+ if (refs.rssTimer) clearInterval(refs.rssTimer)
319
+ refs.rssTimer = null
994
320
  while (cleanups.length > 0) {
995
321
  const disposer = cleanups.pop()
996
322
  try {
@@ -1003,69 +329,4 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
1003
329
  }
1004
330
  }
1005
331
 
1006
- /** Top5 v2: measured + estimate + child RSS with EWMA smoothing and rank hysteresis. */
1007
- function mergedTop(state, limit) {
1008
- const operations = topOperations(state.operations, 50)
1009
- const { rows, nextRanking } = rankTopPlugins({
1010
- operations,
1011
- budgets: state.budgets || {},
1012
- rss: state.rss || {},
1013
- previous: state.ranking || {},
1014
- limit,
1015
- })
1016
- state.ranking = nextRanking
1017
- return rows.map((row) => ({
1018
- target: row.target,
1019
- count: row.count || 0,
1020
- estimateMB: row.moduleLoadMB || row.operationMB || 0,
1021
- rssMB: row.rssMB || 0,
1022
- totalMB: row.score,
1023
- lastAt: row.measuredAt || null,
1024
- version: row.version || null,
1025
- source: row.source,
1026
- }))
1027
- }
1028
- /** Serialisable snapshot shared by the tool and the panel route. */
1029
- export function watchdogSnapshot() {
1030
- const s = watchdogState
1031
- const quarantine = []
1032
- for (const [target, entry] of s.quarantine instanceof Map ? s.quarantine : []) {
1033
- quarantine.push({ target, ...entry })
1034
- }
1035
- return {
1036
- ok: Boolean(s.startedAt),
1037
- mode: s.mode,
1038
- enforce: s.enforce,
1039
- startedAt: s.startedAt,
1040
- runId: s.runId,
1041
- dataDir: s.dataDir,
1042
- degraded: s.degraded,
1043
- heap: s.latest,
1044
- thresholds: s.thresholds,
1045
- waterline: s.waterline,
1046
- strongWarn: s.strongWarn,
1047
- pausedAt: s.pausedAt,
1048
- graceUntil: s.graceUntil,
1049
- frozenAt: s.frozenAt,
1050
- samples: s.samples.slice(-30),
1051
- operations: mergedTop(s, 10),
1052
- topFive: mergedTop(s, 5),
1053
- probeProgress: s.probeProgress || null,
1054
- quarantine,
1055
- plans: s.plans.slice(-5),
1056
- escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
1057
- crashFallback: s.crashFallback || 'enforce',
1058
- baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
1059
- budgets: s.budgets,
1060
- tamper: s.tamper || null,
1061
- boot: s.boot || null,
1062
- heap6g: s.heap6g === true,
1063
- rss: s.rss || {},
1064
- rssAt: s.rssAt || null,
1065
- rssError: s.rssError || null,
1066
- rssStats: s.rssStats || null,
1067
- rssServiceError: s.rssServiceError || null,
1068
- incidents: s.incidents.slice(-20),
1069
- generatedAt: new Date().toISOString(),
1070
- }
1071
- }
332
+ export { watchdogSnapshot }