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