@twinsearth/ai-prison-dsh-plugin 1.2.0 → 1.3.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,66 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.3.0] — 2026-11-18
6
+
7
+ ### Added — P1 enforcement (requirements 2, 3, 4 dry-run, 5)
8
+
9
+ - **Memory waterline enforcement**: warn 3 GB, pause 3.9 GB (needs a panel
10
+ second confirmation, 10-minute grace), strong warning 4 GB, freeze 5 GB on a
11
+ 6 GB host. Thresholds stay cap-relative on a 4 GB host. Hysteresis keeps a
12
+ frozen host frozen until the heap drops below the block line minus 300 MB.
13
+ - **Hot-operation jail (requirement 2)**: `plugin-manager/operation` settled
14
+ records are counted per target (install/remove = 1, enable = 1, disable = 0.5,
15
+ failed/cancelled ignored, base bundles and the watchdog itself exempt). More
16
+ than five in one run auto-disables the target through
17
+ `pluginManager.setBundleEnabled`, quarantines it for the rest of the run and
18
+ audits every step. Quarantine is released by restart or by the panel
19
+ "Release" action; the agent-facing `plugin_manager` tool is denied while a
20
+ target is jailed.
21
+ - **Tool guard**: frozen/paused states deny mutating `plugin_manager` actions
22
+ with a reason (read-only actions stay allowed; the panel keeps release
23
+ actions for the Top5 close buttons).
24
+ - **Crash attribution (requirement 3, dry-run)**: new crash logs are parsed for
25
+ `hostRunId`; the plugin-operation journal is matched by that run id and the
26
+ last changed plugin is picked (in-flight install/enable first, then the latest
27
+ settled install, then the latest settled enable). The result is recorded as an
28
+ L1 plan and an incident; nothing is closed until the user confirms enforcement.
29
+ - **Baseline (requirement 4, dry-run)**: a clean run records its enabled bundle
30
+ set after 60 s without crashes, waterline trouble or quarantine; escalation
31
+ counters L1→L2→L3 persist across restarts.
32
+ - **Panel**: new "Enforcement" card shows the freeze banner, pause confirmation,
33
+ quarantine list with release buttons, the memory Top5 with "close now" buttons
34
+ and the latest dry-run crash plans.
35
+ - **Tool**: `ai_prison_watchdog_status` now reports enforcement state,
36
+ quarantine, Top5, plans and escalation.
37
+
38
+ ### Notes
39
+
40
+ - Automatic disable only uses the plugin manager service; no profile file is
41
+ edited and no plugin code is loaded or unloaded by the watchdog.
42
+ - Top5 numbers are startup-budget + operation-delta estimates, labelled as such;
43
+ no heap snapshot is taken near the limit.
44
+
45
+ ## [1.2.1] — 2026-11-18
46
+ ## [1.2.1] — 2026-11-18
47
+
48
+ ### Fixed
49
+
50
+ - **Watchdog row crashed before its sampler started**: `readCrashLogs()` ran during
51
+ setup and called `persist()` while `let lastFlush` was still in its temporal dead
52
+ zone, so the row threw a `ReferenceError` after recording crash history but before
53
+ registering the sampler, the operation listener and the status route. The value is now
54
+ declared before the first scan, `readCrashLogs` is wrapped defensively, and the
55
+ runtime exposes a `dispose()` used by tests.
56
+ - Watchdog state directory and crash-log directory are now injectable
57
+ (`config.dataDir` / `config.logsDir`) so runtime tests stay hermetic.
58
+
59
+ ### Tests
60
+
61
+ - New `test/watchdog-runtime.test.mjs`: heap sampling, crash-fixture parsing and
62
+ persistence, plugin-operation counting/estimation, failed-operation and removal
63
+ handling, all against temporary directories.
64
+
5
65
  ## [1.2.0] — 2026-11-18
6
66
 
7
67
  ### Added — P0 memory watchdog (observe mode)
package/client.js CHANGED
@@ -12,6 +12,7 @@ window.__ModuleLoader__.load({
12
12
  const STATUS_URL = 'api/ai-prison/status'
13
13
  const RUN_URL = 'api/ai-prison/run'
14
14
  const WATCHDOG_URL = 'api/ai-prison/watchdog/status'
15
+ const WATCHDOG_ACTION_URL = 'api/ai-prison/watchdog/action'
15
16
 
16
17
  const DICTS = {
17
18
  en: {
@@ -284,6 +285,15 @@ window.__ModuleLoader__.load({
284
285
  })
285
286
  }
286
287
 
288
+
289
+ function postWatchdogAction(action, target) {
290
+ return fetch(new URL(WATCHDOG_ACTION_URL, document.baseURI), {
291
+ method: 'POST',
292
+ credentials: 'same-origin',
293
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
294
+ body: JSON.stringify({ action, target }),
295
+ }).then((response) => response.json())
296
+ }
287
297
  function waterlineText(level) {
288
298
  if (level === 'block') return t('waterline.block')
289
299
  if (level === 'pause') return t('waterline.pause')
@@ -397,6 +407,50 @@ window.__ModuleLoader__.load({
397
407
  )
398
408
  }
399
409
 
410
+ function EnforceCard({ watchdog, refresh }) {
411
+ if (!watchdog || !watchdog.ok) return null
412
+ const act = (name, target, prompt) => {
413
+ if (prompt && !window.confirm(prompt)) return
414
+ postWatchdogAction(name, target).then(() => refresh()).catch(() => refresh())
415
+ }
416
+ const frozen = Boolean(watchdog.frozenAt) || watchdog.waterline === 'frost'
417
+ const paused = Boolean(watchdog.pausedAt) || watchdog.waterline === 'pause'
418
+ const grace = Number.isFinite(watchdog.graceUntil) && Date.now() < watchdog.graceUntil
419
+ const quarantine = Array.isArray(watchdog.quarantine) ? watchdog.quarantine : []
420
+ const topFive = Array.isArray(watchdog.topFive) ? watchdog.topFive : []
421
+ const plans = Array.isArray(watchdog.plans) ? watchdog.plans.slice(-2).reverse() : []
422
+ 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 }
423
+ return h('section', { style: C.card },
424
+ h('div', { style: C.cardHead }, t('watchdog.enforceTitle'), h('span', { style: { ...C.chip, marginLeft: 8 } }, watchdog.enforce ? t('watchdog.enforceOn') : t('watchdog.observeOnly'))),
425
+ frozen ? h('p', { style: { color: C.error.color, fontSize: 12.5, margin: '0 0 8px' } }, t('watchdog.freezeHint', { level: watchdog.waterline })) : null,
426
+ paused && !grace ? h('div', { style: { margin: '0 0 10px' } }, h('button', { style: { ...button, padding: '6px 12px' }, onClick: () => act('confirm-pause') }, t('watchdog.confirmPause'))) : null,
427
+ h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.quarantine')),
428
+ quarantine.length === 0
429
+ ? h('p', { style: { ...C.muted, fontSize: 12, margin: '0 0 10px' } }, t('watchdog.noQuarantine'))
430
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 10 } },
431
+ quarantine.map((entry) => h('div', { key: entry.target, style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
432
+ h('span', { style: { ...C.mono, fontSize: 12, wordBreak: 'break-all' } }, entry.target + ' · ' + entry.reason + ' · ' + entry.level),
433
+ h('button', { style: button, onClick: () => act('release', entry.target, '假释 ' + entry.target + ' ?') }, t('watchdog.release')),
434
+ ))),
435
+ topFive.length === 0 ? null : h('div', null,
436
+ h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.topFive', { n: topFive.length })),
437
+ h('table', { style: C.table },
438
+ h('tbody', null, topFive.map((row) => h('tr', { key: row.target },
439
+ h('td', { style: { ...C.td, ...C.mono, fontSize: 11.5, wordBreak: 'break-all' } }, row.target),
440
+ h('td', { style: C.td }, row.estimateMB + ' MB'),
441
+ h('td', { style: C.td }, h('button', { style: button, onClick: () => act('close', row.target, '立即关闭 ' + row.target + ' ?') }, t('watchdog.close'))),
442
+ ))),
443
+ ),
444
+ ),
445
+ plans.length === 0 ? null : h('div', { style: { marginTop: 10 } },
446
+ h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.plans')),
447
+ plans.map((plan) => h('div', { key: plan.at, style: { ...C.mono, fontSize: 11.5, wordBreak: 'break-word' } },
448
+ plan.at + ' · ' + plan.level + ' · ' + (plan.target || 'unattributed') + (plan.inFlight ? ' (in-flight)' : '') + (plan.crash ? ' · ' + (plan.crash.oom ? 'OOM' : 'exit ' + plan.crash.hostExitCode) : ''))),
449
+ ),
450
+ watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
451
+ )
452
+ }
453
+
400
454
  function MatrixCard({ levels }) {
401
455
  if (!Array.isArray(levels) || levels.length === 0) {
402
456
  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')))
@@ -535,25 +589,18 @@ window.__ModuleLoader__.load({
535
589
  return () => clearInterval(timer)
536
590
  }, [load])
537
591
 
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
- }
592
+ const refreshWatchdog = React.useCallback(() => {
593
+ fetchWatchdog()
594
+ .then((payload) => setWatchdog(payload))
595
+ .catch(() => setWatchdog(null))
555
596
  }, [])
556
597
 
598
+ React.useEffect(() => {
599
+ refreshWatchdog()
600
+ const timer = setInterval(refreshWatchdog, 15000)
601
+ return () => clearInterval(timer)
602
+ }, [refreshWatchdog])
603
+
557
604
  const runAction = React.useCallback(
558
605
  (action) => {
559
606
  setBusy(action)
@@ -606,6 +653,7 @@ window.__ModuleLoader__.load({
606
653
  }),
607
654
  h(MemoryCard, { watchdog }),
608
655
  h(PrisonCard, { watchdog }),
656
+ h(EnforceCard, { watchdog, refresh: refreshWatchdog }),
609
657
  h(
610
658
  'p',
611
659
  { style: { ...C.muted, fontSize: 12, margin: '2px 0 0', display: 'flex', gap: 12, flexWrap: 'wrap' } },
package/lib/tools.js CHANGED
@@ -164,7 +164,7 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
164
164
  register({
165
165
  name: 'ai_prison_watchdog_status',
166
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.',
167
+ 'Read the AI Prison watchdog snapshot (P1 enforce mode): heap waterline (warn 3 GB / pause 3.9 GB / freeze 5 GB on a 6 GB host), per-plugin hot-operation counts and heap estimates, the plugin prison with quarantined targets and release state, the memory Top5, dry-run crash escalation plans (L1-L3) and recent incidents. Enforcement auto-closes a plugin after more than five hot operations in one run; the tool itself never changes a plugin.',
168
168
  parameters: {},
169
169
  output: stringOutput,
170
170
  async execute() {
@@ -202,9 +202,22 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
202
202
  opBlock: formatBytes(snapshot.thresholds.opBlock),
203
203
  }
204
204
  : null,
205
+ enforce: snapshot.enforce,
206
+ strongWarn: snapshot.strongWarn,
207
+ pausedAt: snapshot.pausedAt,
208
+ graceUntil: snapshot.graceUntil,
209
+ frozenAt: snapshot.frozenAt,
210
+ topFive: snapshot.topFive,
211
+ quarantine: snapshot.quarantine,
212
+ plans: snapshot.plans,
213
+ escalation: snapshot.escalation,
214
+ baselineAt: snapshot.baseline ? snapshot.baseline.at : null,
215
+ budgets: snapshot.budgets,
205
216
  operations: snapshot.operations,
206
217
  incidents: snapshot.incidents,
207
- note: 'observe 模式:仅观察与记录,不自动关闭任何插件。',
218
+ note: snapshot.enforce
219
+ ? 'enforce 模式:热操作 > 5 次自动关闭;3.9GB 暂停需二次确认,5GB 冻结插件操作。'
220
+ : 'observe 模式:仅观察与记录,不自动关闭任何插件。',
208
221
  })
209
222
  },
210
223
  })
@@ -1,11 +1,21 @@
1
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.
2
+ * Pure policy math for the AI Prison watchdog (P1).
3
+ *
4
+ * Threshold layout (derived from the real heap limit, absolute values clamped):
5
+ * warn 3.0 GB -> yellow waterline
6
+ * pause 3.9 GB -> additive plugin operations need a second confirmation
7
+ * opWarn 4.0 GB -> red warning once the user continued through pause
8
+ * block 5.0 GB -> freeze every plugin operation except the release whitelist
9
+ * On a 4 GB host the same ratios map down (2.99 / 3.60 / 4.09 / 3.81 GB).
5
10
  */
6
11
  export const MB = 1024 * 1024
7
12
  export const GB = 1024 * MB
8
13
 
14
+ export const FREEZE_MARGIN = 0.3 * GB
15
+ export const HOT_OP_LIMIT = 5
16
+ export const ADDITIVE_ACTIONS = new Set(['set_plugin', 'set_bundle', 'install_bundle', 'remove_bundle', 'set_version_exemption'])
17
+ export const READONLY_ACTIONS = new Set(['list_plugins', 'list_bundles', 'list_version_exemptions'])
18
+
9
19
  /** Thresholds derived from the host heap limit (absolute values clamped to the cap). */
10
20
  export function thresholdsFor(heapLimitBytes) {
11
21
  const limit = Number(heapLimitBytes) > 0 ? Number(heapLimitBytes) : 4 * GB
@@ -22,15 +32,23 @@ export function thresholdsFor(heapLimitBytes) {
22
32
  }
23
33
  }
24
34
 
25
- /** Waterline for the whole host: ok | warn | pause | block. */
26
- export function classifyWaterline(heapUsed, thresholds) {
35
+ /** Waterline for the whole host, with the active level to keep hysteresis. */
36
+ export function classifyWaterline(heapUsed, thresholds, previous = 'ok') {
27
37
  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'
38
+ const above = (value, guard) => heapUsed + guard >= value
39
+ if (previous === 'frost' && heapUsed + FREEZE_MARGIN >= thresholds.totalBlock) return 'frost'
40
+ if (heapUsed + FREEZE_MARGIN >= thresholds.totalBlock) return 'frost'
41
+ if (previous === 'pause' && heapUsed + FREEZE_MARGIN >= thresholds.totalPause) return 'pause'
42
+ if (heapUsed + FREEZE_MARGIN >= thresholds.totalPause) return 'pause'
43
+ if (heapUsed + FREEZE_MARGIN >= thresholds.totalWarn) return 'warn'
31
44
  return 'ok'
32
45
  }
33
46
 
47
+ /** True when additive plugin operations must be denied at this waterline. */
48
+ export function operationsDenied(level) {
49
+ return level === 'pause' || level === 'frost'
50
+ }
51
+
34
52
  /** How much one plugin operation counts toward the per-target hot-operation limit. */
35
53
  export function operationWeight(operation) {
36
54
  if (!operation || typeof operation !== 'object') return 0
@@ -49,14 +67,63 @@ export function mergeEstimate(previous, next, alpha = 0.5) {
49
67
  return Math.round(before * (1 - alpha) + value * alpha)
50
68
  }
51
69
 
70
+ /**
71
+ * Tool guard decision for the agent-facing plugin_manager tool.
72
+ * @returns {{ reason: string, info?: { name: string, code: string } } | undefined}
73
+ */
74
+ export function decideToolGuard(execution, state) {
75
+ if (!execution || execution.name !== 'plugin_manager') return undefined
76
+ const args = execution.arguments && typeof execution.arguments === 'object' ? execution.arguments : {}
77
+ const action = typeof args.action === 'string' ? args.action : ''
78
+ if (!action) return undefined
79
+ const target = typeof args.target === 'string' ? args.target : null
80
+ const quarantine = target && state.quarantine instanceof Map ? state.quarantine.get(target) : null
81
+ if (quarantine && action !== 'list_plugins' && action !== 'list_bundles') {
82
+ return {
83
+ reason: `插件 ${target} 在 AI 监狱(${quarantine.reason},级别 ${quarantine.level})。需要用户在本机面板点击"假释"后才能操作。`,
84
+ info: { name: 'ai-prison-quarantine', code: 'quarantined' },
85
+ }
86
+ }
87
+ if (READONLY_ACTIONS.has(action)) return undefined
88
+ if (!ADDITIVE_ACTIONS.has(action)) return undefined
89
+ const level = state.waterline
90
+ if (level === 'frost') {
91
+ return {
92
+ reason: `堆水位 ${level}(≥${formatBytes(state.thresholds ? state.thresholds.totalBlock : 0)})已冻结所有插件操作。请先在面板"内存看护"里关闭 Top5 插件释放内存,或重启 DSH。`,
93
+ info: { name: 'ai-prison-freeze', code: 'memory-frozen' },
94
+ }
95
+ }
96
+ if (level === 'pause') {
97
+ const grace = Number.isFinite(state.graceUntil) ? state.graceUntil : 0
98
+ if (!(Date.now() < grace)) {
99
+ return {
100
+ reason: `堆水位 ${level}(≥${formatBytes(state.thresholds ? state.thresholds.totalPause : 0)})已暂停插件操作,需要用户二次确认。请在面板"内存看护"里确认继续,或重启 DSH。`,
101
+ info: { name: 'ai-prison-pause', code: 'memory-paused' },
102
+ }
103
+ }
104
+ }
105
+ return undefined
106
+ }
107
+
108
+ /** A panel/UI-initiated operation may run only for the release whitelist while frozen. */
109
+ export function allowedDuringFreeze(action) {
110
+ return action === 'list_plugins' || action === 'list_bundles' || action === 'list_version_exemptions'
111
+ }
112
+
113
+ /** Should this crash attribution candidate be quarantined? */
114
+ export function hotOperationTriggered(count) {
115
+ return Number(count) > HOT_OP_LIMIT
116
+ }
117
+
52
118
  /** Parse the header block of a DSH desktop host crash log. */
53
119
  export function parseCrashLog(text) {
54
120
  const source = String(text || '')
55
- const header = source.slice(0, 4000)
121
+ const header = source.slice(0, 6000)
56
122
  const time = /^time:\s*(.+)$/m.exec(header)
57
123
  const phase = /^phase:\s*(.+)$/m.exec(header)
58
124
  const exit = /exited with (\d+)/.exec(source)
59
125
  const oom = /heap out of memory|Allocation failed|MarkCompactCollector|Scavenger:/i.test(source)
126
+ const runId = /hostRunId:\s*'([^']+)'/.exec(source)
60
127
  const fatal = /FATAL ERROR/.test(source)
61
128
  return {
62
129
  valid: Boolean(time || exit || fatal),
@@ -64,10 +131,82 @@ export function parseCrashLog(text) {
64
131
  phase: phase ? phase[1].trim() : null,
65
132
  hostExitCode: exit ? Number(exit[1]) : null,
66
133
  oom,
134
+ hostRunId: runId ? runId[1] : null,
67
135
  }
68
136
  }
69
137
 
70
- /** A compact top-N view of the per-target accounting, biggest estimate first. */
138
+ /**
139
+ * Attribute a crash to the last changed plugin.
140
+ *
141
+ * Preference order (per requirement 3, "only close the last installed plugin"):
142
+ * 1. an installation/enable that was still in flight when the host died;
143
+ * 2. the latest settled install/update in the same host run;
144
+ * 3. the latest settled enable in the same host run.
145
+ * Disable/remove records are never candidates. A run id mismatch or an empty
146
+ * candidate list means "unknown": the caller records it and does not kill.
147
+ */
148
+ export function attributeCrash(journalRecords, crash) {
149
+ const runId = crash && crash.hostRunId
150
+ const records = Array.isArray(journalRecords) ? journalRecords : []
151
+ const inRun = records.filter((record) => !runId || record.runId === runId)
152
+ const positive = (operation) =>
153
+ operation
154
+ && (operation.stage === 'install' || (operation.stage === 'enable' && operation.enabled !== false))
155
+ && operation.target
156
+ const started = new Map()
157
+ for (const record of inRun) {
158
+ const operation = record.operation
159
+ if (!positive(operation)) continue
160
+ if (operation.phase === 'started') started.set(operation.id, operation)
161
+ if (operation.phase === 'settled') started.delete(operation.id)
162
+ }
163
+ const inFlight = [...started.values()].sort((a, b) => String(b.time).localeCompare(String(a.time)))[0]
164
+ const settled = inRun
165
+ .map((record) => record.operation)
166
+ .filter((operation) => positive(operation) && operation.phase === 'settled')
167
+ .sort((a, b) => String(b.time).localeCompare(String(a.time)))
168
+ const latestInstall = settled.find((operation) => operation.stage === 'install')
169
+ const latestEnable = settled.find((operation) => operation.stage === 'enable')
170
+ const candidates = []
171
+ if (inFlight) candidates.push({ target: inFlight.target, inFlight: true, reason: inFlight.reason, time: inFlight.time, version: inFlight.version || null })
172
+ for (const operation of [latestInstall, latestEnable]) {
173
+ if (operation && !candidates.some((candidate) => candidate.target === operation.target)) {
174
+ candidates.push({ target: operation.target, inFlight: false, reason: operation.reason, time: operation.time, version: operation.version || null })
175
+ }
176
+ }
177
+ return {
178
+ hostRunId: runId || null,
179
+ candidates,
180
+ picked: candidates.length > 0 ? candidates[0] : null,
181
+ reason: candidates.length === 0 ? 'no candidate in this host run (missing or incomplete operation history)' : 'last changed plugin in the crashed host run',
182
+ }
183
+ }
184
+
185
+ /** Difference between current bundle rows and the recorded clean baseline. */
186
+ export function diffBaseline(rows, baseline) {
187
+ const baselineBundles = baseline && Array.isArray(baseline.bundles) ? baseline.bundles : []
188
+ const known = new Map(baselineBundles.map((row) => [row.name, String(row.version || '')]))
189
+ const changed = []
190
+ for (const row of Array.isArray(rows) ? rows : []) {
191
+ const version = String(row.version || '')
192
+ if (!row.enabled) continue
193
+ const before = known.get(row.name)
194
+ if (before === undefined) changed.push({ name: row.name, version, kind: 'added' })
195
+ else if (before !== version) changed.push({ name: row.name, version, before, kind: 'updated' })
196
+ }
197
+ const level = escalationLevel(0)
198
+ return { changed, unknown: !baseline, level }
199
+ }
200
+
201
+ /** Escalation level from recent crash count (dry-run plans in P1). */
202
+ export function escalationLevel(crashCount) {
203
+ if (crashCount >= 3) return 'L3'
204
+ if (crashCount >= 2) return 'L2'
205
+ if (crashCount >= 1) return 'L1'
206
+ return 'L0'
207
+ }
208
+
209
+ /** Top-N view of per-target accounting, biggest estimate first. */
71
210
  export function topOperations(operations, limit = 5) {
72
211
  const rows = []
73
212
  for (const [target, entry] of operations instanceof Map ? operations : Object.entries(operations || {})) {
@@ -2,10 +2,16 @@ import fs from 'node:fs'
2
2
  import os from 'node:os'
3
3
  import path from 'node:path'
4
4
  import v8 from 'node:v8'
5
+ import crypto from 'node:crypto'
5
6
  import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
6
7
  import {
8
+ attributeCrash,
7
9
  classifyWaterline,
10
+ decideToolGuard,
11
+ diffBaseline,
12
+ escalationLevel,
8
13
  formatBytes,
14
+ hotOperationTriggered,
9
15
  mergeEstimate,
10
16
  operationWeight,
11
17
  parseCrashLog,
@@ -15,8 +21,18 @@ import {
15
21
 
16
22
  const SAMPLE_MS = 5_000
17
23
  const FLUSH_MS = 30_000
18
- const CRASH_HEAD_BYTES = 8 * 1024
19
- const LEVEL_RANK = { ok: 0, warn: 1, pause: 2, block: 3 }
24
+ const CRASH_HEAD_BYTES = 256 * 1024
25
+ const BASELINE_DELAY_MS = 60_000
26
+ const PAUSE_GRACE_MS = 10 * 60_000
27
+ const CRASH_WINDOW_MS = 10 * 60_000
28
+ const MAX_JOURNAL_RECORDS = 4000
29
+ const EXEMPT_TARGETS = new Set([
30
+ 'dsh-base',
31
+ 'dsh-web-app',
32
+ '@deepseek-ai/dsh-base',
33
+ '@deepseek-ai/dsh-web-app',
34
+ '@twinsearth/ai-prison-dsh-plugin',
35
+ ])
20
36
 
21
37
  function resolveProfileDir() {
22
38
  const fromEnv = typeof process.env.DSH_PROFILE_DIR === 'string' && process.env.DSH_PROFILE_DIR.trim()
@@ -30,6 +46,11 @@ function resolveLogsDir() {
30
46
  return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'logs')
31
47
  }
32
48
 
49
+ function resolveJournalDir() {
50
+ const roaming = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming')
51
+ return path.join(roaming, '@deepseek-ai', 'dsh-desktop', 'plugin-operations')
52
+ }
53
+
33
54
  function readHead(file, bytes) {
34
55
  let fd
35
56
  try {
@@ -50,16 +71,49 @@ function readHead(file, bytes) {
50
71
  }
51
72
  }
52
73
 
53
- /** Read-only watchdog runtime. It observes; it never enables or disables plugins. */
74
+ function readJournalRecords(journalDir) {
75
+ const records = []
76
+ for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
77
+ const file = path.join(journalDir, name)
78
+ let text = ''
79
+ try {
80
+ text = fs.readFileSync(file, 'utf8')
81
+ } catch {
82
+ continue
83
+ }
84
+ for (const line of text.split('\n').slice(-MAX_JOURNAL_RECORDS)) {
85
+ const trimmed = line.trim()
86
+ if (!trimmed) continue
87
+ try {
88
+ records.push(JSON.parse(trimmed))
89
+ } catch {
90
+ // ignore partial line
91
+ }
92
+ }
93
+ }
94
+ return records
95
+ }
96
+
97
+ /** Read-only watchdog runtime. Enforcement never touches plugin files, only the manager API. */
54
98
  export function createWatchdog(ctx, config = {}, logger = {}) {
55
99
  const profileDir = resolveProfileDir()
56
- const dataDir = path.join(profileDir, '.ai-prison-watchdog')
100
+ const dataDir = config.dataDir ? path.resolve(String(config.dataDir)) : path.join(profileDir, '.ai-prison-watchdog')
101
+ const logsDir = config.logsDir ? path.resolve(String(config.logsDir)) : resolveLogsDir()
102
+ const journalDir = config.journalDir ? path.resolve(String(config.journalDir)) : resolveJournalDir()
57
103
  const stateFile = path.join(dataDir, 'state.json')
58
104
  const incidentsFile = path.join(dataDir, 'incidents.jsonl')
105
+ const baselineFile = path.join(dataDir, 'baseline.json')
59
106
  const log = {
60
107
  info: (...args) => (typeof logger.info === 'function' ? logger.info(...args) : undefined),
61
108
  warn: (...args) => (typeof logger.warn === 'function' ? logger.warn(...args) : undefined),
62
109
  }
110
+ const refs = { manager: null, tools: null }
111
+ const cleanups = []
112
+ const effect = (fn, label) => {
113
+ const disposer = ctx.effect(fn, label)
114
+ if (typeof disposer === 'function') cleanups.push(disposer)
115
+ return disposer
116
+ }
63
117
 
64
118
  try {
65
119
  fs.mkdirSync(dataDir, { recursive: true })
@@ -67,22 +121,47 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
67
121
  watchdogState.degraded = `cannot create ${dataDir}: ${String((error && error.message) || error)}`
68
122
  }
69
123
 
70
- watchdogState.mode = 'observe'
124
+ watchdogState.mode = config.enforce === false ? 'observe' : 'enforce'
125
+ watchdogState.enforce = config.enforce !== false
71
126
  watchdogState.startedAt = new Date().toISOString()
127
+ watchdogState.runId = crypto.randomUUID()
72
128
  watchdogState.dataDir = dataDir
73
129
  watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
74
130
  watchdogState.lastCrashScan = 0
131
+ watchdogState.baseline = null
132
+ for (const plan of watchdogState.plans) plan.applied = false
75
133
 
134
+ let lastFlush = 0
76
135
  restoreState()
77
136
  readCrashLogs()
78
137
 
138
+ function persist(force = false) {
139
+ const now = Date.now()
140
+ if (!force && now - lastFlush < FLUSH_MS) return
141
+ lastFlush = now
142
+ const payload = {
143
+ startedAt: watchdogState.startedAt,
144
+ lastCrashScan: watchdogState.lastCrashScan,
145
+ incidents: watchdogState.incidents.slice(-50),
146
+ escalation: watchdogState.escalation,
147
+ baseline: watchdogState.baseline,
148
+ budgets: watchdogState.budgets,
149
+ }
150
+ try {
151
+ fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
152
+ } catch {
153
+ // ignore
154
+ }
155
+ }
156
+
79
157
  function restoreState() {
80
158
  try {
81
159
  const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
82
160
  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
- }
161
+ if (Array.isArray(parsed.incidents)) watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
162
+ if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
163
+ if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
164
+ if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
86
165
  } catch {
87
166
  // first run or unreadable state: start clean
88
167
  }
@@ -91,9 +170,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
91
170
  function appendIncident(incident) {
92
171
  const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
93
172
  watchdogState.incidents.push(record)
94
- if (watchdogState.incidents.length > MAX_INCIDENTS) {
95
- watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
96
- }
173
+ if (watchdogState.incidents.length > MAX_INCIDENTS) watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
97
174
  try {
98
175
  fs.appendFileSync(incidentsFile, `${JSON.stringify(record)}\n`)
99
176
  const stat = fs.statSync(incidentsFile)
@@ -102,28 +179,12 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
102
179
  fs.writeFileSync(incidentsFile, `${lines.join('\n')}\n`)
103
180
  }
104
181
  } catch {
105
- // auditing is best-effort in observe mode
182
+ // auditing is best-effort
106
183
  }
107
184
  return record
108
185
  }
109
186
 
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
-
187
+ // ---- memory waterline ----------------------------------------------------
127
188
  function sample() {
128
189
  let heap
129
190
  try {
@@ -133,10 +194,11 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
133
194
  }
134
195
  const usage = process.memoryUsage()
135
196
  const heapLimit = Number(heap.heap_size_limit) > 0 ? Number(heap.heap_size_limit) : 4 * 1024 * 1024 * 1024
136
- watchdogState.thresholds = thresholdsFor(heapLimit)
197
+ const thresholds = thresholdsFor(heapLimit)
198
+ watchdogState.thresholds = thresholds
137
199
  const heapUsed = Number(usage.heapUsed) > 0 ? Number(usage.heapUsed) : Number(heap.used_heap_size) || 0
138
- const waterline = classifyWaterline(heapUsed, watchdogState.thresholds)
139
200
  const previous = watchdogState.waterline
201
+ const waterline = classifyWaterline(heapUsed, thresholds, previous)
140
202
  const record = {
141
203
  t: new Date().toISOString(),
142
204
  heapUsed,
@@ -148,83 +210,180 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
148
210
  }
149
211
  watchdogState.latest = record
150
212
  watchdogState.waterline = waterline
213
+ watchdogState.strongWarn = waterline !== 'ok' && heapUsed >= thresholds.opWarn
151
214
  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]) {
215
+ if (watchdogState.samples.length > MAX_SAMPLES) watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
216
+
217
+ if (waterline === 'frost' && !watchdogState.frozenAt) {
218
+ watchdogState.frozenAt = record.t
156
219
  const incident = appendIncident({
157
- kind: 'waterline',
158
- level: waterline,
220
+ kind: 'freeze',
221
+ level: 'frost',
222
+ heapUsed,
223
+ heapLimit,
224
+ detail: `heap ${formatBytes(heapUsed)} ≥ block ${formatBytes(thresholds.totalBlock)}:冻结插件操作`,
225
+ })
226
+ log.warn(`[ai-prison-watchdog] ${incident.detail}`)
227
+ persist(true)
228
+ } else if (waterline === 'pause' && !watchdogState.pausedAt) {
229
+ watchdogState.pausedAt = record.t
230
+ appendIncident({
231
+ kind: 'pause',
232
+ level: 'pause',
159
233
  heapUsed,
160
234
  heapLimit,
161
- detail: `heap ${formatBytes(heapUsed)} / limit ${formatBytes(heapLimit)}`,
235
+ detail: `heap ${formatBytes(heapUsed)} ≥ pause ${formatBytes(thresholds.totalPause)}:插件操作需二次确认`,
162
236
  })
163
- log.warn(`[ai-prison-watchdog] waterline ${waterline}: ${incident.detail}(observe 模式,不关闭插件)`)
164
237
  persist(true)
238
+ } else if (waterline === 'warn' && previous !== 'warn' && previous === 'ok') {
239
+ appendIncident({ kind: 'waterline', level: 'warn', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ warn ${formatBytes(thresholds.totalWarn)}` })
240
+ }
241
+ if (waterline === 'ok') {
242
+ watchdogState.pausedAt = null
243
+ watchdogState.frozenAt = null
244
+ watchdogState.graceUntil = null
245
+ }
246
+ if (waterline === 'warn') {
247
+ watchdogState.frozenAt = null
248
+ watchdogState.graceUntil = null
249
+ }
250
+ if (watchdogState.strongWarn && waterline === 'pause') {
251
+ appendIncident({ kind: 'strong-warn', level: 'pause', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ 强警告 ${formatBytes(thresholds.opWarn)}` })
252
+ }
253
+ maybeWriteBaseline()
254
+ }
255
+
256
+ // ---- clean baseline (requirement 4, dry-run in P1) ----------------------
257
+ function maybeWriteBaseline() {
258
+ if (watchdogState.baseline && watchdogState.baseline.runId === watchdogState.runId) return
259
+ if (!watchdogState.startedAt) return
260
+ const age = Date.now() - Date.parse(watchdogState.startedAt)
261
+ if (age < BASELINE_DELAY_MS) return
262
+ if (watchdogState.waterline === 'pause' || watchdogState.waterline === 'frost') return
263
+ if (watchdogState.quarantine.size > 0) return
264
+ const recentCrash = watchdogState.incidents.some((incident) => incident.kind === 'crash' && Date.parse(incident.at || 0) >= Date.parse(watchdogState.startedAt))
265
+ if (recentCrash) return
266
+ void collectBaseline()
267
+ }
268
+
269
+ async function collectBaseline() {
270
+ const manager = refs.manager
271
+ if (!manager || typeof manager.listBundles !== 'function') return
272
+ try {
273
+ const rows = await manager.listBundles()
274
+ const bundles = rows
275
+ .filter((row) => row.enabled)
276
+ .map((row) => ({ name: row.name, version: String(row.version || ''), enabled: true }))
277
+ watchdogState.baseline = {
278
+ at: new Date().toISOString(),
279
+ runId: watchdogState.runId,
280
+ hostRunId: watchdogState.hostRunId || null,
281
+ bundles,
282
+ }
283
+ try {
284
+ fs.writeFileSync(baselineFile, `${JSON.stringify(watchdogState.baseline, null, 2)}\n`)
285
+ } catch {
286
+ // ignore
287
+ }
288
+ appendIncident({ kind: 'baseline', detail: `记录干净基线:${bundles.length} 个 bundle` })
289
+ persist(true)
290
+ } catch (error) {
291
+ watchdogState.degraded = `baseline: ${String((error && error.message) || error)}`
165
292
  }
166
293
  }
167
294
 
168
- /** target -> { heapBefore } for operations currently in flight. */
295
+ // ---- plugin operation accounting / hot-op jail (requirement 2) ----------
169
296
  const inflight = new Map()
170
297
 
171
298
  function onOperation(operation) {
172
299
  try {
173
300
  if (!operation || typeof operation !== 'object') return
174
301
  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
- }
302
+ if (!target) return
303
+ if ((watchdogState.suppressUntil.get(target) || 0) > Date.now()) return
304
+ const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
188
305
  if (operation.phase === 'started') {
189
306
  inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
190
307
  entry.lastAt = operation.time || entry.lastAt
191
308
  watchdogState.operations.set(target, entry)
192
309
  return
193
310
  }
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
- }
311
+ if (operation.phase !== 'settled') return
312
+ const weight = operationWeight(operation)
313
+ if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
314
+ entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
315
+ }
316
+ const before = inflight.get(operation.id)
317
+ inflight.delete(operation.id)
318
+ if (before && watchdogState.latest && before.heapBefore > 0) {
319
+ const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
320
+ entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
321
+ }
322
+ entry.lastAt = operation.time || entry.lastAt
323
+ entry.version = operation.version || entry.version
324
+ entry.lastApplication = operation.application || null
325
+ watchdogState.operations.set(target, entry)
326
+ if (operation.reason === 'remove' && operation.application === 'applied') {
327
+ watchdogState.operations.delete(target)
328
+ return
329
+ }
330
+ if (watchdogState.enforce && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target) && hotOperationTriggered(entry.count)) {
331
+ watchdogState.quarantine.set(target, {
332
+ reason: 'hot-ops',
333
+ level: 'L2',
334
+ at: new Date().toISOString(),
335
+ release: 'restart',
336
+ evidence: `本次运行内热操作计数 ${entry.count} > 5(安装/启用/热切换)`,
337
+ })
338
+ appendIncident({ kind: 'quarantine', target, level: 'L2', reason: 'hot-ops', detail: `热操作 ${entry.count} 次 > 5,自动关闭` })
219
339
  persist(true)
340
+ void disableTarget(target, 'hot-ops')
220
341
  }
342
+ persist(true)
221
343
  } catch (error) {
222
344
  watchdogState.degraded = `operation handler: ${String((error && error.message) || error)}`
223
345
  }
224
346
  }
225
347
 
348
+ async function disableTarget(target, reason) {
349
+ const manager = refs.manager
350
+ if (!manager || typeof manager.setBundleEnabled !== 'function') {
351
+ watchdogState.degraded = `disable ${target}: pluginManager unavailable`
352
+ return false
353
+ }
354
+ watchdogState.suppressUntil.set(target, Date.now() + 8000)
355
+ for (let attempt = 0; attempt < 2; attempt += 1) {
356
+ try {
357
+ const rows = typeof manager.listBundles === 'function' ? await manager.listBundles() : []
358
+ const row = rows.find((entry) => entry.name === target)
359
+ if (row && row.enabled === false) return true
360
+ await manager.setBundleEnabled(target, false)
361
+ appendIncident({ kind: 'close', target, reason, detail: `已自动关闭 ${target}(${reason})` })
362
+ return true
363
+ } catch (error) {
364
+ if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 500))
365
+ else {
366
+ appendIncident({ kind: 'close-failed', target, reason, detail: `自动关闭 ${target} 失败:${String((error && error.message) || error)}` })
367
+ watchdogState.degraded = `disable ${target}: ${String((error && error.message) || error)}`
368
+ return false
369
+ }
370
+ }
371
+ }
372
+ return false
373
+ }
374
+
375
+ function releaseTarget(target) {
376
+ const entry = watchdogState.quarantine.get(target)
377
+ if (!entry) return { ok: false, error: 'not quarantined' }
378
+ watchdogState.quarantine.delete(target)
379
+ watchdogState.suppressUntil.set(target, Date.now() + 5000)
380
+ appendIncident({ kind: 'release', target, detail: `用户假释 ${target}(原因 ${entry.reason})` })
381
+ persist(true)
382
+ return { ok: true }
383
+ }
384
+
385
+ // ---- crash attribution and dry-run plans (requirements 3 & 4) -----------
226
386
  function readCrashLogs() {
227
- const logsDir = resolveLogsDir()
228
387
  let entries
229
388
  try {
230
389
  entries = fs.readdirSync(logsDir, { withFileTypes: true })
@@ -232,6 +391,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
232
391
  return
233
392
  }
234
393
  let newest = watchdogState.lastCrashScan
394
+ const crashes = []
235
395
  for (const entry of entries) {
236
396
  if (!entry.isFile() || !/^crash-.*-host\.log$/.test(entry.name)) continue
237
397
  const file = path.join(logsDir, entry.name)
@@ -242,18 +402,49 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
242
402
  continue
243
403
  }
244
404
  if (stat.mtimeMs <= watchdogState.lastCrashScan) continue
245
- const parsed = parseCrashLog(readHead(file, CRASH_HEAD_BYTES))
405
+ const text = readHead(file, CRASH_HEAD_BYTES)
406
+ const parsed = parseCrashLog(text)
246
407
  if (!parsed.valid) continue
408
+ crashes.push({ file: entry.name, mtimeMs: stat.mtimeMs, parsed })
409
+ if (stat.mtimeMs > newest) newest = stat.mtimeMs
410
+ }
411
+ if (crashes.length === 0) return
412
+ const records = readJournalRecords(journalDir)
413
+ for (const crash of crashes) {
414
+ watchdogState.escalation.crashes.push(Date.now())
415
+ const recent = watchdogState.escalation.crashes.filter((at) => Date.now() - at <= CRASH_WINDOW_MS)
416
+ watchdogState.escalation.crashes = recent
417
+ const level = escalationLevel(recent.length)
418
+ watchdogState.escalation.level = level
419
+ const attribution = attributeCrash(records, crash.parsed)
420
+ watchdogState.hostRunId = crash.parsed.hostRunId || null
421
+ const plan = {
422
+ at: new Date().toISOString(),
423
+ level,
424
+ crash: { file: crash.file, time: crash.parsed.time, phase: crash.parsed.phase, oom: crash.parsed.oom, hostExitCode: crash.parsed.hostExitCode },
425
+ hostRunId: crash.parsed.hostRunId,
426
+ target: attribution.picked ? attribution.picked.target : null,
427
+ inFlight: attribution.picked ? Boolean(attribution.picked.inFlight) : false,
428
+ evidence: attribution.candidates,
429
+ reason: attribution.reason,
430
+ applied: false,
431
+ }
432
+ watchdogState.plans.push(plan)
433
+ if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
247
434
  appendIncident({
248
435
  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 ?? '?'}`,
436
+ file: crash.file,
437
+ time: crash.parsed.time,
438
+ phase: crash.parsed.phase,
439
+ hostExitCode: crash.parsed.hostExitCode,
440
+ oom: crash.parsed.oom,
441
+ level,
442
+ target: plan.target,
443
+ inFlight: plan.inFlight,
444
+ detail: plan.target
445
+ ? `崩溃归因:${plan.target}${plan.inFlight ? '(崩溃时操作仍在途)' : ''};${watchdogState.enforce ? 'enforce' : 'dry-run'}`
446
+ : '崩溃归因失败:本 run 无安装/启用记录,不自动关闭',
255
447
  })
256
- if (stat.mtimeMs > newest) newest = stat.mtimeMs
257
448
  }
258
449
  if (newest > watchdogState.lastCrashScan) {
259
450
  watchdogState.lastCrashScan = newest
@@ -261,27 +452,60 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
261
452
  }
262
453
  }
263
454
 
264
- // Sampler (P0: observe only).
455
+ // ---- registration --------------------------------------------------------
456
+ try {
457
+ if (typeof ctx.inject === 'function') {
458
+ ctx.inject(['pluginManager'], (child) => {
459
+ refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
460
+ })
461
+ }
462
+ } catch (error) {
463
+ watchdogState.degraded = `pluginManager inject: ${String((error && error.message) || error)}`
464
+ }
465
+
466
+ try {
467
+ if (typeof ctx.inject === 'function' && watchdogState.enforce) {
468
+ ctx.inject(['tools'], (child) => {
469
+ refs.tools = child.tools || null
470
+ try {
471
+ if (!child.tools || typeof child.tools.guard !== 'function') return
472
+ child.effect(
473
+ () =>
474
+ child.tools.guard((execution) => {
475
+ const denial = decideToolGuard(execution, watchdogState)
476
+ return denial ? { reason: denial.reason, info: denial.info } : undefined
477
+ }),
478
+ 'ai-prison-watchdog: tool guard',
479
+ )
480
+ } catch (error) {
481
+ watchdogState.degraded = `tool guard: ${String((error && error.message) || error)}`
482
+ }
483
+ })
484
+ }
485
+ } catch (error) {
486
+ watchdogState.degraded = `tools inject: ${String((error && error.message) || error)}`
487
+ }
488
+
265
489
  try {
490
+ const interval = Number(config.sampleMs) > 0 ? Number(config.sampleMs) : SAMPLE_MS
266
491
  if (typeof ctx.effect === 'function') {
267
- ctx.effect(() => {
492
+ effect(() => {
268
493
  sample()
269
- const timer = setInterval(sample, SAMPLE_MS)
494
+ const timer = setInterval(sample, interval)
270
495
  return () => clearInterval(timer)
271
496
  }, 'ai-prison-watchdog: sampler')
272
497
  } else {
273
498
  sample()
274
- setInterval(sample, SAMPLE_MS)
499
+ setInterval(sample, interval)
275
500
  }
276
501
  } catch (error) {
277
502
  watchdogState.degraded = `sampler: ${String((error && error.message) || error)}`
278
503
  }
279
504
 
280
- // Plugin-operation accounting.
281
505
  try {
282
506
  if (typeof ctx.on === 'function') {
283
507
  if (typeof ctx.effect === 'function') {
284
- ctx.effect(() => ctx.on('plugin-manager/operation', onOperation), 'ai-prison-watchdog: operations')
508
+ effect(() => ctx.on('plugin-manager/operation', onOperation), 'ai-prison-watchdog: operations')
285
509
  } else {
286
510
  ctx.on('plugin-manager/operation', onOperation)
287
511
  }
@@ -290,7 +514,6 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
290
514
  watchdogState.degraded = `operations: ${String((error && error.message) || error)}`
291
515
  }
292
516
 
293
- // Read-only HTTP snapshot for the panel.
294
517
  try {
295
518
  if (typeof ctx.inject === 'function') {
296
519
  ctx.inject(['connection'], (child) => {
@@ -301,11 +524,40 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
301
524
  path: '/api/ai-prison/watchdog/status',
302
525
  methods: ['GET'],
303
526
  requestBody: 'buffered',
304
- fetch: async () =>
305
- Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
527
+ fetch: async () => Response.json(watchdogSnapshot(), { headers: { 'cache-control': 'no-store' } }),
306
528
  }),
307
529
  'ai-prison-watchdog: status api',
308
530
  )
531
+ child.effect(
532
+ () =>
533
+ child.connection.fetch.register({
534
+ path: '/api/ai-prison/watchdog/action',
535
+ methods: ['POST'],
536
+ requestBody: 'buffered',
537
+ fetch: async (request) => {
538
+ let body = {}
539
+ try {
540
+ body = await request.json()
541
+ } catch {
542
+ body = {}
543
+ }
544
+ const action = typeof body.action === 'string' ? body.action : ''
545
+ const target = typeof body.target === 'string' ? body.target : ''
546
+ if (action === 'confirm-pause') {
547
+ watchdogState.graceUntil = Date.now() + PAUSE_GRACE_MS
548
+ appendIncident({ kind: 'pause-confirmed', detail: `用户二次确认继续插件操作(宽限 10 分钟)` })
549
+ return Response.json({ ok: true })
550
+ }
551
+ if (action === 'release') return Response.json(releaseTarget(target))
552
+ if (action === 'close') {
553
+ const ok = await disableTarget(target, 'manual-close')
554
+ return Response.json({ ok })
555
+ }
556
+ return Response.json({ ok: false, error: 'unknown action' }, { status: 400 })
557
+ },
558
+ }),
559
+ 'ai-prison-watchdog: action api',
560
+ )
309
561
  } catch (error) {
310
562
  watchdogState.degraded = `status api: ${String((error && error.message) || error)}`
311
563
  }
@@ -315,28 +567,56 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
315
567
  watchdogState.degraded = `connection: ${String((error && error.message) || error)}`
316
568
  }
317
569
 
318
- log.info(`[ai-prison-watchdog] observe 模式已启动(数据目录 ${dataDir})`)
570
+ log.info(`[ai-prison-watchdog] ${watchdogState.mode} 模式已启动(数据目录 ${dataDir})`)
319
571
  return {
320
572
  snapshot: watchdogSnapshot,
321
573
  sample,
322
574
  readCrashLogs,
575
+ disableTarget,
576
+ releaseTarget,
577
+ dispose() {
578
+ while (cleanups.length > 0) {
579
+ const disposer = cleanups.pop()
580
+ try {
581
+ disposer()
582
+ } catch {
583
+ // ignore dispose races
584
+ }
585
+ }
586
+ },
323
587
  }
324
588
  }
325
589
 
326
590
  /** Serialisable snapshot shared by the tool and the panel route. */
327
591
  export function watchdogSnapshot() {
328
592
  const s = watchdogState
593
+ const quarantine = []
594
+ for (const [target, entry] of s.quarantine instanceof Map ? s.quarantine : []) {
595
+ quarantine.push({ target, ...entry })
596
+ }
329
597
  return {
330
598
  ok: Boolean(s.startedAt),
331
599
  mode: s.mode,
600
+ enforce: s.enforce,
332
601
  startedAt: s.startedAt,
602
+ runId: s.runId,
333
603
  dataDir: s.dataDir,
334
604
  degraded: s.degraded,
335
605
  heap: s.latest,
336
606
  thresholds: s.thresholds,
337
607
  waterline: s.waterline,
608
+ strongWarn: s.strongWarn,
609
+ pausedAt: s.pausedAt,
610
+ graceUntil: s.graceUntil,
611
+ frozenAt: s.frozenAt,
338
612
  samples: s.samples.slice(-30),
339
613
  operations: topOperations(s.operations, 10),
614
+ topFive: topOperations(s.operations, 5),
615
+ quarantine,
616
+ plans: s.plans.slice(-5),
617
+ escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
618
+ baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
619
+ budgets: s.budgets,
340
620
  incidents: s.incidents.slice(-20),
341
621
  generatedAt: new Date().toISOString(),
342
622
  }
@@ -1,11 +1,15 @@
1
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).
2
+ * Shared in-process state of the AI Prison watchdog.
3
+ *
4
+ * P0 wrote it in observe mode; P1 keeps the same shape and adds the enforcement
5
+ * registries (quarantine, pause grace, hot-operation counters, budget table,
6
+ * baseline, crash plans). Nothing here touches the plugin manager by itself.
5
7
  */
6
8
  export const watchdogState = {
7
- mode: 'observe',
9
+ mode: 'enforce',
10
+ enforce: true,
8
11
  startedAt: null,
12
+ runId: null,
9
13
  dataDir: null,
10
14
  config: {},
11
15
  /** Latest metrics sample. */
@@ -14,8 +18,24 @@ export const watchdogState = {
14
18
  samples: [],
15
19
  thresholds: null,
16
20
  waterline: 'ok',
21
+ strongWarn: false,
22
+ pausedAt: null,
23
+ graceUntil: null,
24
+ frozenAt: null,
17
25
  /** target -> { count, estimateMB, lastAt, version, lastApplication } */
18
26
  operations: new Map(),
27
+ /** target -> { reason, level, at, evidence, release: 'restart'|'manual' } */
28
+ quarantine: new Map(),
29
+ /** target -> ms timestamp until which operation events are our own doing. */
30
+ suppressUntil: new Map(),
31
+ /** name@version -> measured/estimated startup MB (budget probe feeds this in P2). */
32
+ budgets: {},
33
+ /** Last clean baseline: { at, runId, bundles: [{name, version, enabled}], files } */
34
+ baseline: null,
35
+ /** Crash attribution plans (dry-run): { at, level, target, evidence, applied } */
36
+ plans: [],
37
+ /** Escalation counters: crash timestamps (ms) and applied level. */
38
+ escalation: { crashes: [], level: 'L0' },
19
39
  /** Recent incidents (newest last), capped. */
20
40
  incidents: [],
21
41
  /** Last crash-log scan marker (ms). */
@@ -28,15 +48,27 @@ export const MAX_SAMPLES = 120
28
48
  export const MAX_INCIDENTS = 200
29
49
 
30
50
  export function resetWatchdogState(overrides = {}) {
31
- watchdogState.mode = 'observe'
51
+ watchdogState.mode = 'enforce'
52
+ watchdogState.enforce = true
32
53
  watchdogState.startedAt = null
54
+ watchdogState.runId = null
33
55
  watchdogState.dataDir = null
34
56
  watchdogState.config = {}
35
57
  watchdogState.latest = null
36
58
  watchdogState.samples = []
37
59
  watchdogState.thresholds = null
38
60
  watchdogState.waterline = 'ok'
61
+ watchdogState.strongWarn = false
62
+ watchdogState.pausedAt = null
63
+ watchdogState.graceUntil = null
64
+ watchdogState.frozenAt = null
39
65
  watchdogState.operations = new Map()
66
+ watchdogState.quarantine = new Map()
67
+ watchdogState.suppressUntil = new Map()
68
+ watchdogState.budgets = {}
69
+ watchdogState.baseline = null
70
+ watchdogState.plans = []
71
+ watchdogState.escalation = { crashes: [], level: 'L0' }
40
72
  watchdogState.incidents = []
41
73
  watchdogState.lastCrashScan = 0
42
74
  watchdogState.degraded = null
package/locale/en.json CHANGED
@@ -3,5 +3,18 @@
3
3
  "title": "AI Prison",
4
4
  "description": "Wraps the aiprison CLI as six DSH tools (levels, status, demo, drill, inspect, verify, repair-tail) and adds a sidebar panel showing the L0–L5 grading matrix together with the durable ledger's audit-chain integrity and record count. Open it from the sidebar's shield entry; the panel is read-only and never writes to the ledger. Ledgers live in <session working directory>/.ai-prison unless a data directory is configured. Every capability-removal backend (GRAM, TLM, hardware binding, MicroVM isolation) stays simulated, so the tools audit and demonstrate governance instead of enforcing real isolation.",
5
5
  "detail": "docs/DETAIL.md"
6
- }
6
+ },
7
+ "watchdog.enforceTitle": "Enforcement",
8
+ "watchdog.enforceOn": "enforce",
9
+ "watchdog.observeOnly": "observe only",
10
+ "watchdog.freezeHint": "Heap is frozen at {level}: plugin operations are blocked except release actions. Close the biggest plugins below or restart DSH.",
11
+ "watchdog.confirmPause": "I understand: allow plugin operations for 10 minutes",
12
+ "watchdog.quarantine": "Plugin prison",
13
+ "watchdog.noQuarantine": "No quarantined plugins.",
14
+ "watchdog.release": "Release",
15
+ "watchdog.topFive": "Top {n} by estimated heap",
16
+ "watchdog.close": "Close now",
17
+ "watchdog.plans": "Crash plans (dry-run)",
18
+ "watchdog.noPlans": "No crash attribution plans.",
19
+ "watchdog.baseline": "Clean baseline: {at}"
7
20
  }
package/locale/zh.json CHANGED
@@ -3,5 +3,18 @@
3
3
  "title": "AI Prison · AI 监狱",
4
4
  "description": "把 aiprison CLI 封装为六个 DSH 工具(levels、status、demo、drill、inspect、verify、repair-tail),并在侧边栏增加一个面板:展示 L0–L5 分级矩阵,以及落盘账本的审计链完整性与记录数。从侧边栏的盾牌入口打开;面板只读,不会写入数据目录。账本默认写到 <会话工作目录>/.ai-prison,也可在配置里指定数据目录。GRAM、TLM、硬件绑定、MicroVM 隔离等能力摘除后端全部为内存模拟 —— 这些工具用于审计与演示治理流程,并不执行真实隔离。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
- }
6
+ },
7
+ "watchdog.enforceTitle": "执行状态",
8
+ "watchdog.enforceOn": "enforce",
9
+ "watchdog.observeOnly": "仅观察",
10
+ "watchdog.freezeHint": "堆水位已冻结({level}):除释放类操作外,所有插件操作被禁止。请关闭下方内存最大的插件或重启 DSH。",
11
+ "watchdog.confirmPause": "我已知晓:允许插件操作 10 分钟",
12
+ "watchdog.quarantine": "插件监狱",
13
+ "watchdog.noQuarantine": "没有被隔离的插件。",
14
+ "watchdog.release": "假释",
15
+ "watchdog.topFive": "按估算内存排序的前 {n} 个插件",
16
+ "watchdog.close": "立即关闭",
17
+ "watchdog.plans": "崩溃降级计划(dry-run)",
18
+ "watchdog.noPlans": "暂无崩溃归因计划。",
19
+ "watchdog.baseline": "干净基线:{at}"
7
20
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.2.0",
3
+ "version": "1.3.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",