@twinsearth/ai-prison-dsh-plugin 1.2.1 → 1.4.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.
@@ -2,10 +2,17 @@ import fs from 'node:fs'
2
2
  import os from 'node:os'
3
3
  import path from 'node:path'
4
4
  import v8 from 'node:v8'
5
+ import crypto from 'node:crypto'
5
6
  import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
7
+ import { probeBudget } from './budget-probe.js'
6
8
  import {
9
+ attributeCrash,
7
10
  classifyWaterline,
11
+ decideToolGuard,
12
+ diffBaseline,
13
+ escalationLevel,
8
14
  formatBytes,
15
+ hotOperationTriggered,
9
16
  mergeEstimate,
10
17
  operationWeight,
11
18
  parseCrashLog,
@@ -15,8 +22,18 @@ import {
15
22
 
16
23
  const SAMPLE_MS = 5_000
17
24
  const FLUSH_MS = 30_000
18
- const CRASH_HEAD_BYTES = 8 * 1024
19
- const LEVEL_RANK = { ok: 0, warn: 1, pause: 2, block: 3 }
25
+ const CRASH_HEAD_BYTES = 256 * 1024
26
+ const BASELINE_DELAY_MS = 60_000
27
+ const PAUSE_GRACE_MS = 10 * 60_000
28
+ const CRASH_WINDOW_MS = 10 * 60_000
29
+ const MAX_JOURNAL_RECORDS = 4000
30
+ const EXEMPT_TARGETS = new Set([
31
+ 'dsh-base',
32
+ 'dsh-web-app',
33
+ '@deepseek-ai/dsh-base',
34
+ '@deepseek-ai/dsh-web-app',
35
+ '@twinsearth/ai-prison-dsh-plugin',
36
+ ])
20
37
 
21
38
  function resolveProfileDir() {
22
39
  const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.trim()
@@ -30,6 +47,11 @@ function resolveLogsDir() {
30
47
  return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'logs')
31
48
  }
32
49
 
50
+ function resolveJournalDir() {
51
+ const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
52
+ return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'plugin-operations')
53
+ }
54
+
33
55
  function readHead(file, bytes) {
34
56
  let fd
35
57
  try {
@@ -50,17 +72,49 @@ function readHead(file, bytes) {
50
72
  }
51
73
  }
52
74
 
53
- /** Read-only watchdog runtime. It observes; it never enables or disables plugins. */
75
+ function readJournalRecords(journalDir) {
76
+ const records = []
77
+ for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
78
+ const file = path.join(journalDir, name)
79
+ let text = ''
80
+ try {
81
+ text = fs.readFileSync(file, 'utf8')
82
+ } catch {
83
+ continue
84
+ }
85
+ for (const line of text.split('\n').slice(-MAX_JOURNAL_RECORDS)) {
86
+ const trimmed = line.trim()
87
+ if (!trimmed) continue
88
+ try {
89
+ records.push(JSON.parse(trimmed))
90
+ } catch {
91
+ // ignore partial line
92
+ }
93
+ }
94
+ }
95
+ return records
96
+ }
97
+
98
+ /** Read-only watchdog runtime. Enforcement never touches plugin files, only the manager API. */
54
99
  export function createWatchdog(ctx, config = {}, logger = {}) {
55
100
  const profileDir = resolveProfileDir()
56
101
  const dataDir = config.dataDir ? path.resolve(String(config.dataDir)) : path.join(profileDir, '.ai-prison-watchdog')
57
102
  const logsDir = config.logsDir ? path.resolve(String(config.logsDir)) : resolveLogsDir()
103
+ const journalDir = config.journalDir ? path.resolve(String(config.journalDir)) : resolveJournalDir()
58
104
  const stateFile = path.join(dataDir, 'state.json')
59
105
  const incidentsFile = path.join(dataDir, 'incidents.jsonl')
106
+ const baselineFile = path.join(dataDir, 'baseline.json')
60
107
  const log = {
61
108
  info: (...args) => (typeof logger.info === 'function' ? logger.info(...args) : undefined),
62
109
  warn: (...args) => (typeof logger.warn === 'function' ? logger.warn(...args) : undefined),
63
110
  }
111
+ const refs = { manager: null, tools: null }
112
+ const cleanups = []
113
+ const effect = (fn, label) => {
114
+ const disposer = ctx.effect(fn, label)
115
+ if (typeof disposer === 'function') cleanups.push(disposer)
116
+ return disposer
117
+ }
64
118
 
65
119
  try {
66
120
  fs.mkdirSync(dataDir, { recursive: true })
@@ -68,28 +122,54 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
68
122
  watchdogState.degraded = `cannot create ${dataDir}: ${String((error && error.message) || error)}`
69
123
  }
70
124
 
71
- watchdogState.mode = 'observe'
125
+ watchdogState.mode = config.enforce === false ? 'observe' : 'enforce'
126
+ watchdogState.enforce = config.enforce !== false
72
127
  watchdogState.startedAt = new Date().toISOString()
128
+ watchdogState.runId = crypto.randomUUID()
73
129
  watchdogState.dataDir = dataDir
74
130
  watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
131
+ watchdogState.crashFallback = config.crashFallback === 'dry-run' ? 'dry-run' : 'enforce'
132
+ watchdogState.probeStarted = false
75
133
  watchdogState.lastCrashScan = 0
76
- let lastFlush = 0
77
- const cleanups = []
78
- const effect = (fn, label) => {
79
- const disposer = ctx.effect(fn, label)
80
- if (typeof disposer === 'function') cleanups.push(disposer)
81
- return disposer
82
- }
134
+ watchdogState.baseline = null
135
+ for (const plan of watchdogState.plans) plan.applied = false
83
136
 
137
+ let lastFlush = 0
84
138
  restoreState()
85
139
  readCrashLogs()
86
140
 
141
+ function persist(force = false) {
142
+ const now = Date.now()
143
+ if (!force && now - lastFlush < FLUSH_MS) return
144
+ lastFlush = now
145
+ const payload = {
146
+ startedAt: watchdogState.startedAt,
147
+ lastCrashScan: watchdogState.lastCrashScan,
148
+ incidents: watchdogState.incidents.slice(-50),
149
+ escalation: watchdogState.escalation,
150
+ baseline: watchdogState.baseline,
151
+ budgets: watchdogState.budgets,
152
+ quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
153
+ }
154
+ try {
155
+ fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
156
+ } catch {
157
+ // ignore
158
+ }
159
+ }
160
+
87
161
  function restoreState() {
88
162
  try {
89
163
  const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
90
164
  watchdogState.lastCrashScan = Number(parsed.lastCrashScan) > 0 ? Number(parsed.lastCrashScan) : 0
91
- if (Array.isArray(parsed.incidents)) {
92
- watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
165
+ if (Array.isArray(parsed.incidents)) watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
166
+ if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
167
+ if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
168
+ if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
169
+ if (Array.isArray(parsed.quarantine)) {
170
+ for (const entry of parsed.quarantine) {
171
+ 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 || '' })
172
+ }
93
173
  }
94
174
  } catch {
95
175
  // first run or unreadable state: start clean
@@ -99,9 +179,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
99
179
  function appendIncident(incident) {
100
180
  const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
101
181
  watchdogState.incidents.push(record)
102
- if (watchdogState.incidents.length > MAX_INCIDENTS) {
103
- watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
104
- }
182
+ if (watchdogState.incidents.length > MAX_INCIDENTS) watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
105
183
  try {
106
184
  fs.appendFileSync(incidentsFile, `${JSON.stringify(record)}\n`)
107
185
  const stat = fs.statSync(incidentsFile)
@@ -110,27 +188,12 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
110
188
  fs.writeFileSync(incidentsFile, `${lines.join('\n')}\n`)
111
189
  }
112
190
  } catch {
113
- // auditing is best-effort in observe mode
191
+ // auditing is best-effort
114
192
  }
115
193
  return record
116
194
  }
117
195
 
118
- function persist(force = false) {
119
- const now = Date.now()
120
- if (!force && now - lastFlush < FLUSH_MS) return
121
- lastFlush = now
122
- const payload = {
123
- startedAt: watchdogState.startedAt,
124
- lastCrashScan: watchdogState.lastCrashScan,
125
- incidents: watchdogState.incidents.slice(-50),
126
- }
127
- try {
128
- fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
129
- } catch {
130
- // ignore
131
- }
132
- }
133
-
196
+ // ---- memory waterline ----------------------------------------------------
134
197
  function sample() {
135
198
  let heap
136
199
  try {
@@ -140,10 +203,11 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
140
203
  }
141
204
  const usage = process.memoryUsage()
142
205
  const heapLimit = Number(heap.heap_size_limit) > 0 ? Number(heap.heap_size_limit) : 4 * 1024 * 1024 * 1024
143
- watchdogState.thresholds = thresholdsFor(heapLimit)
206
+ const thresholds = thresholdsFor(heapLimit)
207
+ watchdogState.thresholds = thresholds
144
208
  const heapUsed = Number(usage.heapUsed) > 0 ? Number(usage.heapUsed) : Number(heap.used_heap_size) || 0
145
- const waterline = classifyWaterline(heapUsed, watchdogState.thresholds)
146
209
  const previous = watchdogState.waterline
210
+ const waterline = classifyWaterline(heapUsed, thresholds, previous)
147
211
  const record = {
148
212
  t: new Date().toISOString(),
149
213
  heapUsed,
@@ -155,81 +219,291 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
155
219
  }
156
220
  watchdogState.latest = record
157
221
  watchdogState.waterline = waterline
222
+ watchdogState.strongWarn = waterline !== 'ok' && heapUsed >= thresholds.opWarn
158
223
  watchdogState.samples.push(record)
159
- if (watchdogState.samples.length > MAX_SAMPLES) {
160
- watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
161
- }
162
- if (waterline !== previous && LEVEL_RANK[waterline] > LEVEL_RANK[previous]) {
224
+ if (watchdogState.samples.length > MAX_SAMPLES) watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
225
+
226
+ if (waterline === 'frost' && !watchdogState.frozenAt) {
227
+ watchdogState.frozenAt = record.t
163
228
  const incident = appendIncident({
164
- kind: 'waterline',
165
- level: waterline,
229
+ kind: 'freeze',
230
+ level: 'frost',
231
+ heapUsed,
232
+ heapLimit,
233
+ detail: `heap ${formatBytes(heapUsed)} ≥ block ${formatBytes(thresholds.totalBlock)}:冻结插件操作`,
234
+ })
235
+ log.warn(`[ai-prison-watchdog] ${incident.detail}`)
236
+ persist(true)
237
+ } else if (waterline === 'pause' && !watchdogState.pausedAt) {
238
+ watchdogState.pausedAt = record.t
239
+ appendIncident({
240
+ kind: 'pause',
241
+ level: 'pause',
166
242
  heapUsed,
167
243
  heapLimit,
168
- detail: `heap ${formatBytes(heapUsed)} / limit ${formatBytes(heapLimit)}`,
244
+ detail: `heap ${formatBytes(heapUsed)} ≥ pause ${formatBytes(thresholds.totalPause)}:插件操作需二次确认`,
169
245
  })
170
- log.warn(`[ai-prison-watchdog] waterline ${waterline}: ${incident.detail}(observe 模式,不关闭插件)`)
171
246
  persist(true)
247
+ } else if (waterline === 'warn' && previous !== 'warn' && previous === 'ok') {
248
+ appendIncident({ kind: 'waterline', level: 'warn', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ warn ${formatBytes(thresholds.totalWarn)}` })
249
+ }
250
+ if (waterline === 'ok') {
251
+ watchdogState.pausedAt = null
252
+ watchdogState.frozenAt = null
253
+ watchdogState.graceUntil = null
254
+ }
255
+ if (waterline === 'warn') {
256
+ watchdogState.frozenAt = null
257
+ watchdogState.graceUntil = null
258
+ }
259
+ if (watchdogState.strongWarn && waterline === 'pause') {
260
+ appendIncident({ kind: 'strong-warn', level: 'pause', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ 强警告 ${formatBytes(thresholds.opWarn)}` })
261
+ }
262
+ maybeWriteBaseline()
263
+ }
264
+
265
+ // ---- clean baseline (requirement 4, dry-run in P1) ----------------------
266
+ function maybeWriteBaseline() {
267
+ if (watchdogState.baseline && watchdogState.baseline.runId === watchdogState.runId) return
268
+ if (!watchdogState.startedAt) return
269
+ const age = Date.now() - Date.parse(watchdogState.startedAt)
270
+ if (age < BASELINE_DELAY_MS) return
271
+ if (watchdogState.waterline === 'pause' || watchdogState.waterline === 'frost') return
272
+ if (watchdogState.quarantine.size > 0) return
273
+ const recentCrash = watchdogState.incidents.some((incident) => incident.kind === 'crash' && Date.parse(incident.at || 0) >= Date.parse(watchdogState.startedAt))
274
+ if (recentCrash) return
275
+ void collectBaseline()
276
+ }
277
+
278
+ async function collectBaseline() {
279
+ const manager = refs.manager
280
+ if (!manager || typeof manager.listBundles !== 'function') return
281
+ try {
282
+ const rows = await manager.listBundles()
283
+ const bundles = rows
284
+ .filter((row) => row.enabled)
285
+ .map((row) => ({ name: row.name, version: String(row.version || ''), enabled: true }))
286
+ watchdogState.baseline = {
287
+ at: new Date().toISOString(),
288
+ runId: watchdogState.runId,
289
+ hostRunId: watchdogState.hostRunId || null,
290
+ bundles,
291
+ }
292
+ try {
293
+ fs.writeFileSync(baselineFile, `${JSON.stringify(watchdogState.baseline, null, 2)}\n`)
294
+ } catch {
295
+ // ignore
296
+ }
297
+ appendIncident({ kind: 'baseline', detail: `记录干净基线:${bundles.length} 个 bundle` })
298
+ persist(true)
299
+ } catch (error) {
300
+ watchdogState.degraded = `baseline: ${String((error && error.message) || error)}`
172
301
  }
173
302
  }
174
303
 
175
- /** target -> { heapBefore } for operations currently in flight. */
304
+ // ---- plugin operation accounting / hot-op jail (requirement 2) ----------
176
305
  const inflight = new Map()
177
306
 
178
307
  function onOperation(operation) {
179
308
  try {
180
309
  if (!operation || typeof operation !== 'object') return
181
310
  const target = typeof operation.target === 'string' && operation.target ? operation.target : null
182
- if (!target || operation.reason === 'remove') {
183
- if (operation.phase === 'settled' && target) {
184
- watchdogState.operations.delete(target)
185
- }
186
- return
187
- }
188
- const entry = watchdogState.operations.get(target) || {
189
- count: 0,
190
- estimateMB: 0,
191
- lastAt: null,
192
- version: operation.version || null,
193
- lastApplication: null,
194
- }
311
+ if (!target) return
312
+ if ((watchdogState.suppressUntil.get(target) || 0) > Date.now()) return
313
+ const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
195
314
  if (operation.phase === 'started') {
196
315
  inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
197
316
  entry.lastAt = operation.time || entry.lastAt
198
317
  watchdogState.operations.set(target, entry)
199
318
  return
200
319
  }
201
- if (operation.phase === 'settled') {
202
- const weight = operationWeight(operation)
203
- if (weight > 0 && operation.application !== 'failed') {
204
- entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
205
- }
206
- const before = inflight.get(operation.id)
207
- inflight.delete(operation.id)
208
- if (before && watchdogState.latest && before.heapBefore > 0) {
209
- const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
210
- entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
211
- }
212
- entry.lastAt = operation.time || entry.lastAt
213
- entry.version = operation.version || entry.version
214
- entry.lastApplication = operation.application || null
215
- watchdogState.operations.set(target, entry)
216
- const thresholds = watchdogState.thresholds
217
- if (thresholds && entry.estimateMB >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
218
- appendIncident({
219
- kind: 'plugin-estimate',
220
- target,
221
- estimateMB: entry.estimateMB,
222
- level: entry.estimateMB >= Math.round(thresholds.singleBlock / (1024 * 1024)) ? 'block' : 'warn',
223
- detail: `${target} 估算 ${entry.estimateMB} MB(observe 模式,仅提醒)`,
224
- })
225
- }
320
+ if (operation.phase !== 'settled') return
321
+ const weight = operationWeight(operation)
322
+ if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
323
+ entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
324
+ }
325
+ const before = inflight.get(operation.id)
326
+ inflight.delete(operation.id)
327
+ if (before && watchdogState.latest && before.heapBefore > 0) {
328
+ const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
329
+ entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
330
+ }
331
+ entry.lastAt = operation.time || entry.lastAt
332
+ entry.version = operation.version || entry.version
333
+ entry.lastApplication = operation.application || null
334
+ watchdogState.operations.set(target, entry)
335
+ if (operation.reason === 'remove' && operation.application === 'applied') {
336
+ watchdogState.operations.delete(target)
337
+ return
338
+ }
339
+ if (watchdogState.enforce && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target) && hotOperationTriggered(entry.count)) {
340
+ watchdogState.quarantine.set(target, {
341
+ reason: 'hot-ops',
342
+ level: 'L2',
343
+ at: new Date().toISOString(),
344
+ release: 'restart',
345
+ evidence: `本次运行内热操作计数 ${entry.count} > 5(安装/启用/热切换)`,
346
+ })
347
+ appendIncident({ kind: 'quarantine', target, level: 'L2', reason: 'hot-ops', detail: `热操作 ${entry.count} 次 > 5,自动关闭` })
226
348
  persist(true)
349
+ void disableTarget(target, 'hot-ops')
227
350
  }
351
+ persist(true)
228
352
  } catch (error) {
229
353
  watchdogState.degraded = `operation handler: ${String((error && error.message) || error)}`
230
354
  }
231
355
  }
232
356
 
357
+ async function disableTarget(target, reason) {
358
+ const manager = refs.manager
359
+ if (!manager || typeof manager.setBundleEnabled !== 'function') {
360
+ watchdogState.degraded = `disable ${target}: pluginManager unavailable`
361
+ return false
362
+ }
363
+ watchdogState.suppressUntil.set(target, Date.now() + 8000)
364
+ for (let attempt = 0; attempt < 2; attempt += 1) {
365
+ try {
366
+ const rows = typeof manager.listBundles === 'function' ? await manager.listBundles() : []
367
+ const row = rows.find((entry) => entry.name === target)
368
+ if (row && row.enabled === false) return true
369
+ await manager.setBundleEnabled(target, false)
370
+ appendIncident({ kind: 'close', target, reason, detail: `已自动关闭 ${target}(${reason})` })
371
+ return true
372
+ } catch (error) {
373
+ if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 500))
374
+ else {
375
+ appendIncident({ kind: 'close-failed', target, reason, detail: `自动关闭 ${target} 失败:${String((error && error.message) || error)}` })
376
+ watchdogState.degraded = `disable ${target}: ${String((error && error.message) || error)}`
377
+ return false
378
+ }
379
+ }
380
+ }
381
+ return false
382
+ }
383
+
384
+ function releaseTarget(target) {
385
+ const entry = watchdogState.quarantine.get(target)
386
+ if (!entry) return { ok: false, error: 'not quarantined' }
387
+ watchdogState.quarantine.delete(target)
388
+ watchdogState.suppressUntil.set(target, Date.now() + 5000)
389
+ appendIncident({ kind: 'release', target, detail: `用户假释 ${target}(原因 ${entry.reason})` })
390
+ persist(true)
391
+ return { ok: true }
392
+ }
393
+
394
+ function writePendingBoot(payload) {
395
+ try {
396
+ fs.writeFileSync(path.join(dataDir, 'pending-boot.json'), JSON.stringify({ writtenAt: new Date().toISOString(), ...payload }, null, 2) + '\n')
397
+ } catch {
398
+ // wrapper reads this file; best effort
399
+ }
400
+ }
401
+
402
+ async function disableMany(targets, reason) {
403
+ const unique = [...new Set(targets)].filter((target) => target && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target))
404
+ const disabled = []
405
+ for (const target of unique) {
406
+ watchdogState.quarantine.set(target, { reason, level: 'crash', at: new Date().toISOString(), release: 'manual', evidence: reason })
407
+ if (await disableTarget(target, reason)) disabled.push(target)
408
+ await new Promise((resolve) => setTimeout(resolve, 300))
409
+ }
410
+ return disabled
411
+ }
412
+
413
+ async function enforceCrashPlan(plan) {
414
+ if (!plan || !plan.target || watchdogState.crashFallback !== 'enforce') return
415
+ try {
416
+ watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason })
417
+ const disabled = [plan.target].filter((target) => !EXEMPT_TARGETS.has(target))
418
+ await disableTarget(plan.target, 'crash-' + plan.level)
419
+ let targets = [plan.target]
420
+ if (plan.level === 'L2' || plan.level === 'L3') {
421
+ const manager = refs.manager
422
+ const rows = manager && typeof manager.listBundles === 'function' ? await manager.listBundles() : []
423
+ const baselineNames = watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : []
424
+ targets = plan.level === 'L3'
425
+ ? rows.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name) && !baselineNames.includes(row.name)).map((row) => row.name)
426
+ : diffBaseline(rows, watchdogState.baseline).changed.map((row) => row.name).concat(plan.target)
427
+ disabled.push(...(await disableMany(targets, 'crash-' + plan.level)))
428
+ }
429
+ writePendingBoot({
430
+ level: plan.level,
431
+ reason: 'crash',
432
+ attribution: plan.target,
433
+ disable: [...new Set(targets)],
434
+ keep: watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : [],
435
+ })
436
+ appendIncident({ kind: 'crash-enforced', level: plan.level, target: plan.target, detail: '已按 ' + plan.level + ' 隔离 ' + disabled.length + ' 个目标(pending-boot.json 供外部包装器下次启动前使用)' })
437
+ persist(true)
438
+ } catch (error) {
439
+ watchdogState.degraded = 'crash enforce: ' + String((error && error.message) || error)
440
+ }
441
+ }
442
+
443
+ async function reapplyQuarantine() {
444
+ for (const [target, entry] of watchdogState.quarantine) {
445
+ if (entry.release === 'restart') {
446
+ watchdogState.quarantine.delete(target)
447
+ continue
448
+ }
449
+ void disableTarget(target, 'boot-reapply')
450
+ }
451
+ }
452
+
453
+ async function probeOne(name) {
454
+ const result = await probeBudget({ profileDir, packageName: name })
455
+ if (!result.ok) {
456
+ watchdogState.budgets[name] = { error: String(result.error || 'probe-failed').slice(0, 300), measuredAt: new Date().toISOString(), source: 'module-load-probe' }
457
+ persist(true)
458
+ return
459
+ }
460
+ watchdogState.budgets[name] = { moduleLoadMB: result.moduleLoadMB, rssMB: result.rssMB, ms: result.ms, measuredAt: new Date().toISOString(), source: 'module-load-probe' }
461
+ const thresholds = watchdogState.thresholds
462
+ const mb = result.moduleLoadMB
463
+ if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
464
+ appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,建议禁止该插件' })
465
+ if (watchdogState.enforce) {
466
+ watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB' })
467
+ void disableTarget(name, 'budget-over-500MB')
468
+ writePendingBoot({ level: 'L1', reason: 'budget', disable: [name], keep: [] })
469
+ }
470
+ } else if (thresholds && mb >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
471
+ appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
472
+ }
473
+ persist(true)
474
+ }
475
+
476
+ async function scheduleProbe() {
477
+ if (watchdogState.probeStarted) return
478
+ watchdogState.probeStarted = true
479
+ const manager = refs.manager
480
+ if (!manager || typeof manager.listBundles !== 'function') return
481
+ let rows
482
+ try {
483
+ rows = await manager.listBundles()
484
+ } catch {
485
+ return
486
+ }
487
+ const recent = new Set()
488
+ const cutoff = Date.now() - 30 * 60 * 1000
489
+ for (const record of readJournalRecords(journalDir)) {
490
+ const operation = record && record.operation
491
+ if (!operation || !operation.target) continue
492
+ if (operation.stage !== 'install' && operation.stage !== 'enable') continue
493
+ if (Date.parse(operation.time || 0) < cutoff) continue
494
+ recent.add(operation.target)
495
+ }
496
+ const targets = rows
497
+ .filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name) && !watchdogState.budgets[row.name] && recent.has(row.name))
498
+ .map((row) => row.name)
499
+ .slice(0, 5)
500
+ for (const name of targets) {
501
+ if (watchdogState.waterline !== 'ok') break
502
+ await probeOne(name)
503
+ }
504
+ }
505
+
506
+ // ---- crash attribution and dry-run plans (requirements 3 & 4) -----------
233
507
  function readCrashLogs() {
234
508
  let entries
235
509
  try {
@@ -238,6 +512,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
238
512
  return
239
513
  }
240
514
  let newest = watchdogState.lastCrashScan
515
+ const crashes = []
241
516
  for (const entry of entries) {
242
517
  if (!entry.isFile() || !/^crash-.*-host\.log$/.test(entry.name)) continue
243
518
  const file = path.join(logsDir, entry.name)
@@ -248,18 +523,50 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
248
523
  continue
249
524
  }
250
525
  if (stat.mtimeMs <= watchdogState.lastCrashScan) continue
251
- const parsed = parseCrashLog(readHead(file, CRASH_HEAD_BYTES))
526
+ const text = readHead(file, CRASH_HEAD_BYTES)
527
+ const parsed = parseCrashLog(text)
252
528
  if (!parsed.valid) continue
529
+ crashes.push({ file: entry.name, mtimeMs: stat.mtimeMs, parsed })
530
+ if (stat.mtimeMs > newest) newest = stat.mtimeMs
531
+ }
532
+ if (crashes.length === 0) return
533
+ const records = readJournalRecords(journalDir)
534
+ for (const crash of crashes) {
535
+ watchdogState.escalation.crashes.push(Date.now())
536
+ const recent = watchdogState.escalation.crashes.filter((at) => Date.now() - at <= CRASH_WINDOW_MS)
537
+ watchdogState.escalation.crashes = recent
538
+ const level = escalationLevel(recent.length)
539
+ watchdogState.escalation.level = level
540
+ const attribution = attributeCrash(records, crash.parsed)
541
+ watchdogState.hostRunId = crash.parsed.hostRunId || null
542
+ const plan = {
543
+ at: new Date().toISOString(),
544
+ level,
545
+ crash: { file: crash.file, time: crash.parsed.time, phase: crash.parsed.phase, oom: crash.parsed.oom, hostExitCode: crash.parsed.hostExitCode },
546
+ hostRunId: crash.parsed.hostRunId,
547
+ target: attribution.picked ? attribution.picked.target : null,
548
+ inFlight: attribution.picked ? Boolean(attribution.picked.inFlight) : false,
549
+ evidence: attribution.candidates,
550
+ reason: attribution.reason,
551
+ applied: false,
552
+ }
553
+ watchdogState.plans.push(plan)
554
+ if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
253
555
  appendIncident({
254
556
  kind: 'crash',
255
- file: entry.name,
256
- time: parsed.time,
257
- phase: parsed.phase,
258
- hostExitCode: parsed.hostExitCode,
259
- oom: parsed.oom,
260
- detail: parsed.oom ? 'JavaScript heap out of memory' : `host exited with ${parsed.hostExitCode ?? '?'}`,
557
+ file: crash.file,
558
+ time: crash.parsed.time,
559
+ phase: crash.parsed.phase,
560
+ hostExitCode: crash.parsed.hostExitCode,
561
+ oom: crash.parsed.oom,
562
+ level,
563
+ target: plan.target,
564
+ inFlight: plan.inFlight,
565
+ detail: plan.target
566
+ ? `崩溃归因:${plan.target}${plan.inFlight ? '(崩溃时操作仍在途)' : ''};${watchdogState.enforce ? 'enforce' : 'dry-run'}`
567
+ : '崩溃归因失败:本 run 无安装/启用记录,不自动关闭',
261
568
  })
262
- if (stat.mtimeMs > newest) newest = stat.mtimeMs
569
+ if (watchdogState.enforce && watchdogState.crashFallback === 'enforce') void enforceCrashPlan(plan)
263
570
  }
264
571
  if (newest > watchdogState.lastCrashScan) {
265
572
  watchdogState.lastCrashScan = newest
@@ -267,24 +574,63 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
267
574
  }
268
575
  }
269
576
 
270
- // Sampler (P0: observe only).
577
+ // ---- registration --------------------------------------------------------
271
578
  try {
579
+ if (typeof ctx.inject === 'function') {
580
+ ctx.inject(['pluginManager'], (child) => {
581
+ refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
582
+ if (refs.manager) {
583
+ void reapplyQuarantine()
584
+ const probeTimer = setTimeout(() => {
585
+ void scheduleProbe()
586
+ }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
587
+ if (typeof probeTimer.unref === 'function') probeTimer.unref()
588
+ }
589
+ })
590
+ }
591
+ } catch (error) {
592
+ watchdogState.degraded = `pluginManager inject: ${String((error && error.message) || error)}`
593
+ }
594
+
595
+ try {
596
+ if (typeof ctx.inject === 'function' && watchdogState.enforce) {
597
+ ctx.inject(['tools'], (child) => {
598
+ refs.tools = child.tools || null
599
+ try {
600
+ if (!child.tools || typeof child.tools.guard !== 'function') return
601
+ child.effect(
602
+ () =>
603
+ child.tools.guard((execution) => {
604
+ const denial = decideToolGuard(execution, watchdogState)
605
+ return denial ? { reason: denial.reason, info: denial.info } : undefined
606
+ }),
607
+ 'ai-prison-watchdog: tool guard',
608
+ )
609
+ } catch (error) {
610
+ watchdogState.degraded = `tool guard: ${String((error && error.message) || error)}`
611
+ }
612
+ })
613
+ }
614
+ } catch (error) {
615
+ watchdogState.degraded = `tools inject: ${String((error && error.message) || error)}`
616
+ }
617
+
618
+ try {
619
+ const interval = Number(config.sampleMs) > 0 ? Number(config.sampleMs) : SAMPLE_MS
272
620
  if (typeof ctx.effect === 'function') {
273
621
  effect(() => {
274
622
  sample()
275
- const interval = Number(config.sampleMs) > 0 ? Number(config.sampleMs) : SAMPLE_MS
276
623
  const timer = setInterval(sample, interval)
277
624
  return () => clearInterval(timer)
278
625
  }, 'ai-prison-watchdog: sampler')
279
626
  } else {
280
627
  sample()
281
- setInterval(sample, SAMPLE_MS)
628
+ setInterval(sample, interval)
282
629
  }
283
630
  } catch (error) {
284
631
  watchdogState.degraded = `sampler: ${String((error && error.message) || error)}`
285
632
  }
286
633
 
287
- // Plugin-operation accounting.
288
634
  try {
289
635
  if (typeof ctx.on === 'function') {
290
636
  if (typeof ctx.effect === 'function') {
@@ -297,7 +643,6 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
297
643
  watchdogState.degraded = `operations: ${String((error && error.message) || error)}`
298
644
  }
299
645
 
300
- // Read-only HTTP snapshot for the panel.
301
646
  try {
302
647
  if (typeof ctx.inject === 'function') {
303
648
  ctx.inject(['connection'], (child) => {
@@ -308,11 +653,40 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
308
653
  path: '/api/ai-prison/watchdog/status',
309
654
  methods: ['GET'],
310
655
  requestBody: 'buffered',
311
- fetch: async () =>
312
- Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
656
+ fetch: async () => Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
313
657
  }),
314
658
  'ai-prison-watchdog: status api',
315
659
  )
660
+ child.effect(
661
+ () =>
662
+ child.connection.fetch.register({
663
+ path: '/api/ai-prison/watchdog/action',
664
+ methods: ['POST'],
665
+ requestBody: 'buffered',
666
+ fetch: async (request) => {
667
+ let body = {}
668
+ try {
669
+ body = await request.json()
670
+ } catch {
671
+ body = {}
672
+ }
673
+ const action = typeof body.action === 'string' ? body.action : ''
674
+ const target = typeof body.target === 'string' ? body.target : ''
675
+ if (action === 'confirm-pause') {
676
+ watchdogState.graceUntil = Date.now() + PAUSE_GRACE_MS
677
+ appendIncident({ kind: 'pause-confirmed', detail: `用户二次确认继续插件操作(宽限 10 分钟)` })
678
+ return Response.json({ ok: true })
679
+ }
680
+ if (action === 'release') return Response.json(releaseTarget(target))
681
+ if (action === 'close') {
682
+ const ok = await disableTarget(target, 'manual-close')
683
+ return Response.json({ ok })
684
+ }
685
+ return Response.json({ ok: false, error: 'unknown action' }, { status: 400 })
686
+ },
687
+ }),
688
+ 'ai-prison-watchdog: action api',
689
+ )
316
690
  } catch (error) {
317
691
  watchdogState.degraded = `status api: ${String((error && error.message) || error)}`
318
692
  }
@@ -322,11 +696,13 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
322
696
  watchdogState.degraded = `connection: ${String((error && error.message) || error)}`
323
697
  }
324
698
 
325
- log.info(`[ai-prison-watchdog] observe 模式已启动(数据目录 ${dataDir})`)
699
+ log.info(`[ai-prison-watchdog] ${watchdogState.mode} 模式已启动(数据目录 ${dataDir})`)
326
700
  return {
327
701
  snapshot: watchdogSnapshot,
328
702
  sample,
329
703
  readCrashLogs,
704
+ disableTarget,
705
+ releaseTarget,
330
706
  dispose() {
331
707
  while (cleanups.length > 0) {
332
708
  const disposer = cleanups.pop()
@@ -343,17 +719,34 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
343
719
  /** Serialisable snapshot shared by the tool and the panel route. */
344
720
  export function watchdogSnapshot() {
345
721
  const s = watchdogState
722
+ const quarantine = []
723
+ for (const [target, entry] of s.quarantine instanceof Map ? s.quarantine : []) {
724
+ quarantine.push({ target, ...entry })
725
+ }
346
726
  return {
347
727
  ok: Boolean(s.startedAt),
348
728
  mode: s.mode,
729
+ enforce: s.enforce,
349
730
  startedAt: s.startedAt,
731
+ runId: s.runId,
350
732
  dataDir: s.dataDir,
351
733
  degraded: s.degraded,
352
734
  heap: s.latest,
353
735
  thresholds: s.thresholds,
354
736
  waterline: s.waterline,
737
+ strongWarn: s.strongWarn,
738
+ pausedAt: s.pausedAt,
739
+ graceUntil: s.graceUntil,
740
+ frozenAt: s.frozenAt,
355
741
  samples: s.samples.slice(-30),
356
742
  operations: topOperations(s.operations, 10),
743
+ topFive: topOperations(s.operations, 5),
744
+ quarantine,
745
+ plans: s.plans.slice(-5),
746
+ escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
747
+ crashFallback: s.crashFallback || 'enforce',
748
+ baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
749
+ budgets: s.budgets,
357
750
  incidents: s.incidents.slice(-20),
358
751
  generatedAt: new Date().toISOString(),
359
752
  }