@twinsearth/ai-prison-dsh-plugin 1.4.4 → 1.4.6

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 CHANGED
@@ -2,6 +2,52 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.4.6] — 2026-11-18
6
+
7
+ ### Added — structured reason / impact / steps / release text
8
+
9
+ - New `lib/remediation.js` explains every enforcement action in four fixed
10
+ sections: why it happened, what it affects, what to do (numbered steps) and how
11
+ the plugin leaves the prison.
12
+ - Freeze, pause and every quarantine reason (hot-ops, crash, budget, tamper) now
13
+ carry a `remediation` object in the incident, the quarantine entry and the
14
+ crash/tamper plan.
15
+ - The panel "Plugin prison" renders it under each jailed plugin (title, why,
16
+ impact, numbered steps, release path); the agent tool returns the same object.
17
+ - Tests cover every remediation reason and the quarantine payload.
18
+
19
+ ### Notes
20
+ - This completes the three follow-ups requested for the probe work: the probe
21
+ publish fix and the full background probe queue shipped in 1.4.3/1.4.4; this
22
+ release adds the operator-facing explanation.
23
+
24
+ ## [1.4.5] — 2026-11-18
25
+ ## [1.4.5] — 2026-11-18
26
+
27
+ ### Fixed — tamper monitor false positives (important)
28
+
29
+ - The first tamper monitor attributed writes at **poll time**, not at write time, so
30
+ a legitimate plugin-manager write (install/enable rewrites package.json and
31
+ pnpm-lock.yaml) was classified as tampering 30 s later. That closed and jailed
32
+ plugins after every install.
33
+ - Operation windows are now recorded on `started`/`settled` and matched against
34
+ each changed file's **mtime** (±5 s), so a manager write stays legitimate even
35
+ when the poll happens after the window closed.
36
+ - One-time migration: tamper quarantine persisted by 1.4.3/1.4.4 is cleared with
37
+ an audited `migration` incident instead of re-closing those plugins on boot.
38
+
39
+ ### Fixed — budget probe could not import plugins that use harness peers
40
+
41
+ - `budget-child.mjs` now resolves `@deepseek-ai/*` and `cordis` from the DSH
42
+ installation via `module.registerHooks`, so plugins like `dsh-context` that
43
+ import `@deepseek-ai/dsh-session` at module scope can be measured.
44
+ - Also fixed a wrong `pathToFileURL` import that broke the probe child entirely.
45
+
46
+ ### Tests
47
+ - mtime operation-window suppression, legacy tamper-quarantine migration, and the
48
+ probe child import path are covered by the test suite (70 tests total).
49
+
50
+ ## [1.4.4] — 2026-11-18
5
51
  ## [1.4.4] — 2026-11-18
6
52
 
7
53
  ### Fixed — per-plugin budget probe actually works end to end
package/client.js CHANGED
@@ -443,9 +443,18 @@ window.__ModuleLoader__.load({
443
443
  h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.quarantine')),
444
444
  quarantine.length === 0
445
445
  ? h('p', { style: { ...C.muted, fontSize: 12, margin: '0 0 10px' } }, t('watchdog.noQuarantine'))
446
- : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 10 } },
447
- quarantine.map((entry) => h('div', { key: entry.target, style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
448
- h('span', { style: { ...C.mono, fontSize: 12, wordBreak: 'break-all' } }, entry.target + ' · ' + entry.reason + ' · ' + entry.level),
446
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 10 } },
447
+ quarantine.map((entry) => h('div', { key: entry.target, style: { display: 'flex', alignItems: 'flex-start', gap: 8, flexWrap: 'wrap' } },
448
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: 2, flex: '1 1 260px', minWidth: 0 } },
449
+ h('span', { style: { ...C.mono, fontSize: 12, wordBreak: 'break-all' } }, entry.target + ' · ' + entry.reason + ' · ' + entry.level),
450
+ entry.remediation ? h('div', { style: { fontSize: 11.5, color: 'var(--dsw-alias-label-secondary, #61666b)', lineHeight: 1.5 } },
451
+ h('div', { style: { fontWeight: 600 } }, entry.remediation.title),
452
+ h('div', null, entry.remediation.why),
453
+ h('div', null, entry.remediation.impact),
454
+ entry.remediation.steps.map((step, index) => h('div', { key: index }, (index + 1) + '. ' + step)),
455
+ h('div', null, '解除:' + entry.remediation.release),
456
+ ) : null,
457
+ ),
449
458
  h('button', { style: button, onClick: () => act('release', entry.target, '假释 ' + entry.target + ' ?') }, t('watchdog.release')),
450
459
  ))),
451
460
  topFive.length === 0 ? null : h('div', null,
@@ -1,14 +1,39 @@
1
+ import * as nodeModule from 'node:module'
1
2
  import { createRequire } from 'node:module'
2
3
  import { pathToFileURL } from 'node:url'
4
+ import path from 'node:path'
3
5
 
4
6
  // Child side of the AI Prison per-plugin budget probe (see budget-probe.js).
5
- // argv: [node, --expose-gc, thisFile, profileDir, packageName]
6
- const [, , profileDir, packageName] = process.argv
7
+ // argv: [node, --expose-gc, thisFile, profileDir, packageName, installDir]
8
+ const [, , profileDir, packageName, installDir] = process.argv
7
9
 
8
10
  function heapMB() {
9
11
  return process.memoryUsage().heapUsed / (1024 * 1024)
10
12
  }
11
13
 
14
+ // Plugins import peer packages such as @deepseek-ai/dsh-session that live in the
15
+ // DSH installation, not in the profile. Resolve those from the install root so
16
+ // the probe can measure the real entry module.
17
+ if (installDir && typeof nodeModule.registerHooks === 'function') {
18
+ try {
19
+ const requireFromInstall = createRequire(path.join(installDir, 'package.json'))
20
+ nodeModule.registerHooks({
21
+ resolve(specifier, context, nextResolve) {
22
+ if (specifier.startsWith('@deepseek-ai/') || specifier === 'cordis') {
23
+ try {
24
+ return { url: pathToFileURL(requireFromInstall.resolve(specifier)).href, shortCircuit: true }
25
+ } catch {
26
+ // fall through to the default resolver
27
+ }
28
+ }
29
+ return nextResolve(specifier, context)
30
+ },
31
+ })
32
+ } catch {
33
+ // hooks are best effort; the probe still measures what resolves normally
34
+ }
35
+ }
36
+
12
37
  async function main() {
13
38
  if (!profileDir || !packageName) {
14
39
  console.log(JSON.stringify({ ok: false, error: 'missing-args' }))
@@ -12,10 +12,11 @@ const CHILD = fileURLToPath(new URL('./budget-child.mjs', import.meta.url))
12
12
  export function probeBudget({ profileDir, packageName, timeoutMs = 25_000 } = {}) {
13
13
  return new Promise((resolve) => {
14
14
  const nodeExe = process.env.DSH_PROBE_NODE || process.execPath
15
+ const installDir = process.env.DSH_INSTALL_DIR || (typeof process.argv[2] === 'string' && process.argv[2].endsWith('package.json') === false ? process.argv[2] : '')
15
16
  const env = { ...process.env }
16
17
  if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1'
17
18
  delete env.NODE_OPTIONS
18
- const child = spawn(nodeExe, ['--expose-gc', CHILD, profileDir, packageName], {
19
+ const child = spawn(nodeExe, ['--expose-gc', CHILD, profileDir, packageName, installDir || ''], {
19
20
  env,
20
21
  windowsHide: true,
21
22
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Human-readable remediation for every AI Prison enforcement action.
3
+ *
4
+ * Each entry answers four questions in fixed order so the panel and the agent
5
+ * say the same thing: why it happened, what it affects, what to do, and how the
6
+ * plugin gets out of prison.
7
+ */
8
+ const REMEDIATION = {
9
+ 'hot-ops': {
10
+ title: '插件热操作过频',
11
+ why: '同一插件在本次运行中被反复安装、启用或热切换(超过 5 次),插件图被反复重组,是内存暴涨与崩溃的高风险来源。',
12
+ impact: '该插件已被自动关闭并隔离;本次运行内不再加载。',
13
+ steps: [
14
+ '确认你确实需要反复开关它;安装/升级完成一次即可,不要连续点击。',
15
+ '重启 DSH(或在本面板点"假释")后重新启用一次。',
16
+ '如果它每次启动都反复启用自己,向插件作者反馈"启动期重复 enable"。',
17
+ ],
18
+ release: '重启 DSH 会自动释放;也可以在面板"插件监狱"里点"假释"手动释放。',
19
+ },
20
+ crash: {
21
+ title: '该插件被归因为崩溃来源',
22
+ why: 'DSH 宿主进程崩溃(如爆内存),崩溃日志里的 hostRunId 与本插件最后一次安装/启用记录匹配。',
23
+ impact: '该插件已被隔离并关闭,隔离在重启后仍生效,避免崩溃循环。',
24
+ steps: [
25
+ '先重启 DSH,确认在没有该插件时环境稳定。',
26
+ '检查插件版本是否有修复(升级到最新版),或查看其 README 的已知崩溃问题。',
27
+ '确需继续使用时,在面板"插件监狱"点"假释",一次只放行一个插件并观察内存。',
28
+ ],
29
+ release: '仅手动释放(面板"假释");重启不会自动解除,防止崩溃循环。',
30
+ },
31
+ budget: {
32
+ title: '启动内存超过硬阈值',
33
+ why: '隔离探针实测该插件模块加载的 retained 内存超过 500 MB 硬阈值(或该项目历史上留下超限记录)。',
34
+ impact: '该插件已被关闭并隔离,且写入 pending-boot.json,下次启动前会被外部 guard 直接剔除。',
35
+ steps: [
36
+ '升级到该插件的修复版本;若仍超限,联系作者或换用轻量替代。',
37
+ '如果确认是误报(插件版本已变化),在面板"插件监狱"点"假释"后重新测量预算。',
38
+ '临时需要使用时,只放行一次并在面板观察内存 Top5。',
39
+ ],
40
+ release: '手动释放(面板"假释");释放后再测一次预算确认。',
41
+ },
42
+ tamper: {
43
+ title: '关键配置文件被非插件管理器修改',
44
+ why: 'profile 的 package.json / cordis.patch.yml / pnpm-workspace.yaml / pnpm-lock.yaml 在插件管理器操作窗口之外发生了变化(被修改或删除)。',
45
+ impact: '已把被改动内容备份到 .ai-prison-watchdog/tampered/,默认恢复原文件;归因到的最后安装/启用插件已被隔离。',
46
+ steps: [
47
+ '检查 .ai-prison-watchdog/tampered/ 下的备份,确认改动来自哪里(手工编辑、脚本、其他工具)。',
48
+ '不要在 DSH 运行中手工改 profile 配置;确需修改时先退出 DSH。',
49
+ '确认无插件行为异常后,在面板"插件监狱"点"假释"恢复该插件。',
50
+ ],
51
+ release: '手动释放(面板"假释");恢复前先核对 tampered/ 备份。',
52
+ },
53
+ freeze: {
54
+ title: '内存水位达到冻结线',
55
+ why: '宿主堆内存超过 5 GB 冻结阈值(6 GB host;4 GB host 按比例折算),继续加载/重组插件会直接导致 OOM 崩溃。',
56
+ impact: '所有增内存的插件操作被禁止(安装、启用、热切换、重载、卸载等),Agent 的 plugin_manager 也已被拒绝。',
57
+ steps: [
58
+ '在面板"内存看护 → Top5"里立即关闭占用最大的插件。',
59
+ '关闭后等待 1 分钟让堆回落,或直接重启 DSH。',
60
+ '排查是谁在持续吃内存:优先怀疑最近开启/升级的插件。',
61
+ ],
62
+ release: '堆回落到冻结线以下并持续 60 秒会自动解除;或重启 DSH。',
63
+ },
64
+ pause: {
65
+ title: '内存水位达到暂停线,需要二次确认',
66
+ why: '宿主堆内存超过 3.9 GB 暂停阈值,插件操作已暂停,防止继续推高水位。',
67
+ impact: '所有增内存的插件操作被临时拦截;本次操作需要你明确确认。',
68
+ steps: [
69
+ '先在"内存看护 → Top5"里关闭一个不需要的插件。',
70
+ '确认要继续时,点面板的"我已知晓:允许插件操作 10 分钟"。',
71
+ '宽限期内若水位继续上涨到 5 GB,会自动升级为冻结。',
72
+ ],
73
+ release: '点"二次确认"给 10 分钟宽限;堆回落到 3.6 GB 以下会自动解除。',
74
+ },
75
+ }
76
+
77
+ /** Look up the remediation for one enforcement reason. */
78
+ export function remediationFor(reason, extra = {}) {
79
+ const code = REMEDIATION[reason] ? reason : 'hot-ops'
80
+ const base = REMEDIATION[code]
81
+ return {
82
+ code,
83
+ title: base.title,
84
+ why: base.why,
85
+ impact: base.impact,
86
+ steps: [...base.steps],
87
+ release: base.release,
88
+ ...(extra.count !== undefined ? { detail: `本次运行计数 ${extra.count}` } : {}),
89
+ }
90
+ }
91
+
92
+ /** Reasons this module knows about (used by tests and the panel). */
93
+ export const REMEDIATION_REASONS = Object.keys(REMEDIATION)
@@ -33,7 +33,9 @@ export function snapshotCriticalFiles(profileDir) {
33
33
  const file = path.join(profileDir, rel)
34
34
  const bytes = readIfExists(file)
35
35
  contents.set(rel, bytes)
36
- files.push({ file: rel, exists: bytes !== null, hash: bytes === null ? null : sha256(bytes), size: bytes === null ? 0 : bytes.length })
36
+ let mtimeMs = 0
37
+ try { mtimeMs = fs.statSync(file).mtimeMs } catch { mtimeMs = 0 }
38
+ files.push({ file: rel, exists: bytes !== null, hash: bytes === null ? null : sha256(bytes), size: bytes === null ? 0 : bytes.length, mtimeMs })
37
39
  }
38
40
  return { files, contents }
39
41
  }
@@ -45,9 +47,9 @@ export function diffSnapshots(previous, next) {
45
47
  for (const entry of next || []) {
46
48
  const old = before.get(entry.file)
47
49
  if (!old) continue
48
- if (!old.exists && entry.exists) diffs.push({ file: entry.file, kind: 'created' })
49
- else if (old.exists && !entry.exists) diffs.push({ file: entry.file, kind: 'deleted' })
50
- else if (old.exists && entry.exists && old.hash !== entry.hash) diffs.push({ file: entry.file, kind: 'modified' })
50
+ if (!old.exists && entry.exists) diffs.push({ file: entry.file, kind: 'created', mtimeMs: entry.mtimeMs })
51
+ else if (old.exists && !entry.exists) diffs.push({ file: entry.file, kind: 'deleted', mtimeMs: entry.mtimeMs })
52
+ else if (old.exists && entry.exists && old.hash !== entry.hash) diffs.push({ file: entry.file, kind: 'modified', mtimeMs: entry.mtimeMs })
51
53
  }
52
54
  return diffs
53
55
  }
@@ -108,6 +110,7 @@ export function createTamperMonitor({
108
110
  graceMs = STARTUP_GRACE_MS,
109
111
  intervalMs = DEFAULT_INTERVAL_MS,
110
112
  shouldIgnore,
113
+ isWithinOperationWindow,
111
114
  onTamper,
112
115
  log,
113
116
  } = {}) {
@@ -138,9 +141,13 @@ export function createTamperMonitor({
138
141
  status.skipped = null
139
142
  return { ok: true, diffs: [], restored: [] }
140
143
  }
144
+ // A changed file written inside a plugin-manager operation window is a
145
+ // legitimate manager write even when this poll runs after the window closed.
146
+ const withinWindow = (mtimeMs) => typeof isWithinOperationWindow === 'function' && isWithinOperationWindow(mtimeMs)
147
+ const suspicious = force ? diffs : diffs.filter((diff) => !withinWindow(diff.mtimeMs))
141
148
  const startup = !force && Date.now() - baselineAt < graceMs
142
149
  const ignored = !force && typeof shouldIgnore === 'function' && shouldIgnore()
143
- if (startup || ignored) {
150
+ if (startup || ignored || suspicious.length === 0) {
144
151
  baseline = next
145
152
  baselineAt = Date.now()
146
153
  status.skipped = startup ? 'startup' : 'operation-window'
@@ -148,16 +155,16 @@ export function createTamperMonitor({
148
155
  if (typeof log === 'function') log(`tamper monitor: ${diffs.map((d) => d.file).join(', ')} ${status.skipped}(视为正常写入)`)
149
156
  return { ok: true, diffs: [], restored: [], skipped: status.skipped }
150
157
  }
151
- const backup = backupTampered(dataDir, profileDir, diffs)
152
- const restored = policy === 'restore' ? restoreBaseline(profileDir, baseline.contents, diffs) : []
153
- status.lastDiff = diffs
158
+ const backup = backupTampered(dataDir, profileDir, suspicious)
159
+ const restored = policy === 'restore' ? restoreBaseline(profileDir, baseline.contents, suspicious) : []
160
+ status.lastDiff = suspicious
154
161
  status.restored = restored
155
162
  status.incidents += 1
156
163
  // Re-baseline on the post-restore state so one drift yields one alert.
157
164
  baseline = snapshotCriticalFiles(profileDir)
158
165
  baselineAt = Date.now()
159
166
  if (backup.length > 0 && typeof log === 'function') log(`tamper monitor: 备份到 ${backup.length} 个文件`)
160
- if (typeof onTamper === 'function') onTamper({ diffs, restored, policy, backup })
167
+ if (typeof onTamper === 'function') onTamper({ diffs: suspicious, restored, policy, backup })
161
168
  return { ok: true, diffs, restored, backup }
162
169
  }
163
170
 
@@ -6,6 +6,7 @@ import crypto from 'node:crypto'
6
6
  import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
7
7
  import { probeBudget } from './budget-probe.js'
8
8
  import { createTamperMonitor } from './tamper-monitor.js'
9
+ import { remediationFor } from './remediation.js'
9
10
  import {
10
11
  attributeCrash,
11
12
  classifyWaterline,
@@ -137,6 +138,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
137
138
 
138
139
  let lastFlush = 0
139
140
  let operationWindowUntil = 0
141
+ const operationWindows = []
142
+ let tamperMigrationDone = false
140
143
  let tamper = null
141
144
  restoreState()
142
145
  readCrashLogs()
@@ -155,6 +158,10 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
155
158
  graceMs: Number(config.tamperGraceMs) >= 0 ? Number(config.tamperGraceMs) : 15_000,
156
159
  intervalMs: Number(config.tamperIntervalMs) > 0 ? Number(config.tamperIntervalMs) : 30_000,
157
160
  shouldIgnore: () => Date.now() < operationWindowUntil,
161
+ isWithinOperationWindow: (mtimeMs) => {
162
+ const now = Date.now()
163
+ return operationWindows.some((window) => mtimeMs >= window.startedAt - 5000 && mtimeMs <= (window.settledAt || now) + 5000)
164
+ },
158
165
  onTamper: handleTamper,
159
166
  log: (message) => log.info('[ai-prison-watchdog] ' + message),
160
167
  })
@@ -188,11 +195,11 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
188
195
  target = null
189
196
  }
190
197
  const applied = Boolean(watchdogState.enforce && target)
191
- const plan = { at: new Date().toISOString(), level: 'L1', crash: null, reason: 'tamper', target, inFlight: false, evidence: { files: result.diffs, candidates: evidence }, applied }
198
+ 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 }
192
199
  watchdogState.plans.push(plan)
193
200
  if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
194
201
  if (applied) {
195
- watchdogState.quarantine.set(target, { reason: 'tamper', level: 'L1', at: plan.at, release: 'manual', evidence: '配置漂移:' + files.join(', ') })
202
+ watchdogState.quarantine.set(target, { reason: 'tamper', level: 'L1', at: plan.at, release: 'manual', evidence: '配置漂移:' + files.join(', '), remediation: remediationFor('tamper') })
196
203
  void disableTarget(target, 'tamper')
197
204
  writePendingBoot({ level: 'L1', reason: 'tamper', disable: [target], keep: [] })
198
205
  appendIncident({ kind: 'tamper-enforced', target, files, detail: '配置漂移后已隔离 ' + target })
@@ -212,6 +219,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
212
219
  baseline: watchdogState.baseline,
213
220
  budgets: watchdogState.budgets,
214
221
  quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
222
+ migratedTamperQuarantine: tamperMigrationDone,
215
223
  }
216
224
  try {
217
225
  fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
@@ -228,10 +236,20 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
228
236
  if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
229
237
  if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
230
238
  if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
239
+ tamperMigrationDone = parsed.migratedTamperQuarantine === true
231
240
  if (Array.isArray(parsed.quarantine)) {
241
+ let dropped = 0
232
242
  for (const entry of parsed.quarantine) {
243
+ if (!tamperMigrationDone && entry && entry.reason === 'tamper') {
244
+ dropped += 1
245
+ continue
246
+ }
233
247
  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 || '' })
234
248
  }
249
+ if (dropped > 0) {
250
+ watchdogState.incidents.push({ at: new Date().toISOString(), mode: watchdogState.mode, kind: 'migration', detail: '清理 ' + dropped + ' 条 1.4.3/1.4.4 误判的 tamper 隔离(操作窗口归因已修复)' })
251
+ }
252
+ tamperMigrationDone = true
235
253
  }
236
254
  } catch {
237
255
  // first run or unreadable state: start clean
@@ -293,6 +311,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
293
311
  heapUsed,
294
312
  heapLimit,
295
313
  detail: `heap ${formatBytes(heapUsed)} ≥ block ${formatBytes(thresholds.totalBlock)}:冻结插件操作`,
314
+ remediation: remediationFor('freeze'),
296
315
  })
297
316
  log.warn(`[ai-prison-watchdog] ${incident.detail}`)
298
317
  persist(true)
@@ -304,6 +323,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
304
323
  heapUsed,
305
324
  heapLimit,
306
325
  detail: `heap ${formatBytes(heapUsed)} ≥ pause ${formatBytes(thresholds.totalPause)}:插件操作需二次确认`,
326
+ remediation: remediationFor('pause'),
307
327
  })
308
328
  persist(true)
309
329
  } else if (waterline === 'warn' && previous !== 'warn' && previous === 'ok') {
@@ -376,6 +396,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
376
396
  const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
377
397
  if (operation.phase === 'started') {
378
398
  operationWindowUntil = Date.now() + 4000
399
+ operationWindows.push({ startedAt: Date.now(), settledAt: null })
400
+ if (operationWindows.length > 20) operationWindows.shift()
379
401
  inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
380
402
  entry.lastAt = operation.time || entry.lastAt
381
403
  watchdogState.operations.set(target, entry)
@@ -383,6 +405,9 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
383
405
  }
384
406
  if (operation.phase !== 'settled') return
385
407
  operationWindowUntil = Date.now() + 4000
408
+ for (let i = operationWindows.length - 1; i >= 0; i -= 1) {
409
+ if (operationWindows[i].settledAt === null) { operationWindows[i].settledAt = Date.now(); break }
410
+ }
386
411
  const weight = operationWeight(operation)
387
412
  if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
388
413
  entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
@@ -408,6 +433,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
408
433
  at: new Date().toISOString(),
409
434
  release: 'restart',
410
435
  evidence: `本次运行内热操作计数 ${entry.count} > 5(安装/启用/热切换)`,
436
+ remediation: remediationFor('hot-ops', { count: entry.count }),
411
437
  })
412
438
  appendIncident({ kind: 'quarantine', target, level: 'L2', reason: 'hot-ops', detail: `热操作 ${entry.count} 次 > 5,自动关闭` })
413
439
  persist(true)
@@ -468,7 +494,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
468
494
  const unique = [...new Set(targets)].filter((target) => target && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target))
469
495
  const disabled = []
470
496
  for (const target of unique) {
471
- watchdogState.quarantine.set(target, { reason, level: 'crash', at: new Date().toISOString(), release: 'manual', evidence: reason })
497
+ watchdogState.quarantine.set(target, { reason, level: 'crash', at: new Date().toISOString(), release: 'manual', evidence: reason, remediation: remediationFor(reason) })
472
498
  if (await disableTarget(target, reason)) disabled.push(target)
473
499
  await new Promise((resolve) => setTimeout(resolve, 300))
474
500
  }
@@ -478,7 +504,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
478
504
  async function enforceCrashPlan(plan) {
479
505
  if (!plan || !plan.target || watchdogState.crashFallback !== 'enforce') return
480
506
  try {
481
- watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason })
507
+ watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason, remediation: remediationFor('crash') })
482
508
  const disabled = [plan.target].filter((target) => !EXEMPT_TARGETS.has(target))
483
509
  await disableTarget(plan.target, 'crash-' + plan.level)
484
510
  let targets = [plan.target]
@@ -562,7 +588,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
562
588
  if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
563
589
  appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,禁止该插件' })
564
590
  if (watchdogState.enforce) {
565
- watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB' })
591
+ watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB', remediation: remediationFor('budget') })
566
592
  void disableTarget(name, 'budget-over-500MB')
567
593
  writePendingBoot({ level: 'L1', reason: 'budget', disable: [name], keep: [] })
568
594
  }
@@ -652,6 +678,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
652
678
  const plan = {
653
679
  at: new Date().toISOString(),
654
680
  level,
681
+ remediation: remediationFor('crash'),
655
682
  crash: { file: crash.file, time: crash.parsed.time, phase: crash.parsed.phase, oom: crash.parsed.oom, hostExitCode: crash.parsed.hostExitCode },
656
683
  hostRunId: crash.parsed.hostRunId,
657
684
  target: attribution.picked ? attribution.picked.target : null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.4.4",
3
+ "version": "1.4.6",
4
4
  "description": "AI Prison for DSH: six governance tools wrapping the aiprison CLI (levels, demo, drill, inspect, verify, repair-tail) plus a panel for the L0–L5 matrix and the audit-chain state. The CLI ships bundled for Windows, macOS and Linux; every capability-removal backend stays simulated.",
5
5
  "type": "module",
6
6
  "main": "index.js",