@twinsearth/ai-prison-dsh-plugin 1.1.3 → 1.2.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,56 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.2.0] — 2026-11-18
6
+
7
+ ### Added — P0 memory watchdog (observe mode)
8
+
9
+ - **New loader row `ai-prison-watchdog`** (`watchdog.js` + `lib/watchdog-*.js`):
10
+ samples the host heap every 5 s (`process.memoryUsage` + `v8.getHeapStatistics`),
11
+ derives the design thresholds from the actual heap limit (300/500 MB per plugin,
12
+ 3.0/3.9/5.0 GB total, 4/5 GB operation gates), classifies the waterline
13
+ (`ok` → `warn` → `pause` → `block`) and records threshold crossings, per-plugin
14
+ operation counts (install/remove = 1, enable = 1, disable = 0.5) and estimated
15
+ heap deltas per plugin.
16
+ - **Crash-history scan**: on activation it reads new
17
+ `crash-*-host.log` files from the desktop log directory, parses
18
+ phase/OOM/exit-code and appends them to the incident journal.
19
+ - **Read-only API** `GET /api/ai-prison/watchdog/status` and a new
20
+ `ai_prison_watchdog_status` tool.
21
+ - **Panel**: two new cards — **Memory watchdog** (heap bar, used/limit, RSS,
22
+ warn/pause/block thresholds) and **Plugin prison** (top-5 plugins by estimated
23
+ heap, hot-operation counts, recent incidents). Both label themselves
24
+ "observe mode: records only, never closes plugins".
25
+ - State is persisted under `<profile>/.ai-prison-watchdog/`
26
+ (`state.json`, `incidents.jsonl`).
27
+
28
+ ### Explicitly not in this release
29
+
30
+ - No automatic closing, disabling or quarantine: enforcement (P1–P3 of
31
+ `AI-PRISON-WATCHDOG-DESIGN.md`) is not implemented and requires explicit
32
+ confirmation.
33
+
34
+ ## [1.1.4] — 2026-11-18
35
+
36
+ ### Fixed
37
+
38
+ - **Run drill failed on a second drill**: like `demo`, the CLI replays an
39
+ existing ledger and then refuses to re-seed credentials that an earlier drill
40
+ already revoked, so pressing **Run drill** on a ledger that already contained
41
+ drill events failed with `seed allocate: … credential "cred:resource:drl-N" is
42
+ present in the global revocation set`. A fresh ledger passes (157 records), and
43
+ demo-then-drill passes (233 records); only a second drill failed.
44
+
45
+ ### Changed
46
+
47
+ - **Both actions now start from a clean baseline**: pressing **Run demo** or
48
+ **Run drill** clears the CLI's own `seg-*.log` files first (two-click
49
+ confirmation when the ledger is not empty), so every run is deterministic.
50
+ The action posts `reset-demo` / `reset-drill` to `POST /api/ai-prison/run`;
51
+ the separate rebuild button is gone.
52
+ - `ai_prison_drill` attaches a `hint` for replay/seed-allocation failures, and
53
+ the panel explains the clear-first behaviour under the buttons.
54
+
5
55
  ## [1.1.3] — 2026-11-18
6
56
 
7
57
  ### Added
package/README.md CHANGED
@@ -34,14 +34,27 @@ panel; the six tools become visible to the Agent on the next session step.
34
34
 
35
35
  The panel shows the matrix from `ai_prison_levels` data plus the ledger
36
36
  directory, integrity pill, record/segment/file counts; it refreshes every 20
37
- seconds and on demand. Below the audit-chain card sit three explicit buttons —
38
- **Run demo (create ledger)**, **Run recovery drill**, and **Rebuild ledger
39
- (clear and run demo)** (two-click confirmation) — which call `POST
40
- /api/ai-prison/run` and therefore write the ledger only when pressed; the panel
41
- never writes on its own. `demo` needs an empty ledger because the CLI replays an
42
- existing one and refuses to re-seed revoked credentials, so the demo button is
43
- disabled once segments exist and the rebuild action clears the CLI's own
44
- `seg-*.log` files before running it.
37
+ seconds and on demand. Below the audit-chain card sit two explicit buttons —
38
+ **Run demo** and **Run drill** — which call `POST /api/ai-prison/run` and
39
+ therefore write the ledger only when pressed; the panel never writes on its own.
40
+ Both runs start from a clean baseline: when the ledger already has segments the
41
+ first click asks for confirmation, then the CLI's own `seg-*.log` files are
42
+ deleted and the action runs, because the CLI replays an existing ledger and
43
+ refuses to re-seed credentials that earlier runs already revoked (`demo` twice,
44
+ or a second `drill`, would otherwise fail).
45
+
46
+ ## Memory watchdog (P0, observe only)
47
+
48
+ A second loader row (`ai-prison-watchdog`) samples the host heap every 5 seconds,
49
+ derives the design thresholds from the real heap limit (300/500 MB per plugin,
50
+ 3.0/3.9/5.0 GB total, 4/5 GB operation gates), accounts plugin operations
51
+ (install/remove = 1, enable = 1, disable = 0.5), estimates each plugin's heap
52
+ delta around those operations and reads new `crash-*-host.log` files at startup.
53
+ It exposes `GET /api/ai-prison/watchdog/status` and the read-only
54
+ `ai_prison_watchdog_status` tool; the panel adds **Memory watchdog** and
55
+ **Plugin prison** cards. **Observe mode never enables or disables a plugin** —
56
+ enforcement (P1–P3) is not implemented and needs explicit confirmation.
57
+ State lives in `<profile>/.ai-prison-watchdog/`.
45
58
 
46
59
  ## Ledger directory
47
60
 
package/client.js CHANGED
@@ -11,6 +11,7 @@ window.__ModuleLoader__.load({
11
11
  const NS = 'ai-prison'
12
12
  const STATUS_URL = 'api/ai-prison/status'
13
13
  const RUN_URL = 'api/ai-prison/run'
14
+ const WATCHDOG_URL = 'api/ai-prison/watchdog/status'
14
15
 
15
16
  const DICTS = {
16
17
  en: {
@@ -39,17 +40,35 @@ window.__ModuleLoader__.load({
39
40
  'cli.source': 'Source',
40
41
  'action.refresh': 'Refresh',
41
42
  'action.loading': 'Reading…',
42
- 'action.runDemo': 'Run demo (create ledger)',
43
- 'action.runDrill': 'Run recovery drill',
44
- 'action.resetDemo': 'Rebuild ledger (clear and run demo)',
45
- 'action.confirmReset': 'Click again to clear {records} records',
43
+ 'action.runDemo': 'Run demo',
44
+ 'action.runDrill': 'Run drill',
45
+ 'action.confirmRun': 'Click again: clear {records} records and run',
46
46
  'action.running': 'Running…',
47
47
  'ledger.actions': 'Explicit actions',
48
- 'ledger.actionsHint': 'These buttons run the bundled CLI and write the ledger; the panel never writes on its own.',
49
- 'ledger.demoNeedsEmpty': 'The ledger is not empty: the demo needs a fresh ledger. Rebuild it or run the recovery drill instead.',
48
+ 'ledger.actionsHint': 'These buttons run the bundled CLI. An existing ledger is cleared first, so every run starts from a consistent baseline.',
49
+ 'ledger.resetHint': 'The ledger already exists: a run clears its segments first, then executes. Click twice to confirm.',
50
50
  'ledger.lastAction': 'Last action',
51
51
  'meta.updated': 'Updated {time}',
52
52
  'meta.readonly': 'Read-only view: the panel never writes by itself; only the buttons above do.',
53
+ 'watchdog.title': 'Memory watchdog',
54
+ 'watchdog.mode': 'Observe mode: records only, never closes plugins',
55
+ 'watchdog.disabled': 'Watchdog row not enabled; heap observation is unavailable.',
56
+ 'watchdog.heap': 'Heap used',
57
+ 'watchdog.limit': 'Heap limit',
58
+ 'watchdog.rss': 'RSS',
59
+ 'watchdog.waterline': 'Waterline',
60
+ 'watchdog.thresholds': 'Warn / pause / block',
61
+ 'waterline.ok': 'OK',
62
+ 'waterline.warn': 'Warning',
63
+ 'waterline.pause': 'Paused',
64
+ 'waterline.block': 'Blocked',
65
+ 'prison.title': 'Plugin prison',
66
+ 'prison.top': 'Top {n} plugins by estimated heap',
67
+ 'prison.ops': 'Hot ops',
68
+ 'prison.estimate': 'Est.',
69
+ 'prison.incidents': 'Recent incidents',
70
+ 'prison.empty': 'No quarantined plugins: observe mode never closes one.',
71
+ 'prison.noestimates': 'No plugin operations observed yet.',
53
72
  'error.title': 'Cannot read the status',
54
73
  'error.hint': 'Check that the bundle is enabled and the aiprison CLI resolves for this platform.',
55
74
  },
@@ -79,17 +98,35 @@ window.__ModuleLoader__.load({
79
98
  'cli.source': '来源',
80
99
  'action.refresh': '刷新',
81
100
  'action.loading': '读取中…',
82
- 'action.runDemo': '运行 demo(创建账本)',
83
- 'action.runDrill': '运行恢复演练',
84
- 'action.resetDemo': '重置账本并重建',
85
- 'action.confirmReset': '再次点击确认清空 {records} 条记录',
101
+ 'action.runDemo': '运行 demo',
102
+ 'action.runDrill': '运行演练',
103
+ 'action.confirmRun': '再次点击:清空 {records} 条记录并运行',
86
104
  'action.running': '运行中…',
87
105
  'ledger.actions': '显式操作',
88
- 'ledger.actionsHint': '这些按钮会运行内置 CLI 并写入账本;面板本身不会自动写入。',
89
- 'ledger.demoNeedsEmpty': '账本非空:demo 需要空账本。请点「重置账本并重建」,或改用「运行恢复演练」。',
106
+ 'ledger.actionsHint': '这些按钮运行内置 CLI;账本已存在时会先清空,保证每次从一致基线开始。',
107
+ 'ledger.resetHint': '账本已存在:运行会先清空账本段再执行;再次点击确认。',
90
108
  'ledger.lastAction': '最近操作',
91
109
  'meta.updated': '更新于 {time}',
92
110
  'meta.readonly': '只读视图:面板不会自行写入账本,只有上方按钮会写入。',
111
+ 'watchdog.title': '内存看护',
112
+ 'watchdog.mode': '观察模式:只记录,不关闭插件',
113
+ 'watchdog.disabled': 'watchdog 行未启用,暂时无法观察内存。',
114
+ 'watchdog.heap': '已用堆',
115
+ 'watchdog.limit': '堆上限',
116
+ 'watchdog.rss': 'RSS',
117
+ 'watchdog.waterline': '水位',
118
+ 'watchdog.thresholds': '提醒 / 暂停 / 禁止',
119
+ 'waterline.ok': '正常',
120
+ 'waterline.warn': '警告',
121
+ 'waterline.pause': '暂停',
122
+ 'waterline.block': '禁止',
123
+ 'prison.title': '插件监狱',
124
+ 'prison.top': '按估算内存排序的前 {n} 个插件',
125
+ 'prison.ops': '热操作',
126
+ 'prison.estimate': '估算',
127
+ 'prison.incidents': '最近事件',
128
+ 'prison.empty': '没有被隔离的插件:观察模式不会关闭任何插件。',
129
+ 'prison.noestimates': '还没有观察到插件操作。',
93
130
  'error.title': '无法读取状态',
94
131
  'error.hint': '请确认插件已启用,且本平台能解析到 aiprison CLI。',
95
132
  },
@@ -236,6 +273,130 @@ window.__ModuleLoader__.load({
236
273
  })
237
274
  }
238
275
 
276
+ /** Read-only watchdog snapshot; a missing row (or 404) simply hides the cards. */
277
+ function fetchWatchdog() {
278
+ return fetch(new URL(WATCHDOG_URL, document.baseURI), {
279
+ credentials: 'same-origin',
280
+ headers: { accept: 'application/json' },
281
+ }).then((response) => {
282
+ if (!response.ok) return null
283
+ return response.json().then((payload) => (payload && payload.ok ? payload : null))
284
+ })
285
+ }
286
+
287
+ function waterlineText(level) {
288
+ if (level === 'block') return t('waterline.block')
289
+ if (level === 'pause') return t('waterline.pause')
290
+ if (level === 'warn') return t('waterline.warn')
291
+ return t('waterline.ok')
292
+ }
293
+
294
+ function MemoryCard({ watchdog }) {
295
+ if (!watchdog) {
296
+ return h(
297
+ 'section',
298
+ { style: C.card },
299
+ h('div', { style: C.cardHead }, t('watchdog.title')),
300
+ h('p', { style: { ...C.muted, fontSize: 12, margin: 0 } }, t('watchdog.disabled')),
301
+ )
302
+ }
303
+ const heap = watchdog.heap || {}
304
+ const thresholds = watchdog.thresholds || {}
305
+ const ratio = heap.heapLimit > 0 ? Math.min(1, heap.heapUsed / heap.heapLimit) : 0
306
+ const tone = watchdog.waterline === 'ok' ? C.ok.color : watchdog.waterline === 'warn' ? '#b45309' : C.error.color
307
+ return h(
308
+ 'section',
309
+ { style: C.card },
310
+ h(
311
+ 'div',
312
+ { style: C.cardHead },
313
+ t('watchdog.title'),
314
+ h('span', { style: { ...C.chip, marginLeft: 8 } }, t('watchdog.mode')),
315
+ h(Pill, { tone: watchdog.waterline === 'ok' ? 'ok' : 'error', text: `${t('watchdog.waterline')}: ${waterlineText(watchdog.waterline)}` }),
316
+ ),
317
+ h(
318
+ 'div',
319
+ { style: { height: 10, borderRadius: 999, background: 'var(--dsw-alias-border-l1, rgba(0,0,0,.08))', overflow: 'hidden', margin: '4px 0 10px' } },
320
+ h('div', { style: { width: `${Math.round(ratio * 1000) / 10}%`, height: '100%', background: tone } }),
321
+ ),
322
+ h(
323
+ 'div',
324
+ { style: C.grid },
325
+ h('div', { style: C.key }, t('watchdog.heap')),
326
+ h('div', { style: C.mono }, `${Math.round(heap.heapUsed / 1048576)} MB / ${Math.round(heap.heapLimit / 1048576)} MB(${Math.round(ratio * 100)}%)`),
327
+ h('div', { style: C.key }, t('watchdog.rss')),
328
+ h('div', { style: C.mono }, `${Math.round((heap.rss || 0) / 1048576)} MB`),
329
+ h('div', { style: C.key }, t('watchdog.thresholds')),
330
+ h(
331
+ 'div',
332
+ { style: C.mono },
333
+ `${Math.round(thresholds.totalWarn / 1048576)} / ${Math.round(thresholds.totalPause / 1048576)} / ${Math.round(thresholds.totalBlock / 1048576)} MB`,
334
+ ),
335
+ ),
336
+ )
337
+ }
338
+
339
+ function PrisonCard({ watchdog }) {
340
+ if (!watchdog) {
341
+ return h(
342
+ 'section',
343
+ { style: C.card },
344
+ h('div', { style: C.cardHead }, t('prison.title')),
345
+ h('p', { style: { ...C.muted, fontSize: 12, margin: 0 } }, t('watchdog.disabled')),
346
+ )
347
+ }
348
+ const operations = Array.isArray(watchdog.operations) ? watchdog.operations.slice(0, 5) : []
349
+ const incidents = Array.isArray(watchdog.incidents) ? watchdog.incidents.slice(-5).reverse() : []
350
+ return h(
351
+ 'section',
352
+ { style: C.card },
353
+ h('div', { style: C.cardHead }, t('prison.title'), h('span', { style: { ...C.chip, marginLeft: 8 } }, t('watchdog.mode'))),
354
+ operations.length === 0
355
+ ? h('p', { style: { ...C.muted, fontSize: 12, margin: '0 0 6px' } }, t('prison.noestimates'))
356
+ : h(
357
+ 'table',
358
+ { style: C.table },
359
+ h(
360
+ 'thead',
361
+ null,
362
+ h('tr', null, h('th', { style: C.th }, t('prison.top', { n: operations.length })), h('th', { style: C.th }, t('prison.estimate')), h('th', { style: C.th }, t('prison.ops'))),
363
+ ),
364
+ h(
365
+ 'tbody',
366
+ null,
367
+ operations.map((row) =>
368
+ h(
369
+ 'tr',
370
+ { key: row.target },
371
+ h('td', { style: { ...C.td, ...C.mono, wordBreak: 'break-all' } }, row.target),
372
+ h('td', { style: C.td }, `${row.estimateMB} MB`),
373
+ h('td', { style: C.td }, String(row.count)),
374
+ ),
375
+ ),
376
+ ),
377
+ ),
378
+ h('p', { style: { ...C.muted, fontSize: 12, margin: '10px 0 4px' } }, t('prison.empty')),
379
+ incidents.length > 0
380
+ ? h(
381
+ 'div',
382
+ null,
383
+ h('div', { style: { ...C.key, marginBottom: 4 } }, t('prison.incidents')),
384
+ h(
385
+ 'div',
386
+ { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
387
+ incidents.map((incident, index) =>
388
+ h(
389
+ 'div',
390
+ { key: `${incident.at || index}-${index}`, style: { ...C.mono, fontSize: 11.5, wordBreak: 'break-word' } },
391
+ `${incident.at || ''} · ${incident.kind || 'event'}${incident.detail ? ` · ${incident.detail}` : ''}${incident.target ? ` · ${incident.target}` : ''}`,
392
+ ),
393
+ ),
394
+ ),
395
+ )
396
+ : null,
397
+ )
398
+ }
399
+
239
400
  function MatrixCard({ levels }) {
240
401
  if (!Array.isArray(levels) || levels.length === 0) {
241
402
  return h('section', { style: C.card }, h('div', { style: C.cardHead }, t('matrix.title')), h('p', { style: { ...C.muted, margin: 0, fontSize: 12 } }, t('matrix.empty')))
@@ -271,9 +432,9 @@ window.__ModuleLoader__.load({
271
432
  }
272
433
 
273
434
  function LedgerCard({ ledger, cliFound, busy, onAction, lastResult }) {
274
- const [confirmReset, setConfirmReset] = React.useState(false)
435
+ const [pending, setPending] = React.useState(null)
275
436
  const exists = Boolean(ledger && ledger.exists)
276
- const canDemo = !exists || ledger.canDemo !== false
437
+ const needsReset = exists && Number(ledger.segments ?? 0) > 0
277
438
  const integrityTone = !exists ? 'none' : ledger.integrity === 'ok' ? 'ok' : 'error'
278
439
  const integrityText = !exists ? t('integrity.none') : ledger.integrity === 'ok' ? t('integrity.ok') : t('integrity.failed')
279
440
  const entries = [
@@ -289,14 +450,22 @@ window.__ModuleLoader__.load({
289
450
  entries.push({ key: 'detail', label: t('ledger.detail'), value: h('span', { style: { ...C.mono, wordBreak: 'break-word' } }, ledger.detail) })
290
451
  }
291
452
  const disabled = Boolean(busy) || !cliFound
292
- const rebuild = () => {
293
- if (!confirmReset) {
294
- setConfirmReset(true)
453
+ /** A non-empty ledger is cleared first; that run needs a second click. */
454
+ const run = (action) => {
455
+ if (needsReset && pending !== action) {
456
+ setPending(action)
295
457
  return
296
458
  }
297
- setConfirmReset(false)
298
- onAction('reset-demo')
459
+ setPending(null)
460
+ onAction(needsReset ? `reset-${action}` : action)
461
+ }
462
+ const labelOf = (action, idle) => {
463
+ if (busy === action || busy === `reset-${action}`) return t('action.running')
464
+ if (needsReset && pending === action) return t('action.confirmRun', { records: ledger.records ?? '?' })
465
+ return t(idle)
299
466
  }
467
+ const confirmStyle = (action) =>
468
+ needsReset && pending === action ? { ...C.actionBtn, color: '#b45309', borderColor: '#f59e0b' } : C.actionBtn
300
469
  return h(
301
470
  'section',
302
471
  { style: C.card },
@@ -313,35 +482,11 @@ window.__ModuleLoader__.load({
313
482
  h(
314
483
  'div',
315
484
  { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 10 } },
316
- h(
317
- 'button',
318
- { type: 'button', style: C.actionBtn, disabled: disabled || !canDemo, onClick: () => onAction('demo') },
319
- busy === 'demo' ? t('action.running') : t('action.runDemo'),
320
- ),
321
- h(
322
- 'button',
323
- { type: 'button', style: C.actionBtn, disabled, onClick: () => onAction('drill') },
324
- busy === 'drill' ? t('action.running') : t('action.runDrill'),
325
- ),
326
- exists
327
- ? h(
328
- 'button',
329
- {
330
- type: 'button',
331
- style: confirmReset ? { ...C.actionBtn, color: '#b45309', borderColor: '#f59e0b' } : C.actionBtn,
332
- disabled,
333
- onClick: rebuild,
334
- },
335
- busy === 'reset-demo'
336
- ? t('action.running')
337
- : confirmReset
338
- ? t('action.confirmReset', { records: ledger.records ?? '?' })
339
- : t('action.resetDemo'),
340
- )
341
- : null,
485
+ h('button', { type: 'button', style: confirmStyle('demo'), disabled, onClick: () => run('demo') }, labelOf('demo', 'action.runDemo')),
486
+ h('button', { type: 'button', style: confirmStyle('drill'), disabled, onClick: () => run('drill') }, labelOf('drill', 'action.runDrill')),
342
487
  h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('ledger.actionsHint')),
343
488
  ),
344
- !canDemo ? h('p', { style: { ...C.muted, fontSize: 12, margin: '8px 0 0' } }, t('ledger.demoNeedsEmpty')) : null,
489
+ needsReset ? h('p', { style: { ...C.muted, fontSize: 12, margin: '8px 0 0' } }, t('ledger.resetHint')) : null,
345
490
  lastResult
346
491
  ? h(
347
492
  'p',
@@ -367,6 +512,7 @@ window.__ModuleLoader__.load({
367
512
  const [updated, setUpdated] = React.useState(null)
368
513
  const [busy, setBusy] = React.useState(null)
369
514
  const [lastResult, setLastResult] = React.useState(null)
515
+ const [watchdog, setWatchdog] = React.useState(null)
370
516
 
371
517
  const load = React.useCallback(() => {
372
518
  setLoading(true)
@@ -389,6 +535,25 @@ window.__ModuleLoader__.load({
389
535
  return () => clearInterval(timer)
390
536
  }, [load])
391
537
 
538
+ React.useEffect(() => {
539
+ let cancelled = false
540
+ const tick = () => {
541
+ fetchWatchdog()
542
+ .then((payload) => {
543
+ if (!cancelled) setWatchdog(payload)
544
+ })
545
+ .catch(() => {
546
+ if (!cancelled) setWatchdog(null)
547
+ })
548
+ }
549
+ tick()
550
+ const timer = setInterval(tick, 15000)
551
+ return () => {
552
+ cancelled = true
553
+ clearInterval(timer)
554
+ }
555
+ }, [])
556
+
392
557
  const runAction = React.useCallback(
393
558
  (action) => {
394
559
  setBusy(action)
@@ -439,6 +604,8 @@ window.__ModuleLoader__.load({
439
604
  onAction: runAction,
440
605
  lastResult,
441
606
  }),
607
+ h(MemoryCard, { watchdog }),
608
+ h(PrisonCard, { watchdog }),
442
609
  h(
443
610
  'p',
444
611
  { style: { ...C.muted, fontSize: 12, margin: '2px 0 0', display: 'flex', gap: 12, flexWrap: 'wrap' } },
package/cordis.patch.yml CHANGED
@@ -1,21 +1,30 @@
1
1
  # ai-prison-dsh-plugin: the AI Prison governance bundle.
2
2
  #
3
- # One row carries both halves: the Host half registers the six aiprison_* tools
4
- # and the read-only status API behind the panel, the Client half registers the
5
- # sidebar panel that renders the L0–L5 matrix and the audit-chain state.
3
+ # Two rows:
4
+ # ai-prison Host tools + read-only status API + the sidebar panel
5
+ # (L0-L5 matrix, audit chain, plugin prison and memory cards).
6
+ # ai-prison-watchdog P0 watchdog in OBSERVE mode: samples the host heap,
7
+ # accounts plugin operations, reads recent host crash logs and
8
+ # serves /api/ai-prison/watchdog/status. It never enables or
9
+ # disables a plugin; enforcement arrives in later phases.
6
10
  #
7
11
  # Optional config (a profile-level patch replaces this block wholesale, so
8
12
  # restate every field you want to keep):
9
13
  #
10
14
  # config:
11
- # # Absolute path to an aiprison binary. Default: the bundled build for
12
- # # this platform, else `aiprison` on PATH.
13
- # cliPath: ''
14
- # # Durable ledger directory. Default: <session working directory>/.ai-prison
15
- # dataDir: ''
16
- # # Per-call timeout for the bundled CLI, milliseconds.
17
- # timeoutMs: 120000
15
+ # cliPath: '' # absolute path to an aiprison binary
16
+ # dataDir: '' # durable ledger directory (default <session cwd>/.ai-prison)
17
+ # timeoutMs: 120000 # per-call CLI timeout
18
+ #
19
+ # The watchdog accepts:
20
+ #
21
+ # config:
22
+ # sampleMs: 5000 # heap sampling interval
23
+ # observe: true # P0 is observe-only; enforcement is not implemented yet
18
24
  - insert:
19
25
  - id: ai-prison
20
26
  name: '@twinsearth/ai-prison-dsh-plugin'
21
27
  config: {}
28
+ - id: ai-prison-watchdog
29
+ name: '@twinsearth/ai-prison-dsh-plugin/watchdog'
30
+ config: {}
package/lib/api.js CHANGED
@@ -31,7 +31,7 @@ export function resolveSessionCwd(ctx) {
31
31
  return undefined
32
32
  }
33
33
 
34
- const ACTIONS = new Set(['demo', 'drill', 'reset', 'reset-demo'])
34
+ const ACTIONS = new Set(['demo', 'drill', 'reset', 'reset-demo', 'reset-drill'])
35
35
 
36
36
  function jsonResponse(payload, status = 200) {
37
37
  return Response.json(payload, { status, headers: { 'cache-control': 'no-store' } })
@@ -95,7 +95,7 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
95
95
  const dataDir = requested ? requested : resolveDataDir({ config, cwd })
96
96
 
97
97
  let removed = []
98
- if (action === 'reset' || action === 'reset-demo') {
98
+ if (action === 'reset' || action === 'reset-demo' || action === 'reset-drill') {
99
99
  const reset = resetLedger(dataDir)
100
100
  if (!reset.ok) {
101
101
  return jsonResponse({ ok: false, action, dataDir, error: reset.error || 'reset failed' }, 500)
@@ -116,7 +116,7 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
116
116
  return jsonResponse({ ok: false, error: resolved.missing, reason: 'cli-missing' }, 409)
117
117
  }
118
118
  const timeoutMs = Number(config.timeoutMs) > 0 ? Number(config.timeoutMs) : 120_000
119
- const runAction = action === 'reset-demo' ? 'demo' : action
119
+ const runAction = action.startsWith('reset-') ? action.slice('reset-'.length) : action
120
120
  if (runAction === 'demo' && listSegments(dataDir).length > 0) {
121
121
  return jsonResponse(
122
122
  {
@@ -124,7 +124,7 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
124
124
  action,
125
125
  dataDir,
126
126
  error: 'ledger-not-empty',
127
- hint: '账本已有记录:demo 需要空账本。请点「重置账本并重建」,或改用「运行恢复演练」。',
127
+ hint: '账本已有记录:demo 需要空账本。请点「重置账本并重建」,或改用「运行演练」。',
128
128
  },
129
129
  409,
130
130
  )
package/lib/tools.js CHANGED
@@ -2,6 +2,8 @@ import path from 'node:path'
2
2
  import { resolveCli, resolveDataDir, runCli } from './cli.js'
3
3
  import { loadDefineTool } from './harness.js'
4
4
  import { buildStatus, statusSummary } from './status.js'
5
+ import { watchdogSnapshot } from './watchdog-runtime.js'
6
+ import { formatBytes } from './watchdog-policy.js'
5
7
 
6
8
  const MAX_TEXT = 4_000
7
9
  const TAIL_LINES = 60
@@ -159,6 +161,54 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
159
161
  },
160
162
  })
161
163
 
164
+ register({
165
+ name: 'ai_prison_watchdog_status',
166
+ description:
167
+ 'Read the AI Prison watchdog snapshot (P0 observe mode): host heap usage and limit, derived thresholds, the waterline verdict, per-plugin heap estimates, hot plugin-operation counts and recent incidents (including host crash logs observed at startup). Observe mode never enables or disables a plugin.',
168
+ parameters: {},
169
+ output: stringOutput,
170
+ async execute() {
171
+ const snapshot = watchdogSnapshot()
172
+ if (!snapshot.ok) {
173
+ return toolResult({
174
+ ok: false,
175
+ mode: 'disabled',
176
+ hint: 'watchdog 行未启用:在插件配置里启用 ai-prison-watchdog 后重启即可开始观察。',
177
+ })
178
+ }
179
+ const heap = snapshot.heap || {}
180
+ return toolResult({
181
+ ok: true,
182
+ mode: snapshot.mode,
183
+ dataDir: snapshot.dataDir,
184
+ degraded: snapshot.degraded,
185
+ waterline: snapshot.waterline,
186
+ heap: {
187
+ used: formatBytes(heap.heapUsed),
188
+ total: formatBytes(heap.heapTotal),
189
+ limit: formatBytes(heap.heapLimit),
190
+ rss: formatBytes(heap.rss),
191
+ heapUsedBytes: heap.heapUsed,
192
+ heapLimitBytes: heap.heapLimit,
193
+ },
194
+ thresholds: snapshot.thresholds
195
+ ? {
196
+ totalWarn: formatBytes(snapshot.thresholds.totalWarn),
197
+ totalPause: formatBytes(snapshot.thresholds.totalPause),
198
+ totalBlock: formatBytes(snapshot.thresholds.totalBlock),
199
+ singleWarn: formatBytes(snapshot.thresholds.singleWarn),
200
+ singleBlock: formatBytes(snapshot.thresholds.singleBlock),
201
+ opWarn: formatBytes(snapshot.thresholds.opWarn),
202
+ opBlock: formatBytes(snapshot.thresholds.opBlock),
203
+ }
204
+ : null,
205
+ operations: snapshot.operations,
206
+ incidents: snapshot.incidents,
207
+ note: 'observe 模式:仅观察与记录,不自动关闭任何插件。',
208
+ })
209
+ },
210
+ })
211
+
162
212
  register({
163
213
  name: 'ai_prison_demo',
164
214
  description:
@@ -190,6 +240,13 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
190
240
  output: stringOutput,
191
241
  async execute(args, exec) {
192
242
  const outcome = await invoke({ ctx, config, exec, subcommand: 'drill', dataDir: args?.data_dir })
243
+ if (!outcome.ok) {
244
+ const text = `${outcome.payload.stdout || ''}\n${outcome.payload.stderr || ''}`
245
+ if (/reopened ledger|seed allocate/i.test(text)) {
246
+ outcome.payload.hint =
247
+ '账本已被此前的演练写入:再次演练会重放旧事件并拒绝重新分配已吊销的凭据。请清空该数据目录下的 seg-*.log(或换一个空 data_dir)后重试;面板的「运行演练」会自动先清空。'
248
+ }
249
+ }
193
250
  return toolResult(outcome.payload)
194
251
  },
195
252
  })
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Pure policy math for the AI Prison watchdog (P0 observe mode).
3
+ * No I/O here: every function takes plain numbers/strings so the panel, the
4
+ * tools and the tests share one definition of the thresholds.
5
+ */
6
+ export const MB = 1024 * 1024
7
+ export const GB = 1024 * MB
8
+
9
+ /** Thresholds derived from the host heap limit (absolute values clamped to the cap). */
10
+ export function thresholdsFor(heapLimitBytes) {
11
+ const limit = Number(heapLimitBytes) > 0 ? Number(heapLimitBytes) : 4 * GB
12
+ const clamp = (absolute, ratio) => Math.min(absolute, ratio * limit)
13
+ return {
14
+ heapLimit: limit,
15
+ singleWarn: clamp(300 * MB, 0.075),
16
+ singleBlock: clamp(500 * MB, 0.125),
17
+ totalWarn: clamp(3 * GB, 0.73),
18
+ totalPause: clamp(3.9 * GB, 0.88),
19
+ totalBlock: clamp(5 * GB, 0.93),
20
+ opWarn: clamp(4 * GB, 2 / 3),
21
+ opBlock: clamp(5 * GB, 5 / 6),
22
+ }
23
+ }
24
+
25
+ /** Waterline for the whole host: ok | warn | pause | block. */
26
+ export function classifyWaterline(heapUsed, thresholds) {
27
+ if (!thresholds || !(heapUsed >= 0)) return 'ok'
28
+ if (heapUsed >= thresholds.totalBlock) return 'block'
29
+ if (heapUsed >= thresholds.totalPause) return 'pause'
30
+ if (heapUsed >= thresholds.totalWarn) return 'warn'
31
+ return 'ok'
32
+ }
33
+
34
+ /** How much one plugin operation counts toward the per-target hot-operation limit. */
35
+ export function operationWeight(operation) {
36
+ if (!operation || typeof operation !== 'object') return 0
37
+ const { stage, enabled } = operation
38
+ if (stage === 'install' || stage === 'remove') return 1
39
+ if (stage === 'enable') return enabled === false ? 0.5 : 1
40
+ return 0
41
+ }
42
+
43
+ /** Exponentially weighted estimate of a plugin's heap cost. */
44
+ export function mergeEstimate(previous, next, alpha = 0.5) {
45
+ const value = Number(next)
46
+ if (!Number.isFinite(value) || value < 0) return Number(previous) || 0
47
+ const before = Number(previous)
48
+ if (!Number.isFinite(before) || before <= 0) return value
49
+ return Math.round(before * (1 - alpha) + value * alpha)
50
+ }
51
+
52
+ /** Parse the header block of a DSH desktop host crash log. */
53
+ export function parseCrashLog(text) {
54
+ const source = String(text || '')
55
+ const header = source.slice(0, 4000)
56
+ const time = /^time:\s*(.+)$/m.exec(header)
57
+ const phase = /^phase:\s*(.+)$/m.exec(header)
58
+ const exit = /exited with (\d+)/.exec(source)
59
+ const oom = /heap out of memory|Allocation failed|MarkCompactCollector|Scavenger:/i.test(source)
60
+ const fatal = /FATAL ERROR/.test(source)
61
+ return {
62
+ valid: Boolean(time || exit || fatal),
63
+ time: time ? time[1].trim() : null,
64
+ phase: phase ? phase[1].trim() : null,
65
+ hostExitCode: exit ? Number(exit[1]) : null,
66
+ oom,
67
+ }
68
+ }
69
+
70
+ /** A compact top-N view of the per-target accounting, biggest estimate first. */
71
+ export function topOperations(operations, limit = 5) {
72
+ const rows = []
73
+ for (const [target, entry] of operations instanceof Map ? operations : Object.entries(operations || {})) {
74
+ rows.push({
75
+ target,
76
+ count: Number(entry.count) || 0,
77
+ estimateMB: Number(entry.estimateMB) || 0,
78
+ lastAt: entry.lastAt || null,
79
+ version: entry.version || null,
80
+ })
81
+ }
82
+ rows.sort((a, b) => b.estimateMB - a.estimateMB || b.count - a.count)
83
+ return rows.slice(0, Math.max(1, limit))
84
+ }
85
+
86
+ /** Named byte formatting used by the panel/tool text. */
87
+ export function formatBytes(bytes) {
88
+ const value = Number(bytes)
89
+ if (!Number.isFinite(value) || value < 0) return '—'
90
+ if (value >= GB) return `${(value / GB).toFixed(2)} GB`
91
+ return `${Math.round(value / MB)} MB`
92
+ }
@@ -0,0 +1,343 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import v8 from 'node:v8'
5
+ import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
6
+ import {
7
+ classifyWaterline,
8
+ formatBytes,
9
+ mergeEstimate,
10
+ operationWeight,
11
+ parseCrashLog,
12
+ thresholdsFor,
13
+ topOperations,
14
+ } from './watchdog-policy.js'
15
+
16
+ const SAMPLE_MS = 5_000
17
+ const FLUSH_MS = 30_000
18
+ const CRASH_HEAD_BYTES = 8 * 1024
19
+ const LEVEL_RANK = { ok: 0, warn: 1, pause: 2, block: 3 }
20
+
21
+ function resolveProfileDir() {
22
+ const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.trim()
23
+ if (fromEnv) return fromEnv
24
+ const name = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE.trim() ? process.env.DSH_PROFILE.trim() : 'desktop'
25
+ return path.join(os.homedir(), '.dsh', 'profiles', name)
26
+ }
27
+
28
+ function resolveLogsDir() {
29
+ const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
30
+ return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'logs')
31
+ }
32
+
33
+ function readHead(file, bytes) {
34
+ let fd
35
+ try {
36
+ fd = fs.openSync(file, 'r')
37
+ const buffer = Buffer.alloc(bytes)
38
+ const read = fs.readSync(fd, buffer, 0, bytes, 0)
39
+ return buffer.subarray(0, read).toString('utf8')
40
+ } catch {
41
+ return ''
42
+ } finally {
43
+ if (fd !== undefined) {
44
+ try {
45
+ fs.closeSync(fd)
46
+ } catch {
47
+ // ignore
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ /** Read-only watchdog runtime. It observes; it never enables or disables plugins. */
54
+ export function createWatchdog(ctx, config = {}, logger = {}) {
55
+ const profileDir = resolveProfileDir()
56
+ const dataDir = path.join(profileDir, '.ai-prison-watchdog')
57
+ const stateFile = path.join(dataDir, 'state.json')
58
+ const incidentsFile = path.join(dataDir, 'incidents.jsonl')
59
+ const log = {
60
+ info: (...args) => (typeof logger.info === 'function' ? logger.info(...args) : undefined),
61
+ warn: (...args) => (typeof logger.warn === 'function' ? logger.warn(...args) : undefined),
62
+ }
63
+
64
+ try {
65
+ fs.mkdirSync(dataDir, { recursive: true })
66
+ } catch (error) {
67
+ watchdogState.degraded = `cannot create ${dataDir}: ${String((error && error.message) || error)}`
68
+ }
69
+
70
+ watchdogState.mode = 'observe'
71
+ watchdogState.startedAt = new Date().toISOString()
72
+ watchdogState.dataDir = dataDir
73
+ watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
74
+ watchdogState.lastCrashScan = 0
75
+
76
+ restoreState()
77
+ readCrashLogs()
78
+
79
+ function restoreState() {
80
+ try {
81
+ const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
82
+ watchdogState.lastCrashScan = Number(parsed.lastCrashScan) > 0 ? Number(parsed.lastCrashScan) : 0
83
+ if (Array.isArray(parsed.incidents)) {
84
+ watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
85
+ }
86
+ } catch {
87
+ // first run or unreadable state: start clean
88
+ }
89
+ }
90
+
91
+ function appendIncident(incident) {
92
+ const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
93
+ watchdogState.incidents.push(record)
94
+ if (watchdogState.incidents.length > MAX_INCIDENTS) {
95
+ watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
96
+ }
97
+ try {
98
+ fs.appendFileSync(incidentsFile, `${JSON.stringify(record)}\n`)
99
+ const stat = fs.statSync(incidentsFile)
100
+ if (stat.size > 1024 * 1024) {
101
+ const lines = fs.readFileSync(incidentsFile, 'utf8').trim().split('\n').slice(-500)
102
+ fs.writeFileSync(incidentsFile, `${lines.join('\n')}\n`)
103
+ }
104
+ } catch {
105
+ // auditing is best-effort in observe mode
106
+ }
107
+ return record
108
+ }
109
+
110
+ let lastFlush = 0
111
+ function persist(force = false) {
112
+ const now = Date.now()
113
+ if (!force && now - lastFlush < FLUSH_MS) return
114
+ lastFlush = now
115
+ const payload = {
116
+ startedAt: watchdogState.startedAt,
117
+ lastCrashScan: watchdogState.lastCrashScan,
118
+ incidents: watchdogState.incidents.slice(-50),
119
+ }
120
+ try {
121
+ fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
122
+ } catch {
123
+ // ignore
124
+ }
125
+ }
126
+
127
+ function sample() {
128
+ let heap
129
+ try {
130
+ heap = v8.getHeapStatistics()
131
+ } catch {
132
+ heap = { heap_size_limit: 0, used_heap_size: 0, total_heap_size: 0 }
133
+ }
134
+ const usage = process.memoryUsage()
135
+ const heapLimit = Number(heap.heap_size_limit) > 0 ? Number(heap.heap_size_limit) : 4 * 1024 * 1024 * 1024
136
+ watchdogState.thresholds = thresholdsFor(heapLimit)
137
+ const heapUsed = Number(usage.heapUsed) > 0 ? Number(usage.heapUsed) : Number(heap.used_heap_size) || 0
138
+ const waterline = classifyWaterline(heapUsed, watchdogState.thresholds)
139
+ const previous = watchdogState.waterline
140
+ const record = {
141
+ t: new Date().toISOString(),
142
+ heapUsed,
143
+ heapTotal: Number(usage.heapTotal) || Number(heap.total_heap_size) || 0,
144
+ external: Number(usage.external) || 0,
145
+ rss: Number(usage.rss) || 0,
146
+ heapLimit,
147
+ waterline,
148
+ }
149
+ watchdogState.latest = record
150
+ watchdogState.waterline = waterline
151
+ watchdogState.samples.push(record)
152
+ if (watchdogState.samples.length > MAX_SAMPLES) {
153
+ watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
154
+ }
155
+ if (waterline !== previous && LEVEL_RANK[waterline] > LEVEL_RANK[previous]) {
156
+ const incident = appendIncident({
157
+ kind: 'waterline',
158
+ level: waterline,
159
+ heapUsed,
160
+ heapLimit,
161
+ detail: `heap ${formatBytes(heapUsed)} / limit ${formatBytes(heapLimit)}`,
162
+ })
163
+ log.warn(`[ai-prison-watchdog] waterline ${waterline}: ${incident.detail}(observe 模式,不关闭插件)`)
164
+ persist(true)
165
+ }
166
+ }
167
+
168
+ /** target -> { heapBefore } for operations currently in flight. */
169
+ const inflight = new Map()
170
+
171
+ function onOperation(operation) {
172
+ try {
173
+ if (!operation || typeof operation !== 'object') return
174
+ const target = typeof operation.target === 'string' && operation.target ? operation.target : null
175
+ if (!target || operation.reason === 'remove') {
176
+ if (operation.phase === 'settled' && target) {
177
+ watchdogState.operations.delete(target)
178
+ }
179
+ return
180
+ }
181
+ const entry = watchdogState.operations.get(target) || {
182
+ count: 0,
183
+ estimateMB: 0,
184
+ lastAt: null,
185
+ version: operation.version || null,
186
+ lastApplication: null,
187
+ }
188
+ if (operation.phase === 'started') {
189
+ inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
190
+ entry.lastAt = operation.time || entry.lastAt
191
+ watchdogState.operations.set(target, entry)
192
+ return
193
+ }
194
+ if (operation.phase === 'settled') {
195
+ const weight = operationWeight(operation)
196
+ if (weight > 0 && operation.application !== 'failed') {
197
+ entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
198
+ }
199
+ const before = inflight.get(operation.id)
200
+ inflight.delete(operation.id)
201
+ if (before && watchdogState.latest && before.heapBefore > 0) {
202
+ const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
203
+ entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
204
+ }
205
+ entry.lastAt = operation.time || entry.lastAt
206
+ entry.version = operation.version || entry.version
207
+ entry.lastApplication = operation.application || null
208
+ watchdogState.operations.set(target, entry)
209
+ const thresholds = watchdogState.thresholds
210
+ if (thresholds && entry.estimateMB >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
211
+ appendIncident({
212
+ kind: 'plugin-estimate',
213
+ target,
214
+ estimateMB: entry.estimateMB,
215
+ level: entry.estimateMB >= Math.round(thresholds.singleBlock / (1024 * 1024)) ? 'block' : 'warn',
216
+ detail: `${target} 估算 ${entry.estimateMB} MB(observe 模式,仅提醒)`,
217
+ })
218
+ }
219
+ persist(true)
220
+ }
221
+ } catch (error) {
222
+ watchdogState.degraded = `operation handler: ${String((error && error.message) || error)}`
223
+ }
224
+ }
225
+
226
+ function readCrashLogs() {
227
+ const logsDir = resolveLogsDir()
228
+ let entries
229
+ try {
230
+ entries = fs.readdirSync(logsDir, { withFileTypes: true })
231
+ } catch {
232
+ return
233
+ }
234
+ let newest = watchdogState.lastCrashScan
235
+ for (const entry of entries) {
236
+ if (!entry.isFile() || !/^crash-.*-host\.log$/.test(entry.name)) continue
237
+ const file = path.join(logsDir, entry.name)
238
+ let stat
239
+ try {
240
+ stat = fs.statSync(file)
241
+ } catch {
242
+ continue
243
+ }
244
+ if (stat.mtimeMs <= watchdogState.lastCrashScan) continue
245
+ const parsed = parseCrashLog(readHead(file, CRASH_HEAD_BYTES))
246
+ if (!parsed.valid) continue
247
+ appendIncident({
248
+ kind: 'crash',
249
+ file: entry.name,
250
+ time: parsed.time,
251
+ phase: parsed.phase,
252
+ hostExitCode: parsed.hostExitCode,
253
+ oom: parsed.oom,
254
+ detail: parsed.oom ? 'JavaScript heap out of memory' : `host exited with ${parsed.hostExitCode ?? '?'}`,
255
+ })
256
+ if (stat.mtimeMs > newest) newest = stat.mtimeMs
257
+ }
258
+ if (newest > watchdogState.lastCrashScan) {
259
+ watchdogState.lastCrashScan = newest
260
+ persist(true)
261
+ }
262
+ }
263
+
264
+ // Sampler (P0: observe only).
265
+ try {
266
+ if (typeof ctx.effect === 'function') {
267
+ ctx.effect(() => {
268
+ sample()
269
+ const timer = setInterval(sample, SAMPLE_MS)
270
+ return () => clearInterval(timer)
271
+ }, 'ai-prison-watchdog: sampler')
272
+ } else {
273
+ sample()
274
+ setInterval(sample, SAMPLE_MS)
275
+ }
276
+ } catch (error) {
277
+ watchdogState.degraded = `sampler: ${String((error && error.message) || error)}`
278
+ }
279
+
280
+ // Plugin-operation accounting.
281
+ try {
282
+ if (typeof ctx.on === 'function') {
283
+ if (typeof ctx.effect === 'function') {
284
+ ctx.effect(() => ctx.on('plugin-manager/operation', onOperation), 'ai-prison-watchdog: operations')
285
+ } else {
286
+ ctx.on('plugin-manager/operation', onOperation)
287
+ }
288
+ }
289
+ } catch (error) {
290
+ watchdogState.degraded = `operations: ${String((error && error.message) || error)}`
291
+ }
292
+
293
+ // Read-only HTTP snapshot for the panel.
294
+ try {
295
+ if (typeof ctx.inject === 'function') {
296
+ ctx.inject(['connection'], (child) => {
297
+ try {
298
+ child.effect(
299
+ () =>
300
+ child.connection.fetch.register({
301
+ path: '/api/ai-prison/watchdog/status',
302
+ methods: ['GET'],
303
+ requestBody: 'buffered',
304
+ fetch: async () =>
305
+ Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
306
+ }),
307
+ 'ai-prison-watchdog: status api',
308
+ )
309
+ } catch (error) {
310
+ watchdogState.degraded = `status api: ${String((error && error.message) || error)}`
311
+ }
312
+ })
313
+ }
314
+ } catch (error) {
315
+ watchdogState.degraded = `connection: ${String((error && error.message) || error)}`
316
+ }
317
+
318
+ log.info(`[ai-prison-watchdog] observe 模式已启动(数据目录 ${dataDir})`)
319
+ return {
320
+ snapshot: watchdogSnapshot,
321
+ sample,
322
+ readCrashLogs,
323
+ }
324
+ }
325
+
326
+ /** Serialisable snapshot shared by the tool and the panel route. */
327
+ export function watchdogSnapshot() {
328
+ const s = watchdogState
329
+ return {
330
+ ok: Boolean(s.startedAt),
331
+ mode: s.mode,
332
+ startedAt: s.startedAt,
333
+ dataDir: s.dataDir,
334
+ degraded: s.degraded,
335
+ heap: s.latest,
336
+ thresholds: s.thresholds,
337
+ waterline: s.waterline,
338
+ samples: s.samples.slice(-30),
339
+ operations: topOperations(s.operations, 10),
340
+ incidents: s.incidents.slice(-20),
341
+ generatedAt: new Date().toISOString(),
342
+ }
343
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Shared in-process state of the AI Prison watchdog. The watchdog loader row
3
+ * writes it; the panel tool and the HTTP route read it. Same package, same Node
4
+ * process, so one module instance is enough (no service plumbing needed).
5
+ */
6
+ export const watchdogState = {
7
+ mode: 'observe',
8
+ startedAt: null,
9
+ dataDir: null,
10
+ config: {},
11
+ /** Latest metrics sample. */
12
+ latest: null,
13
+ /** Ring of recent metrics samples (oldest first). */
14
+ samples: [],
15
+ thresholds: null,
16
+ waterline: 'ok',
17
+ /** target -> { count, estimateMB, lastAt, version, lastApplication } */
18
+ operations: new Map(),
19
+ /** Recent incidents (newest last), capped. */
20
+ incidents: [],
21
+ /** Last crash-log scan marker (ms). */
22
+ lastCrashScan: 0,
23
+ /** Non-fatal degradation reason, if any. */
24
+ degraded: null,
25
+ }
26
+
27
+ export const MAX_SAMPLES = 120
28
+ export const MAX_INCIDENTS = 200
29
+
30
+ export function resetWatchdogState(overrides = {}) {
31
+ watchdogState.mode = 'observe'
32
+ watchdogState.startedAt = null
33
+ watchdogState.dataDir = null
34
+ watchdogState.config = {}
35
+ watchdogState.latest = null
36
+ watchdogState.samples = []
37
+ watchdogState.thresholds = null
38
+ watchdogState.waterline = 'ok'
39
+ watchdogState.operations = new Map()
40
+ watchdogState.incidents = []
41
+ watchdogState.lastCrashScan = 0
42
+ watchdogState.degraded = null
43
+ Object.assign(watchdogState, overrides)
44
+ return watchdogState
45
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.1.3",
3
+ "version": "1.2.0",
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",
@@ -37,11 +37,13 @@
37
37
  "./client": "./client.js",
38
38
  "./package.json": "./package.json",
39
39
  "./locale/*.json": "./locale/*.json",
40
- "./icon": "./icon.svg"
40
+ "./icon": "./icon.svg",
41
+ "./watchdog": "./watchdog.js"
41
42
  },
42
43
  "files": [
43
44
  "index.js",
44
45
  "client.js",
46
+ "watchdog.js",
45
47
  "lib/*.js",
46
48
  "cordis.patch.yml",
47
49
  "locale/*.json",
package/watchdog.js ADDED
@@ -0,0 +1,20 @@
1
+ import { createWatchdog } from './lib/watchdog-runtime.js'
2
+
3
+ /**
4
+ * AI Prison watchdog loader row (P0: observe only).
5
+ *
6
+ * It samples the host heap, accounts plugin operations, reads recent host crash
7
+ * logs and serves a read-only snapshot at /api/ai-prison/watchdog/status.
8
+ * It never enables or disables a plugin: enforcement stays in later phases until
9
+ * the design is confirmed.
10
+ */
11
+ export function apply(ctx, config = {}) {
12
+ const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined
13
+ try {
14
+ createWatchdog(ctx, config, logger || {})
15
+ } catch (error) {
16
+ const message = String((error && error.stack) || error)
17
+ if (logger && typeof logger.warn === 'function') logger.warn(`[ai-prison-watchdog] 启动失败:${message}`)
18
+ else console.warn('[ai-prison-watchdog] 启动失败', message)
19
+ }
20
+ }