@twinsearth/ai-prison-dsh-plugin 1.7.3 → 1.7.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,76 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.7.6] — 2026-11-19
6
+
7
+ ### Added — crash degradation plan (crashForensics v2)
8
+
9
+ - Explicit L1–L3 plan preview in the snapshot and the Enforcement card:
10
+ current level, crashes inside the 10-minute window, the 30-minute stability
11
+ reset, the next level and which steps are active.
12
+ - **L1** isolate the attributed (or in-flight) plugin; unknown attribution
13
+ records the plan without killing anything.
14
+ - **L2** L1 + close plugins changed since the clean baseline (without a
15
+ baseline only the attributed target is closed).
16
+ - **L3** safe mode: keep the clean baseline and close every newer plugin;
17
+ without a baseline, close every non-official third-party plugin.
18
+ - Escalation raises a forced `crash-escalation` notification; 30 minutes
19
+ without a crash records `crash-reset` and returns to L0.
20
+ - Plans now record `targets`, `keep`, `applied`, `executedAt` and a
21
+ `fallback` (`observe-only` / `changed-set` / `safe-mode`).
22
+ - `pending-boot.json` never downgrades an existing plan level.
23
+ - Crash enforcement waits for `pluginManager` and the first scan runs on the
24
+ next microtask, so the initial plan can close plugins instead of seeing an
25
+ empty bundle list.
26
+
27
+ ### Added — per-plugin memory tiers in the plugin prison
28
+
29
+ ### Added — per-plugin memory tiers in the plugin prison
30
+
31
+ | Occupancy | Action |
32
+ |---|---|
33
+ | ≥ 300 MB | warning incident (`plugin-memory` warn) |
34
+ | ≥ 500 MB | throttle: add-memory plugin operations are denied (target growth ≤ 1 MB/s) |
35
+ | ≥ 1000 MB | force close (quarantine + pending-boot) |
36
+ | ≥ 2000 MB | force uninstall via `pluginManager.removeBundle` (fallback: force close) |
37
+ | ≥ 3000 MB | close every third-party plugin (official/installation plugins excluded) |
38
+
39
+ - The panel Enforcement Top5 table gains a **memory tier** column with the current
40
+ occupancy; the incident list and remediation text explain each tier.
41
+ - Occupancy uses the measured module-load budget plus child RSS when available,
42
+ falling back to the operation estimate. Actions only run in enforce mode;
43
+ observe mode records tier changes.
44
+ - Tiers are recomputed after each heap sample; escalation is one-way per run
45
+ (a lower reading does not release a closed/uninstalled plugin).
46
+
47
+ ## [1.7.5] — 2026-11-19
48
+ ## [1.7.5] — 2026-11-19
49
+
50
+ ### Changed
51
+
52
+ - Memory watch waterline is now percentage-banded instead of level-text:
53
+ **≤30% relaxed (green), 31–70% normal (blue), 71–95% warning (yellow),
54
+ ≥96% danger (red)**. The card shows the band label with the current percent
55
+ and the progress bar uses the band color; the internal waterline level still
56
+ drives enforcement/rollback logic and is unchanged.
57
+
58
+ ## [1.7.4] — 2026-11-19
59
+ ## [1.7.4] — 2026-11-19
60
+
61
+ ### Changed
62
+
63
+ - Enforcement card: the Top5 action button now reads **立即缉拿 / Arrest now**
64
+ (previously 立即关闭 / Close now), and its confirmation prompt uses the same
65
+ wording. The underlying action is unchanged (close the plugin); only the
66
+ AI-Prison-themed label changed.
67
+ - Enabling a quarantined plugin from the UI is immediately closed again and raises
68
+ a tray notification: **请到 AI 监狱释放该插件!再开启。** The reminder is forced
69
+ even when general notifications are off (rate limited per kind).
70
+ - Header version pill shows the **plugin version** (`AI Prison vX.Y.Z`) instead of
71
+ the bundled aiprison CLI version; the CLI version stays in the footer. Before,
72
+ the pill always read `aiprison 1.0.9` regardless of plugin releases.
73
+
74
+ ## [1.7.3] — 2026-11-19
5
75
  ## [1.7.3] — 2026-11-19
6
76
 
7
77
  ### Added
package/client.js CHANGED
@@ -17,6 +17,7 @@ window.__ModuleLoader__.load({
17
17
  const DICTS = {
18
18
  en: {
19
19
  'panel.label': 'AI Prison',
20
+ 'panel.version': 'AI Prison v{version}',
20
21
  'page.title': 'AI Prison',
21
22
  'page.subtitle': 'Graduated capability deprivation for agents. Every backend is simulated.',
22
23
  'matrix.title': 'L0–L5 grading matrix',
@@ -63,7 +64,7 @@ window.__ModuleLoader__.load({
63
64
  'watchdog.noQuarantine': 'No quarantined plugins.',
64
65
  'watchdog.release': 'Release',
65
66
  'watchdog.topFive': 'Top {n} by estimated heap',
66
- 'watchdog.close': 'Close now',
67
+ 'watchdog.close': 'Arrest now',
67
68
  'watchdog.plans': 'Crash plans',
68
69
  'watchdog.baseline': 'Clean baseline: {at}',
69
70
  'watchdog.tamper': 'Profile watch: {n} critical file(s) · policy {policy} · last check {at}',
@@ -80,6 +81,9 @@ window.__ModuleLoader__.load({
80
81
  'watchdog.waterline': 'Waterline',
81
82
  'watchdog.thresholds': 'Warn / pause / block',
82
83
  'waterline.ok': 'OK',
84
+ 'waterline.easy': 'Relaxed',
85
+ 'waterline.normal': 'Normal',
86
+ 'waterline.danger': 'Danger',
83
87
  'waterline.warn': 'Warning',
84
88
  'waterline.pause': 'Paused',
85
89
  'waterline.block': 'Blocked',
@@ -89,6 +93,24 @@ window.__ModuleLoader__.load({
89
93
  'prison.estimate': 'Est.',
90
94
  'prison.plugin': 'Plugin',
91
95
  'prison.rss': 'Child RSS',
96
+ 'watchdog.memoryTier': 'Memory tier',
97
+ 'crashPlan.title': 'Crash degradation plan',
98
+ 'crashPlan.level': 'Level {level}',
99
+ 'crashPlan.window': '{n} crash(es) in {minutes} min',
100
+ 'crashPlan.next': 'next {level}',
101
+ 'crashPlan.max': 'at the highest level',
102
+ 'crashPlan.step.isolate-target': 'L1 isolate the attributed or in-flight plugin',
103
+ 'crashPlan.step.revert-changed': 'L2 also close plugins changed since the clean baseline',
104
+ 'crashPlan.step.safe-mode': 'L3 safe mode: keep the clean baseline, close newer plugins',
105
+ 'crashPlan.last': 'last plan {at} · {target} · {applied}',
106
+ 'crashPlan.applied': 'applied',
107
+ 'crashPlan.notApplied': 'not applied',
108
+ 'memoryTier.ok': 'Normal',
109
+ 'memoryTier.warn': 'Warning',
110
+ 'memoryTier.throttle': 'Throttled',
111
+ 'memoryTier.close': 'Closed',
112
+ 'memoryTier.uninstall': 'Uninstalled',
113
+ 'memoryTier.all-third-party': 'All third-party',
92
114
  'prison.incidents': 'Recent incidents',
93
115
  'prison.empty': 'No quarantined plugins.',
94
116
  'prison.noestimates': 'No plugin operations observed yet.',
@@ -97,6 +119,7 @@ window.__ModuleLoader__.load({
97
119
  },
98
120
  zh: {
99
121
  'panel.label': 'AI Prison',
122
+ 'panel.version': 'AI Prison v{version}',
100
123
  'page.title': 'AI Prison · AI 监狱',
101
124
  'page.subtitle': '面向 AI Agent 的分级能力剥夺与行为矫正;所有后端均为内存模拟。',
102
125
  'matrix.title': 'L0–L5 分级矩阵',
@@ -143,7 +166,7 @@ window.__ModuleLoader__.load({
143
166
  'watchdog.noQuarantine': '没有被隔离的插件。',
144
167
  'watchdog.release': '假释',
145
168
  'watchdog.topFive': '按估算内存排序的前 {n} 个插件',
146
- 'watchdog.close': '立即关闭',
169
+ 'watchdog.close': '立即缉拿',
147
170
  'watchdog.plans': '崩溃降级计划',
148
171
  'watchdog.baseline': '干净基线:{at}',
149
172
  'watchdog.tamper': '配置监控:{n} 个关键文件 · 策略 {policy} · 最近检查 {at}',
@@ -160,6 +183,9 @@ window.__ModuleLoader__.load({
160
183
  'watchdog.waterline': '水位',
161
184
  'watchdog.thresholds': '提醒 / 暂停 / 禁止',
162
185
  'waterline.ok': '正常',
186
+ 'waterline.easy': '轻松',
187
+ 'waterline.normal': '正常',
188
+ 'waterline.danger': '危险',
163
189
  'waterline.warn': '警告',
164
190
  'waterline.pause': '暂停',
165
191
  'waterline.block': '禁止',
@@ -169,6 +195,24 @@ window.__ModuleLoader__.load({
169
195
  'prison.estimate': '估算',
170
196
  'prison.plugin': '插件',
171
197
  'prison.rss': '子进程 RSS',
198
+ 'watchdog.memoryTier': '内存档位',
199
+ 'crashPlan.title': '崩溃降级计划',
200
+ 'crashPlan.level': '当前 {level}',
201
+ 'crashPlan.window': '{minutes} 分钟窗口内 {n} 次崩溃',
202
+ 'crashPlan.next': '下一档 {level}',
203
+ 'crashPlan.max': '已到最高档',
204
+ 'crashPlan.step.isolate-target': 'L1 隔离崩溃归因(或崩溃时在途)的插件',
205
+ 'crashPlan.step.revert-changed': 'L2 同时关闭干净基线之后变更的插件',
206
+ 'crashPlan.step.safe-mode': 'L3 安全模式:保留干净基线,关闭所有新增插件',
207
+ 'crashPlan.last': '最近计划 {at} · {target} · {applied}',
208
+ 'crashPlan.applied': '已执行',
209
+ 'crashPlan.notApplied': '未执行',
210
+ 'memoryTier.ok': '正常',
211
+ 'memoryTier.warn': '警告',
212
+ 'memoryTier.throttle': '节流',
213
+ 'memoryTier.close': '关闭',
214
+ 'memoryTier.uninstall': '卸载',
215
+ 'memoryTier.all-third-party': '全部第三方',
172
216
  'prison.incidents': '最近事件',
173
217
  'prison.empty': '没有被隔离的插件。',
174
218
  'prison.noestimates': '还没有观察到插件操作。',
@@ -303,8 +347,12 @@ window.__ModuleLoader__.load({
303
347
  )
304
348
  }
305
349
 
350
+ const MEMORY_TIER_KEYS = { ok: 'memoryTier.ok', warn: 'memoryTier.warn', throttle: 'memoryTier.throttle', close: 'memoryTier.close', uninstall: 'memoryTier.uninstall', 'all-third-party': 'memoryTier.all-third-party' }
351
+ const CRASH_STEP_KEYS = { 'isolate-target': 'crashPlan.step.isolate-target', 'revert-changed': 'crashPlan.step.revert-changed', 'safe-mode': 'crashPlan.step.safe-mode' }
352
+
306
353
  function Pill({ tone, text }) {
307
- const color = tone === 'ok' ? C.ok.color : tone === 'error' ? C.error.color : C.muted.color
354
+ const palette = { ok: C.ok.color, info: '#2563eb', warn: '#b45309', error: C.error.color }
355
+ const color = palette[tone] || C.muted.color
308
356
  return h('span', { style: C.pill }, h('span', { style: { ...C.dot, background: color } }), h('span', null, text))
309
357
  }
310
358
 
@@ -354,12 +402,6 @@ window.__ModuleLoader__.load({
354
402
  body: JSON.stringify({ action, target }),
355
403
  }).then((response) => response.json())
356
404
  }
357
- function waterlineText(level) {
358
- if (level === 'block') return t('waterline.block')
359
- if (level === 'pause') return t('waterline.pause')
360
- if (level === 'warn') return t('waterline.warn')
361
- return t('waterline.ok')
362
- }
363
405
 
364
406
  function MemoryCard({ watchdog }) {
365
407
  if (!watchdog) {
@@ -373,7 +415,17 @@ window.__ModuleLoader__.load({
373
415
  const heap = watchdog.heap || {}
374
416
  const thresholds = watchdog.thresholds || {}
375
417
  const ratio = heap.heapLimit > 0 ? Math.min(1, heap.heapUsed / heap.heapLimit) : 0
376
- const tone = watchdog.waterline === 'ok' ? C.ok.color : watchdog.waterline === 'warn' ? '#b45309' : C.error.color
418
+ const percent = Math.floor(ratio * 100)
419
+ // 水位色带:≤30% 轻松(绿)、31–70% 正常(蓝)、71–95% 警告(黄)、≥96% 危险(红)
420
+ const band =
421
+ percent <= 30
422
+ ? { tone: 'ok', key: 'waterline.easy', color: C.ok.color }
423
+ : percent <= 70
424
+ ? { tone: 'info', key: 'waterline.normal', color: '#2563eb' }
425
+ : percent <= 95
426
+ ? { tone: 'warn', key: 'waterline.warn', color: '#b45309' }
427
+ : { tone: 'error', key: 'waterline.danger', color: C.error.color }
428
+ const tone = band.color
377
429
  return h(
378
430
  'section',
379
431
  { style: C.card },
@@ -382,7 +434,7 @@ window.__ModuleLoader__.load({
382
434
  { style: C.cardHead },
383
435
  t('watchdog.title'),
384
436
  h('span', { style: { ...C.chip, marginLeft: 8 } }, (watchdog.enforce ? t('watchdog.modeEnforce') : t('watchdog.mode'))),
385
- h(Pill, { tone: watchdog.waterline === 'ok' ? 'ok' : 'error', text: `${t('watchdog.waterline')}: ${waterlineText(watchdog.waterline)}` }),
437
+ h(Pill, { tone: band.tone, text: `${t('watchdog.waterline')}: ${t(band.key)} · ${percent}%` }),
386
438
  ),
387
439
  h(
388
440
  'div',
@@ -393,7 +445,7 @@ window.__ModuleLoader__.load({
393
445
  'div',
394
446
  { style: C.grid },
395
447
  h('div', { style: C.key }, t('watchdog.heap')),
396
- h('div', { style: C.mono }, `${Math.round(heap.heapUsed / 1048576)} MB / ${Math.round(heap.heapLimit / 1048576)} MB(${Math.round(ratio * 100)}%)`),
448
+ h('div', { style: C.mono }, `${Math.round(heap.heapUsed / 1048576)} MB / ${Math.round(heap.heapLimit / 1048576)} MB(${percent}%)`),
397
449
  h('div', { style: C.key }, t('watchdog.rss')),
398
450
  h('div', { style: C.mono }, `${Math.round((heap.rss || 0) / 1048576)} MB`),
399
451
  h('div', { style: C.key }, t('watchdog.thresholds')),
@@ -488,6 +540,7 @@ window.__ModuleLoader__.load({
488
540
  const grace = Number.isFinite(watchdog.graceUntil) && Date.now() < watchdog.graceUntil
489
541
  const quarantine = Array.isArray(watchdog.quarantine) ? watchdog.quarantine : []
490
542
  const topFive = Array.isArray(watchdog.topFive) ? watchdog.topFive : []
543
+ const crashPlan = watchdog.crashPlan || null
491
544
  const plans = Array.isArray(watchdog.plans) ? watchdog.plans.slice(-2).reverse() : []
492
545
  const button = { cursor: 'pointer', padding: '3px 9px', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l1, rgba(0,0,0,.18))', background: 'transparent', fontSize: 12 }
493
546
  return h('section', { style: C.card },
@@ -518,16 +571,37 @@ window.__ModuleLoader__.load({
518
571
  h('th', { style: C.th }, t('prison.plugin')),
519
572
  h('th', { style: C.th }, t('prison.estimate')),
520
573
  h('th', { style: C.th }, t('prison.rss')),
574
+ h('th', { style: C.th }, t('watchdog.memoryTier')),
521
575
  h('th', { style: C.th }, ''),
522
576
  )),
523
577
  h('tbody', null, topFive.map((row) => h('tr', { key: row.target },
524
578
  h('td', { style: { ...C.td, ...C.mono, fontSize: 11.5, wordBreak: 'break-all' } }, row.target),
525
579
  h('td', { style: C.td }, row.estimateMB + ' MB'),
526
580
  h('td', { style: C.td }, (row.rssMB || 0) + ' MB'),
527
- h('td', { style: C.td }, h('button', { style: button, onClick: () => act('close', row.target, '立即关闭 ' + row.target + ' ?') }, t('watchdog.close'))),
581
+ h('td', { style: C.td }, t(MEMORY_TIER_KEYS[row.memoryTier] || MEMORY_TIER_KEYS.ok) + (row.memoryMB != null ? ' · ' + row.memoryMB + ' MB' : '')),
582
+ h('td', { style: C.td }, h('button', { style: button, onClick: () => act('close', row.target, '立即缉拿 ' + row.target + ' ?') }, t('watchdog.close'))),
528
583
  ))),
529
584
  ),
530
585
  ),
586
+ crashPlan ? h('div', { style: { marginTop: 12, paddingTop: 10, borderTop: '1px dashed var(--dsw-alias-border-l1, rgba(0,0,0,.12))' } },
587
+ h('div', { style: { ...C.key, marginBottom: 4 } }, t('crashPlan.title')),
588
+ h('div', { style: { fontSize: 12.5, marginBottom: 4 } },
589
+ t('crashPlan.level', { level: crashPlan.level })
590
+ + ' · ' + t('crashPlan.window', { n: crashPlan.crashes, minutes: Math.round((crashPlan.windowMs || 0) / 60000) })
591
+ + (crashPlan.nextLevel ? ' · ' + t('crashPlan.next', { level: crashPlan.nextLevel }) : ' · ' + t('crashPlan.max'))),
592
+ h('div', { style: { ...C.muted, fontSize: 11.5, lineHeight: 1.6 } },
593
+ ['isolate-target', 'revert-changed', 'safe-mode'].map((step) => {
594
+ const active = Array.isArray(crashPlan.steps) && crashPlan.steps.indexOf(step) >= 0
595
+ return h('div', { key: step, style: { opacity: active ? 1 : 0.45 } }, (active ? '▸ ' : '· ') + t(CRASH_STEP_KEYS[step]))
596
+ })),
597
+ crashPlan.lastPlan
598
+ ? h('div', { style: { ...C.mono, fontSize: 11, marginTop: 4 } }, t('crashPlan.last', {
599
+ at: crashPlan.lastPlan.at || '—',
600
+ target: crashPlan.lastPlan.target || crashPlan.lastPlan.fallback || 'unattributed',
601
+ applied: crashPlan.lastPlan.applied ? t('crashPlan.applied') : t('crashPlan.notApplied'),
602
+ }))
603
+ : null,
604
+ ) : null,
531
605
  plans.length === 0 ? null : h('div', { style: { marginTop: 10 } },
532
606
  h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.plans')),
533
607
  plans.map((plan) => h('div', { key: plan.at, style: { ...C.mono, fontSize: 11.5, wordBreak: 'break-word' } },
@@ -719,6 +793,7 @@ window.__ModuleLoader__.load({
719
793
 
720
794
  const cli = data?.cli
721
795
  const cliText = cli && cli.found ? t('cli.found', { version: cli.version || '?' }) : t('cli.missing')
796
+ const pillText = data && data.pluginVersion ? t('panel.version', { version: data.pluginVersion }) : cliText
722
797
  const timeText = updated ? updated.toLocaleTimeString() : ''
723
798
 
724
799
  return h(
@@ -729,7 +804,7 @@ window.__ModuleLoader__.load({
729
804
  { style: C.header },
730
805
  h('span', { style: { display: 'inline-flex' } }, h(PrisonIcon, { size: 26, active: true })),
731
806
  h('div', { style: { minWidth: 0 } }, h('h1', { style: C.title }, t('page.title')), h('p', { style: C.sub }, t('page.subtitle'))),
732
- h(Pill, { tone: cli && cli.found ? 'ok' : 'error', text: cliText }),
807
+ h(Pill, { tone: cli && cli.found ? 'ok' : 'error', text: pillText }),
733
808
  h('button', { type: 'button', style: C.btn, onClick: load, disabled: loading }, loading ? t('action.loading') : t('action.refresh')),
734
809
  ),
735
810
  error
@@ -756,7 +831,7 @@ window.__ModuleLoader__.load({
756
831
  'p',
757
832
  { style: { ...C.muted, fontSize: 12, margin: '2px 0 0', display: 'flex', gap: 12, flexWrap: 'wrap' } },
758
833
  h('span', null, t('meta.readonly')),
759
- cli && cli.path ? h('span', { style: C.mono }, `${t('cli.source')}: ${cli.source} · ${cli.path}`) : null,
834
+ cli && cli.path ? h('span', { style: C.mono }, `${t('cli.source')}: ${cli.source} · ${cli.path} · aiprison ${cli.version || '?'}`) : null,
760
835
  timeText ? h('span', null, t('meta.updated', { time: timeText })) : null,
761
836
  ),
762
837
  )
package/lib/notifier.js CHANGED
@@ -11,6 +11,8 @@ const KIND_LABELS = {
11
11
  quarantine: '插件隔离',
12
12
  tamper: '配置篡改',
13
13
  'crash-enforced': '崩溃隔离',
14
+ 'crash-escalation': '崩溃升级',
15
+ 'quarantine-reminder': '插件仍在隔离',
14
16
  budget: '内存超限',
15
17
  }
16
18
 
@@ -17,6 +17,19 @@ const REMEDIATION = {
17
17
  ],
18
18
  release: '重启 DSH 会自动释放;也可以在面板"插件监狱"里点"假释"手动释放。',
19
19
  },
20
+ memory: {
21
+ title: '插件内存档位超限',
22
+ why: '单个插件的实测/估算内存达到插件监狱阈值:300 MB 警告、500 MB 限制增内存操作、1000 MB 强制关闭、2000 MB 强制卸载、3000 MB 关闭全部第三方插件。',
23
+ impact: '达到对应档位后 watchdog 会警告、限流、关闭、卸载或批量关闭第三方插件(官方/内置除外);被隔离的插件需要手动假释。',
24
+ steps: [
25
+ '在面板“执行状态 → 内存档位”里确认占用来源(模块加载 / 子进程 RSS);',
26
+ '达到 500 MB 时该插件的安装/启用等增内存操作会被拒绝(增长目标 ≤1 MB/s);',
27
+ '达到 1000 MB/2000 MB 时插件会被强制关闭/卸载,先排查是否版本缺陷;',
28
+ '确需恢复使用:在“插件监狱”点假释,并先升级到修复版本。',
29
+ ],
30
+ release: '手动释放(面板“假释”);卸载档位需重新安装插件。',
31
+ },
32
+
20
33
  crash: {
21
34
  title: '该插件被归因为崩溃来源',
22
35
  why: 'DSH 宿主进程崩溃(如爆内存),崩溃日志里的 hostRunId 与本插件最后一次安装/启用记录匹配。',
@@ -24,7 +37,7 @@ const REMEDIATION = {
24
37
  steps: [
25
38
  '先重启 DSH,确认在没有该插件时环境稳定。',
26
39
  '检查插件版本是否有修复(升级到最新版),或查看其 README 的已知崩溃问题。',
27
- '确需继续使用时,在面板"插件监狱"点"假释",一次只放行一个插件并观察内存。',
40
+ '确需继续使用时,先在面板"插件监狱"点"假释",再开启;直接开启会被立即缉拿并弹窗提醒。',
28
41
  ],
29
42
  release: '仅手动释放(面板"假释");重启不会自动解除,防止崩溃循环。',
30
43
  },
package/lib/status.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readdirSync } from 'node:fs'
2
2
  import { describeCli, resolveCli, resolveDataDir, runCli } from './cli.js'
3
3
  import { parseLevels } from './levels.js'
4
4
  import { listSegments } from './ledger.js'
5
+ import { PLUGIN_VERSION } from './version.js'
5
6
 
6
7
  const MAX_DETAIL = 600
7
8
 
@@ -70,6 +71,7 @@ export async function buildStatus({ config = {}, cwd, timeoutMs = 120_000, root
70
71
  generatedAt: new Date().toISOString(),
71
72
  cwd: cwd || null,
72
73
  platform: `${process.platform}-${process.arch}`,
74
+ pluginVersion: PLUGIN_VERSION,
73
75
  cli,
74
76
  levels,
75
77
  ledger,
@@ -79,7 +81,7 @@ export async function buildStatus({ config = {}, cwd, timeoutMs = 120_000, root
79
81
  /** Bounded human summary used by tool results. */
80
82
  export function statusSummary(status) {
81
83
  const cliLine = status.cli.found
82
- ? `aiprison ${status.cli.version || '?'}(${status.cli.source}: ${status.cli.path})`
84
+ ? `AI Prison v${status.pluginVersion || '?'} · aiprison ${status.cli.version || '?'}(${status.cli.source}: ${status.cli.path})`
83
85
  : `CLI 不可用:${status.cli.error || 'unknown'}`
84
86
  const ledgerLine = status.ledger.exists
85
87
  ? `账本 ${status.ledger.dir}:${status.ledger.integrity === 'ok' ? `INTEGRITY OK(${status.ledger.records ?? '?'} 条记录)` : `校验失败(${status.ledger.detail})`}`
package/lib/tools.js CHANGED
@@ -241,6 +241,7 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
241
241
  heap6g: snapshot.heap6g,
242
242
  heap6gRequest: snapshot.heap6gRequest,
243
243
  pendingBoot: snapshot.pendingBoot,
244
+ memoryTiers: snapshot.memoryTiers,
244
245
  rss: snapshot.rss,
245
246
  rssAt: snapshot.rssAt,
246
247
  rssError: snapshot.rssError,
package/lib/version.js ADDED
@@ -0,0 +1,17 @@
1
+ import fs from 'node:fs'
2
+ import { fileURLToPath } from 'node:url'
3
+
4
+ /**
5
+ * Version of the installed plugin package.
6
+ *
7
+ * The panel must show the bundle version (which follows releases), not the
8
+ * bundled aiprison CLI version (which is the Go tool's own 1.0.x line).
9
+ */
10
+ export const PLUGIN_VERSION = (() => {
11
+ try {
12
+ const manifest = fileURLToPath(new URL('../package.json', import.meta.url))
13
+ return JSON.parse(fs.readFileSync(manifest, 'utf8')).version || null
14
+ } catch {
15
+ return null
16
+ }
17
+ })()
@@ -13,6 +13,9 @@ export const CRASH_HEAD_BYTES = 256 * 1024
13
13
  export const BASELINE_DELAY_MS = 60_000
14
14
  export const PAUSE_GRACE_MS = 10 * 60_000
15
15
  export const CRASH_WINDOW_MS = 10 * 60_000
16
+
17
+ /** Stable time after which crash counters no longer escalate (30 minutes). */
18
+ export const CRASH_RESET_MS = 30 * 60_000
16
19
  export const MAX_JOURNAL_RECORDS = 4000
17
20
 
18
21
  /** Bundles the watchdog must never quarantine or disable. */
@@ -2,46 +2,149 @@ import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { attributeCrash, diffBaseline, escalationLevel, parseCrashLog } from './watchdog-policy.js'
4
4
  import { remediationFor } from './remediation.js'
5
- import { CRASH_HEAD_BYTES, CRASH_WINDOW_MS, readHead, readJournalRecords } from './watchdog-core.js'
5
+ import { CRASH_HEAD_BYTES, CRASH_RESET_MS, CRASH_WINDOW_MS, readHead, readJournalRecords } from './watchdog-core.js'
6
+
7
+ const LEVEL_RANK = { L0: 0, L1: 1, L2: 2, L3: 3 }
8
+
9
+ /** Ordered degradation steps for one crash-plan level. */
10
+ export function crashPlanSteps(level) {
11
+ if (level === 'L3') return ['isolate-target', 'revert-changed', 'safe-mode']
12
+ if (level === 'L2') return ['isolate-target', 'revert-changed']
13
+ if (level === 'L1') return ['isolate-target']
14
+ return []
15
+ }
6
16
 
7
17
  /**
8
18
  * Crash-log ingestion and graded crash plans.
9
19
  *
10
20
  * Every new `crash-*-host.log` is parsed, attributed to the last changed plugin
11
- * of that host run and turned into an L1-L3 plan. In enforce mode the plan is
12
- * executed through the enforcement module (close/quarantine + pending-boot).
21
+ * of that host run and turned into an L1-L3 degradation plan:
22
+ * L1: isolate the attributed (or in-flight) plugin only.
23
+ * L2: L1 + disable plugins changed since the clean baseline.
24
+ * L3: L2 + safe mode: keep the clean baseline, close every newer plugin.
25
+ * Enforce mode applies the plan through the enforcement module
26
+ * (close/quarantine + pending-boot); observe mode records it.
27
+ * Crash counters reset after CRASH_RESET_MS of stability.
13
28
  */
14
29
  export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptions, appendIncident, persist, enforcement }) {
30
+ function baselineNames() {
31
+ return watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : []
32
+ }
33
+
34
+ async function rowsNow() {
35
+ const manager = refs.manager
36
+ if (!manager || typeof manager.listBundles !== 'function') return []
37
+ try {
38
+ const rows = await manager.listBundles()
39
+ return Array.isArray(rows) ? rows : []
40
+ } catch {
41
+ return []
42
+ }
43
+ }
44
+
45
+ /** Which plugin set a plan should close, for this level and attribution. */
46
+ async function planTargets(level, target) {
47
+ const rows = await rowsNow()
48
+ const keep = baselineNames()
49
+ const candidates = []
50
+ if (target) candidates.push(target)
51
+ if (level === 'L2') {
52
+ if (!watchdogState.baseline) return target ? [target].filter((name) => !exemptions.has(name)) : []
53
+ for (const row of diffBaseline(rows, watchdogState.baseline).changed) {
54
+ if (!exemptions.has(row.name)) candidates.push(row.name)
55
+ }
56
+ }
57
+ if (level === 'L3') {
58
+ if (keep.length === 0) {
59
+ // No clean baseline to protect: close every non-official third-party
60
+ // plugin (never guess a safe set that includes unknown plugins).
61
+ for (const row of rows) {
62
+ if (!row.enabled || exemptions.has(row.name)) continue
63
+ if (row.official === true || String(row.name).startsWith('@deepseek-ai/')) continue
64
+ candidates.push(row.name)
65
+ }
66
+ return [...new Set(candidates)]
67
+ }
68
+ for (const row of rows) {
69
+ if (!row.enabled || exemptions.has(row.name) || keep.includes(row.name)) continue
70
+ candidates.push(row.name)
71
+ }
72
+ }
73
+ return [...new Set(candidates)].filter((name) => name && !exemptions.has(name))
74
+ }
75
+
76
+ async function enforceWhenReady(plan) {
77
+ for (let attempt = 0; attempt < 20; attempt += 1) {
78
+ if (refs.manager && typeof refs.manager.listBundles === 'function') {
79
+ await enforceCrashPlan(plan)
80
+ return
81
+ }
82
+ await new Promise((resolve) => setTimeout(resolve, 25))
83
+ }
84
+ watchdogState.degraded = 'crash enforcement deferred: pluginManager unavailable'
85
+ }
86
+
15
87
  async function enforceCrashPlan(plan) {
16
- if (!plan || !plan.target || watchdogState.crashFallback !== 'enforce') return
88
+ if (!watchdogState.enforce || watchdogState.crashFallback !== 'enforce') return
17
89
  try {
18
- watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason, remediation: remediationFor('crash') })
19
- const disabled = [plan.target].filter((target) => !exemptions.has(target))
20
- await enforcement.disableTarget(plan.target, 'crash-' + plan.level)
21
- let targets = [plan.target]
22
- if (plan.level === 'L2' || plan.level === 'L3') {
23
- const manager = refs.manager
24
- const rows = manager && typeof manager.listBundles === 'function' ? await manager.listBundles() : []
25
- const baselineNames = watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : []
26
- targets = plan.level === 'L3'
27
- ? rows.filter((row) => row.enabled && !exemptions.has(row.name) && !baselineNames.includes(row.name)).map((row) => row.name)
28
- : diffBaseline(rows, watchdogState.baseline).changed.map((row) => row.name).concat(plan.target)
29
- disabled.push(...(await enforcement.disableMany(targets, 'crash-' + plan.level)))
90
+ const targets = await planTargets(plan.level, plan.target)
91
+ const keep = baselineNames()
92
+ plan.targets = targets
93
+ plan.keep = keep
94
+ plan.applied = false
95
+ if (plan.target && !exemptions.has(plan.target)) {
96
+ watchdogState.quarantine.set(plan.target, {
97
+ reason: 'crash',
98
+ level: plan.level,
99
+ at: new Date().toISOString(),
100
+ release: 'manual',
101
+ evidence: plan.reason,
102
+ remediation: remediationFor('crash'),
103
+ })
30
104
  }
31
- enforcement.writePendingBoot({
105
+ let disabled = []
106
+ if (plan.target && !exemptions.has(plan.target)) {
107
+ await enforcement.disableTarget(plan.target, 'crash-' + plan.level)
108
+ disabled.push(plan.target)
109
+ }
110
+ const rest = targets.filter((target) => target !== plan.target)
111
+ if (rest.length > 0) disabled.push(...(await enforcement.disableMany(rest, 'crash-' + plan.level)))
112
+ plan.applied = disabled.length > 0
113
+ if (targets.length > 0) {
114
+ enforcement.writePendingBoot({
115
+ level: plan.level,
116
+ reason: 'crash',
117
+ attribution: plan.target || null,
118
+ disable: [...new Set(targets)],
119
+ keep,
120
+ })
121
+ }
122
+ plan.executedAt = new Date().toISOString()
123
+ appendIncident({
124
+ kind: 'crash-enforced',
32
125
  level: plan.level,
33
- reason: 'crash',
34
- attribution: plan.target,
35
- disable: [...new Set(targets)],
36
- keep: watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : [],
126
+ target: plan.target || null,
127
+ detail: targets.length > 0
128
+ ? '已按 ' + plan.level + ' 隔离 ' + disabled.length + ' 个目标(pending-boot.json 供外部包装器下次启动前使用)'
129
+ : '降级计划 ' + plan.level + ':无归因且无可隔离目标,仅记录',
37
130
  })
38
- appendIncident({ kind: 'crash-enforced', level: plan.level, target: plan.target, detail: '已按 ' + plan.level + ' 隔离 ' + disabled.length + ' 个目标(pending-boot.json 供外部包装器下次启动前使用)' })
39
131
  persist(true)
40
132
  } catch (error) {
41
133
  watchdogState.degraded = 'crash enforce: ' + String((error && error.message) || error)
42
134
  }
43
135
  }
44
136
 
137
+ /** Counters older than the reset window no longer escalate. */
138
+ function resetIfStable(now) {
139
+ const esc = watchdogState.escalation
140
+ if (!esc || !esc.lastCrashAt) return
141
+ if (now - esc.lastCrashAt > CRASH_RESET_MS) {
142
+ esc.crashes = []
143
+ esc.level = 'L0'
144
+ appendIncident({ kind: 'crash-reset', detail: '连续 ' + Math.round(CRASH_RESET_MS / 60000) + ' 分钟无崩溃,崩溃降级等级已重置为 L0' })
145
+ }
146
+ }
147
+
45
148
  function readCrashLogs() {
46
149
  let entries
47
150
  try {
@@ -70,16 +173,21 @@ export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptio
70
173
  if (crashes.length === 0) return
71
174
  const records = readJournalRecords(journalDir)
72
175
  for (const crash of crashes) {
73
- watchdogState.escalation.crashes.push(Date.now())
74
- const recent = watchdogState.escalation.crashes.filter((at) => Date.now() - at <= CRASH_WINDOW_MS)
75
- watchdogState.escalation.crashes = recent
76
- const level = escalationLevel(recent.length)
176
+ const now = Date.now()
177
+ resetIfStable(now)
178
+ watchdogState.escalation.crashes.push(now)
179
+ watchdogState.escalation.crashes = watchdogState.escalation.crashes.filter((at) => now - at <= CRASH_WINDOW_MS)
180
+ watchdogState.escalation.lastCrashAt = now
181
+ const previousLevel = watchdogState.escalation.level || 'L0'
182
+ watchdogState.escalation.previousLevel = previousLevel
183
+ const level = escalationLevel(watchdogState.escalation.crashes.length)
77
184
  watchdogState.escalation.level = level
78
185
  const attribution = attributeCrash(records, crash.parsed)
79
186
  watchdogState.hostRunId = crash.parsed.hostRunId || null
80
187
  const plan = {
81
188
  at: new Date().toISOString(),
82
189
  level,
190
+ steps: crashPlanSteps(level),
83
191
  remediation: remediationFor('crash'),
84
192
  crash: { file: crash.file, time: crash.parsed.time, phase: crash.parsed.phase, oom: crash.parsed.oom, hostExitCode: crash.parsed.hostExitCode },
85
193
  hostRunId: crash.parsed.hostRunId,
@@ -87,6 +195,9 @@ export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptio
87
195
  inFlight: attribution.picked ? Boolean(attribution.picked.inFlight) : false,
88
196
  evidence: attribution.candidates,
89
197
  reason: attribution.reason,
198
+ fallback: attribution.picked ? null : level === 'L1' ? 'observe-only' : level === 'L2' ? 'changed-set' : 'safe-mode',
199
+ targets: [],
200
+ keep: [],
90
201
  applied: false,
91
202
  }
92
203
  watchdogState.plans.push(plan)
@@ -102,10 +213,18 @@ export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptio
102
213
  target: plan.target,
103
214
  inFlight: plan.inFlight,
104
215
  detail: plan.target
105
- ? `崩溃归因:${plan.target}${plan.inFlight ? '(崩溃时操作仍在途)' : ''};${watchdogState.enforce ? 'enforce' : 'dry-run'}`
106
- : '崩溃归因失败:本 run 无安装/启用记录,不自动关闭',
216
+ ? '崩溃归因:' + plan.target + (plan.inFlight ? '(崩溃时操作仍在途)' : '') + ';' + (watchdogState.enforce ? 'enforce' : 'dry-run')
217
+ : '崩溃归因失败:本 run 无安装/启用记录' + (level === 'L1' ? ',本档仅记录' : ',降级改为' + (level === 'L2' ? '变更集隔离' : '安全模式')),
107
218
  })
108
- if (watchdogState.enforce && watchdogState.crashFallback === 'enforce') void enforceCrashPlan(plan)
219
+ if ((LEVEL_RANK[level] || 0) > (LEVEL_RANK[previousLevel] || 0)) {
220
+ appendIncident({
221
+ kind: 'crash-escalation',
222
+ level,
223
+ notify: true,
224
+ detail: '崩溃降级升级:' + previousLevel + ' → ' + level + '(' + watchdogState.escalation.crashes.length + ' 次崩溃 / ' + Math.round(CRASH_WINDOW_MS / 60000) + ' 分钟窗口)',
225
+ })
226
+ }
227
+ if (watchdogState.enforce && watchdogState.crashFallback === 'enforce') void enforceWhenReady(plan)
109
228
  }
110
229
  if (newest > watchdogState.lastCrashScan) {
111
230
  watchdogState.lastCrashScan = newest
@@ -113,5 +232,5 @@ export function createCrash({ watchdogState, logsDir, journalDir, refs, exemptio
113
232
  }
114
233
  }
115
234
 
116
- return { readCrashLogs }
235
+ return { readCrashLogs, crashPlanSteps }
117
236
  }
@@ -1,6 +1,6 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
- import { attributeCrash, hotOperationTriggered, mergeEstimate, operationWeight } from './watchdog-policy.js'
3
+ import { attributeCrash, hotOperationTriggered, memoryTierFor, mergeEstimate, operationWeight } from './watchdog-policy.js'
4
4
  import { remediationFor } from './remediation.js'
5
5
  import { readJournalRecords } from './watchdog-core.js'
6
6
 
@@ -21,7 +21,16 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
21
21
 
22
22
  function writePendingBoot(payload) {
23
23
  try {
24
- fs.writeFileSync(path.join(dataDir, 'pending-boot.json'), JSON.stringify({ writtenAt: new Date().toISOString(), ...payload }, null, 2) + '\n')
24
+ const file = path.join(dataDir, 'pending-boot.json')
25
+ const rank = { L0: 0, L1: 1, L2: 2, L3: 3 }
26
+ let previous = null
27
+ try {
28
+ previous = JSON.parse(fs.readFileSync(file, 'utf8'))
29
+ } catch {
30
+ previous = null
31
+ }
32
+ if (previous && (rank[previous.level] || 0) > (rank[payload.level] || 0)) return
33
+ fs.writeFileSync(file, JSON.stringify({ writtenAt: new Date().toISOString(), ...payload }, null, 2) + '\n')
25
34
  } catch {
26
35
  // an external launcher reads this file; best effort
27
36
  }
@@ -124,6 +133,17 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
124
133
  entry.lastApplication = operation.application || null
125
134
  watchdogState.operations.set(target, entry)
126
135
  const additive = operation.stage === 'install' || (operation.stage === 'enable' && operation.enabled !== false)
136
+ if (operation.stage === 'enable' && operation.enabled !== false && watchdogState.enforce && watchdogState.quarantine.has(target)) {
137
+ const quarantined = watchdogState.quarantine.get(target)
138
+ appendIncident({
139
+ kind: 'quarantine-reminder',
140
+ target,
141
+ level: quarantined.level,
142
+ notify: true,
143
+ detail: '请到,AI监狱释放该插件!再开启。(原因:' + quarantined.reason + ';本次开启已被立即关闭)',
144
+ })
145
+ void disableTarget(target, 'quarantined-enable')
146
+ }
127
147
  if (
128
148
  watchdogState.enforce
129
149
  && additive
@@ -164,6 +184,126 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
164
184
  }
165
185
  }
166
186
 
187
+ const TIER_RANK = { ok: 0, warn: 1, throttle: 2, close: 3, uninstall: 4, 'all-third-party': 5 }
188
+ let tierRunPromise = null
189
+
190
+ /** Best available single-plugin memory estimate: measured module load + child RSS, else operation estimate. */
191
+ function measuredMemoryMB(target) {
192
+ const budget = watchdogState.budgets && watchdogState.budgets[target]
193
+ const moduleMB = budget && Number.isFinite(Number(budget.moduleLoadMB)) ? Number(budget.moduleLoadMB) : 0
194
+ const rssMB = watchdogState.rss ? (Number(watchdogState.rss[target]) || 0) / (1024 * 1024) : 0
195
+ const opMB = (watchdogState.operations.get(target) || {}).estimateMB || 0
196
+ if (moduleMB > 0 || rssMB > 0) return Math.round(moduleMB + rssMB)
197
+ return Math.round(opMB)
198
+ }
199
+
200
+ /** True only when the occupancy came from a real measurement, not an operation estimate. */
201
+ function hasMeasuredMemory(target) {
202
+ const budget = watchdogState.budgets && watchdogState.budgets[target]
203
+ const moduleMB = budget && Number.isFinite(Number(budget.moduleLoadMB)) ? Number(budget.moduleLoadMB) : 0
204
+ const rssMB = watchdogState.rss ? (Number(watchdogState.rss[target]) || 0) / (1024 * 1024) : 0
205
+ return moduleMB > 0 || rssMB > 0
206
+ }
207
+ /**
208
+ * Plugin-prison memory tiers (single-plugin occupancy):
209
+ * 300 MB warn · 500 MB throttle · 1000 MB force close ·
210
+ * 2000 MB force uninstall · 3000 MB close all third-party plugins.
211
+ * Enforce mode acts; observe mode only records the tier changes.
212
+ */
213
+ async function enforceMemoryTiers() {
214
+ if (tierRunPromise) return tierRunPromise
215
+ tierRunPromise = doEnforceMemoryTiers().finally(() => { tierRunPromise = null })
216
+ return tierRunPromise
217
+ }
218
+
219
+ async function doEnforceMemoryTiers() {
220
+ const manager = refs.manager
221
+ if (!manager || typeof manager.listBundles !== 'function') return null
222
+ let rows
223
+ try {
224
+ rows = await manager.listBundles()
225
+ } catch {
226
+ return null
227
+ }
228
+ const enabled = rows.filter((row) => row.enabled && !exemptions.has(row.name))
229
+ const summary = { checked: enabled.length, warned: [], throttled: [], closed: [], uninstalled: [], thirdParty: [] }
230
+ for (const row of enabled) {
231
+ const mb = measuredMemoryMB(row.name)
232
+ const tier = memoryTierFor(mb)
233
+ const previous = watchdogState.memoryTiers.get(row.name)
234
+ const previousRank = TIER_RANK[previous ? previous.tier : 'ok'] || 0
235
+ const rank = TIER_RANK[tier] || 0
236
+ if (tier === 'ok') {
237
+ if (previous) watchdogState.memoryTiers.delete(row.name)
238
+ continue
239
+ }
240
+ watchdogState.memoryTiers.set(row.name, { tier, mb, at: new Date().toISOString(), version: row.version || null })
241
+ if (!watchdogState.enforce) {
242
+ if (rank > previousRank) appendIncident({ kind: 'plugin-memory', level: tier, target: row.name, mb, detail: '插件内存 ' + mb + ' MB 达到 ' + tier + ' 档(observe:仅记录)' })
243
+ continue
244
+ }
245
+ if (rank <= previousRank) continue
246
+ if (tier === 'warn') {
247
+ summary.warned.push(row.name)
248
+ appendIncident({ kind: 'plugin-memory', level: 'warn', target: row.name, mb, detail: '插件内存 ' + mb + ' MB ≥ 300 MB:警告' })
249
+ continue
250
+ }
251
+ if (tier === 'throttle') {
252
+ summary.throttled.push(row.name)
253
+ appendIncident({ kind: 'plugin-memory', level: 'throttle', target: row.name, mb, detail: '插件内存 ' + mb + ' MB ≥ 500 MB:限制该插件的增内存操作(增长目标 ≤1 MB/s)' })
254
+ continue
255
+ }
256
+ // close (>=1000) / uninstall (>=2000) / all-third-party (>=3000)
257
+ watchdogState.quarantine.set(row.name, {
258
+ reason: 'memory',
259
+ level: 'L2',
260
+ at: new Date().toISOString(),
261
+ release: 'manual',
262
+ evidence: '实测/估算 ' + mb + ' MB',
263
+ remediation: remediationFor('memory'),
264
+ })
265
+ if (tier === 'uninstall' && !hasMeasuredMemory(row.name)) {
266
+ await disableTarget(row.name, 'memory-uninstall-unverified')
267
+ summary.closed.push(row.name)
268
+ appendIncident({ kind: 'plugin-memory', level: 'close', target: row.name, mb, detail: '插件内存 ' + mb + ' MB 仅来自操作估算(无实测);为避免误卸载,改为强制关闭' })
269
+ writePendingBoot({ level: 'L1', reason: 'memory', disable: [row.name], keep: [] })
270
+ continue
271
+ }
272
+ if (tier === 'uninstall') {
273
+ let removed = false
274
+ if (typeof manager.removeBundle === 'function') {
275
+ try {
276
+ const result = await manager.removeBundle(row.name)
277
+ removed = Boolean(result && result.application !== 'failed')
278
+ } catch (error) {
279
+ appendIncident({ kind: 'plugin-memory', level: 'uninstall', target: row.name, mb, detail: '强制卸载 ' + row.name + ' 失败:' + String((error && error.message) || error) + ';改为强制关闭' })
280
+ }
281
+ }
282
+ if (!removed) await disableTarget(row.name, 'memory-over-2000MB')
283
+ summary.uninstalled.push(row.name)
284
+ appendIncident({ kind: 'plugin-memory', level: 'uninstall', target: row.name, mb, detail: removed ? '插件内存 ' + mb + ' MB ≥ 2000 MB:已强制卸载' : '插件内存 ' + mb + ' MB ≥ 2000 MB:卸载失败,已强制关闭' })
285
+ writePendingBoot({ level: 'L1', reason: 'memory', disable: [row.name], keep: [] })
286
+ continue
287
+ }
288
+ await disableTarget(row.name, 'memory-over-' + tier)
289
+ summary.closed.push(row.name)
290
+ appendIncident({ kind: 'plugin-memory', level: tier, target: row.name, mb, detail: '插件内存 ' + mb + ' MB ≥ ' + (tier === 'all-third-party' ? 3000 : 1000) + ' MB:强制关闭' })
291
+ if (tier === 'all-third-party') {
292
+ for (const other of enabled) {
293
+ if (other.name === row.name || other.official === true || String(other.name).startsWith('@deepseek-ai/')) continue
294
+ if (watchdogState.quarantine.has(other.name)) continue
295
+ watchdogState.quarantine.set(other.name, { reason: 'memory', level: 'L2', at: new Date().toISOString(), release: 'manual', evidence: '同批第三方关闭(' + row.name + ' ≥3000 MB)', remediation: remediationFor('memory') })
296
+ await disableTarget(other.name, 'memory-all-third-party')
297
+ summary.thirdParty.push(other.name)
298
+ }
299
+ appendIncident({ kind: 'plugin-memory', level: 'all-third-party', target: row.name, mb, detail: '单个插件 ≥3000 MB:强制关闭 ' + summary.thirdParty.length + ' 个第三方插件(官方/内置除外)' })
300
+ }
301
+ writePendingBoot({ level: 'L1', reason: 'memory', disable: [row.name, ...summary.thirdParty], keep: [] })
302
+ }
303
+ if (summary.closed.length || summary.uninstalled.length || summary.thirdParty.length) persist(true)
304
+ return summary
305
+ }
306
+
167
307
  /** Profile drift detected by the tamper monitor: record, attribute, optionally enforce. */
168
308
  function handleTamper(result) {
169
309
  if (!result || !Array.isArray(result.diffs) || result.diffs.length === 0) return
@@ -207,5 +347,5 @@ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, ex
207
347
  return operationWindows.some((window) => mtimeMs >= window.startedAt - 5000 && mtimeMs <= (window.settledAt || now) + 5000)
208
348
  }
209
349
 
210
- return { onOperation, disableTarget, releaseTarget, disableMany, writePendingBoot, reapplyQuarantine, handleTamper, shouldIgnoreWrites, isWithinOperationWindow }
350
+ return { onOperation, disableTarget, releaseTarget, disableMany, writePendingBoot, reapplyQuarantine, handleTamper, shouldIgnoreWrites, isWithinOperationWindow, enforceMemoryTiers }
211
351
  }
@@ -95,7 +95,8 @@ export function createPersistence({ watchdogState, stateFile, incidentsFile }) {
95
95
 
96
96
  function appendIncident(incident) {
97
97
  const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
98
- if (watchdogState.config && watchdogState.config.notify === true && ['freeze', 'pause', 'quarantine', 'tamper', 'crash-enforced', 'budget'].includes(record.kind)) {
98
+ const notificationKinds = ['freeze', 'pause', 'quarantine', 'tamper', 'crash-enforced', 'crash-escalation', 'budget', 'quarantine-reminder']
99
+ if ((record.notify === true || (watchdogState.config && watchdogState.config.notify === true)) && notificationKinds.includes(record.kind)) {
99
100
  try {
100
101
  notify(record)
101
102
  } catch {
@@ -15,6 +15,19 @@ export const GB = 1024 * MB
15
15
 
16
16
  export const FREEZE_MARGIN = 0.3 * GB
17
17
  export const HOT_OP_LIMIT = 5
18
+
19
+ /** Plugin-prison memory tiers (single plugin occupancy, MB). */
20
+ export const MEMORY_TIER_MB = Object.freeze({ warn: 300, throttle: 500, close: 1000, uninstall: 2000, allThirdParty: 3000 })
21
+
22
+ export function memoryTierFor(mb) {
23
+ const value = Number(mb) || 0
24
+ if (value >= MEMORY_TIER_MB.allThirdParty) return 'all-third-party'
25
+ if (value >= MEMORY_TIER_MB.uninstall) return 'uninstall'
26
+ if (value >= MEMORY_TIER_MB.close) return 'close'
27
+ if (value >= MEMORY_TIER_MB.throttle) return 'throttle'
28
+ if (value >= MEMORY_TIER_MB.warn) return 'warn'
29
+ return 'ok'
30
+ }
18
31
  export const ADDITIVE_ACTIONS = new Set(['set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'set_version_exemption'])
19
32
  export const READONLY_ACTIONS = new Set(['list_plugins', 'list_bundles', 'list_version_exemptions'])
20
33
 
@@ -87,6 +100,13 @@ export function decideToolGuard(execution, state) {
87
100
  }
88
101
  }
89
102
  if (READONLY_ACTIONS.has(action)) return undefined
103
+ const memoryTier = state.memoryTiers instanceof Map ? state.memoryTiers.get(target) : undefined
104
+ if (memoryTier && ['throttle', 'close', 'uninstall', 'all-third-party'].includes(memoryTier.tier)) {
105
+ return {
106
+ reason: "插件 " + target + " 内存档位 " + memoryTier.tier + "(" + memoryTier.mb + " MB)已限制增内存操作(增长目标 ≤1MB/s);请先在面板“插件监狱”处理。",
107
+ info: { name: 'ai-prison-memory-tier', code: 'plugin-memory-throttled' },
108
+ }
109
+ }
90
110
  if (!ADDITIVE_ACTIONS.has(action)) return undefined
91
111
  const level = state.waterline
92
112
  if (level === 'frost') {
@@ -122,7 +122,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
122
122
  watchdogState.degraded = 'boot watch: ' + String((error && error.message) || error)
123
123
  }
124
124
 
125
- crash.readCrashLogs()
125
+ // Scan on the next microtask: ctx.inject resolves pluginManager later in create().
126
+ queueMicrotask(() => crash.readCrashLogs())
126
127
 
127
128
  // ---- tamper monitor ----------------------------------------------------
128
129
  let tamper = null
@@ -204,6 +205,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
204
205
  onAfterSample: () => {
205
206
  maybeWriteBaseline()
206
207
  refreshTamperStatus()
208
+ void enforcement.enforceMemoryTiers()
207
209
  },
208
210
  })
209
211
 
@@ -306,6 +308,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
306
308
  sample: sampler.sample,
307
309
  readCrashLogs: crash.readCrashLogs,
308
310
  probeNow: (options) => budget.scheduleProbe(options),
311
+ checkMemoryTiers: () => enforcement.enforceMemoryTiers(),
309
312
  tamperCheck: (options) => {
310
313
  if (!tamper) return null
311
314
  const result = tamper.checkNow(options)
@@ -2,6 +2,7 @@ import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { topOperations, rankTopPlugins } from './watchdog-policy.js'
4
4
  import { watchdogState } from './watchdog-state.js'
5
+ import { CRASH_RESET_MS, CRASH_WINDOW_MS } from './watchdog-core.js'
5
6
 
6
7
  /** Top5 v2: measured + estimate + child RSS with EWMA smoothing and rank hysteresis. */
7
8
  function mergedTop(state, limit) {
@@ -54,8 +55,29 @@ export function watchdogSnapshot() {
54
55
  for (const [target, entry] of s.quarantine instanceof Map ? s.quarantine : []) {
55
56
  quarantine.push({ target, ...entry })
56
57
  }
58
+ const esc = s.escalation || {}
59
+ const now = Date.now()
60
+ const recentCrashes = Array.isArray(esc.crashes) ? esc.crashes.filter((at) => now - at <= CRASH_WINDOW_MS) : []
61
+ const crashLevel = esc.level || (recentCrashes.length >= 3 ? 'L3' : recentCrashes.length >= 2 ? 'L2' : recentCrashes.length >= 1 ? 'L1' : 'L0')
62
+ const nextLevel = crashLevel === 'L0' ? 'L1' : crashLevel === 'L1' ? 'L2' : crashLevel === 'L2' ? 'L3' : null
63
+ const lastPlan = s.plans && s.plans.length > 0 ? s.plans[s.plans.length - 1] : null
64
+ const crashPlan = {
65
+ level: crashLevel,
66
+ previousLevel: esc.previousLevel || null,
67
+ crashes: recentCrashes.length,
68
+ windowMs: CRASH_WINDOW_MS,
69
+ resetMs: CRASH_RESET_MS,
70
+ lastCrashAt: esc.lastCrashAt || null,
71
+ resetAt: esc.lastCrashAt ? esc.lastCrashAt + CRASH_RESET_MS : null,
72
+ nextLevel,
73
+ steps: crashLevel === 'L3' ? ['isolate-target', 'revert-changed', 'safe-mode'] : crashLevel === 'L2' ? ['isolate-target', 'revert-changed'] : crashLevel === 'L1' ? ['isolate-target'] : [],
74
+ lastPlan: lastPlan
75
+ ? { at: lastPlan.at, level: lastPlan.level, target: lastPlan.target || null, inFlight: Boolean(lastPlan.inFlight), applied: Boolean(lastPlan.applied), fallback: lastPlan.fallback || null, targets: lastPlan.targets || [] }
76
+ : null,
77
+ }
57
78
  return {
58
79
  ok: Boolean(s.startedAt),
80
+ crashPlan,
59
81
  mode: s.mode,
60
82
  enforce: s.enforce,
61
83
  startedAt: s.startedAt,
@@ -71,9 +93,13 @@ export function watchdogSnapshot() {
71
93
  frozenAt: s.frozenAt,
72
94
  samples: s.samples.slice(-30),
73
95
  operations: mergedTop(s, 10),
74
- topFive: mergedTop(s, 5),
96
+ topFive: mergedTop(s, 5).map((row) => {
97
+ const tier = s.memoryTiers instanceof Map ? s.memoryTiers.get(row.target) : undefined
98
+ return { ...row, memoryTier: tier ? tier.tier : 'ok', memoryMB: tier ? tier.mb : null }
99
+ }),
75
100
  probeProgress: s.probeProgress || null,
76
101
  quarantine,
102
+ memoryTiers: s.memoryTiers instanceof Map ? [...s.memoryTiers].map(([target, entry]) => ({ target, ...entry })) : [],
77
103
  plans: s.plans.slice(-5),
78
104
  escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
79
105
  crashFallback: s.crashFallback || 'enforce',
@@ -26,6 +26,8 @@ export const watchdogState = {
26
26
  frozenAt: null,
27
27
  /** target -> { count, estimateMB, lastAt, version, lastApplication } */
28
28
  operations: new Map(),
29
+ /** target -> { tier, mb, at, version } from the plugin-prison memory thresholds. */
30
+ memoryTiers: new Map(),
29
31
  /** target -> { reason, level, at, evidence, release: 'restart'|'manual' } */
30
32
  quarantine: new Map(),
31
33
  /** target -> ms timestamp until which operation events are our own doing. */
@@ -37,7 +39,7 @@ export const watchdogState = {
37
39
  /** Crash attribution plans (dry-run): { at, level, target, evidence, applied } */
38
40
  plans: [],
39
41
  /** Escalation counters: crash timestamps (ms) and applied level. */
40
- escalation: { crashes: [], level: 'L0' },
42
+ escalation: { crashes: [], level: 'L0', previousLevel: null, lastCrashAt: null },
41
43
  /** Profile file tamper monitor status. */
42
44
  tamper: null,
43
45
  /** Recent incidents (newest last), capped. */
@@ -67,12 +69,13 @@ export function resetWatchdogState(overrides = {}) {
67
69
  watchdogState.graceUntil = null
68
70
  watchdogState.frozenAt = null
69
71
  watchdogState.operations = new Map()
72
+ watchdogState.memoryTiers = new Map()
70
73
  watchdogState.quarantine = new Map()
71
74
  watchdogState.suppressUntil = new Map()
72
75
  watchdogState.budgets = {}
73
76
  watchdogState.baseline = null
74
77
  watchdogState.plans = []
75
- watchdogState.escalation = { crashes: [], level: 'L0' }
78
+ watchdogState.escalation = { crashes: [], level: 'L0', previousLevel: null, lastCrashAt: null }
76
79
  watchdogState.tamper = null
77
80
  watchdogState.incidents = []
78
81
  watchdogState.lastCrashScan = 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.7.3",
3
+ "version": "1.7.6",
4
4
  "description": "AI Prison for DSH: eight governance tools wrapping the aiprison CLI (levels, status, watchdog status, 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",