@twinsearth/ai-prison-dsh-plugin 1.4.6 → 1.5.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 +67 -0
- package/client.js +9 -2
- package/lib/notifier.js +80 -0
- package/lib/watchdog-policy.js +47 -0
- package/lib/watchdog-runtime.js +117 -24
- package/locale/en.json +5 -2
- package/locale/zh.json +5 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,73 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
|
|
4
4
|
|
|
5
|
+
## [1.5.0] — 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Changed — profile tamper monitor is dry-run (observe) by default
|
|
8
|
+
|
|
9
|
+
- `tamperPolicy` now accepts `observe` (default), `alert` and `restore`. In
|
|
10
|
+
`observe` the monitor still snapshots the five critical files, backs up the
|
|
11
|
+
drifted bytes to `tampered/` and records an L1 plan/incident, but **never
|
|
12
|
+
restores the file, never quarantines and never closes a plugin** — the
|
|
13
|
+
dry-run stage requested before turning the guard on.
|
|
14
|
+
- `alert` records only as well; only an explicit `tamperPolicy: "restore"`
|
|
15
|
+
restores the bytes and applies L1 enforcement.
|
|
16
|
+
- The panel line now shows the active policy, and the tool snapshot carries it.
|
|
17
|
+
|
|
18
|
+
### Added — Top5 v2 (child RSS, EWMA, stable order)
|
|
19
|
+
|
|
20
|
+
- Every 60 s the watchdog scans the process table (Windows) and attributes the
|
|
21
|
+
working set of processes whose command line references
|
|
22
|
+
`profiles/desktop/node_modules/<plugin>` to that plugin (`rssMB`).
|
|
23
|
+
- Top5 scores `module-load/operation estimate + child RSS`, smooths RSS with an
|
|
24
|
+
EWMA (alpha 0.35) and only reorders when a score moved more than 20 %, which
|
|
25
|
+
stops the list from jumping on every sample.
|
|
26
|
+
- The panel Top5 table gained a child-RSS column; the tool snapshot exposes
|
|
27
|
+
`rss` and `rssAt`.
|
|
28
|
+
- A pre-freeze heap snapshot is intentionally not taken: at 4.5 GB of a 6 GB
|
|
29
|
+
heap the snapshot's ~2x temporary cost would OOM the host, so freeze keeps
|
|
30
|
+
using the measured/estimate/RSS data.
|
|
31
|
+
|
|
32
|
+
### Added — optional desktop notifications
|
|
33
|
+
|
|
34
|
+
- `config: { notify: true }` turns on a Windows tray-balloon notification for
|
|
35
|
+
freeze, pause, quarantine, tamper, crash-enforcement and budget incidents
|
|
36
|
+
(rate limited per kind, 60 s; disabled by default). The watchdog does not
|
|
37
|
+
depend on it: failures are ignored.
|
|
38
|
+
|
|
39
|
+
### Notes
|
|
40
|
+
- The monitor stays a module inside the watchdog row rather than a separate
|
|
41
|
+
loader row: it runs in the same host process either way, and keeping it in
|
|
42
|
+
the row avoids a second loader entry whose failure would silently remove the
|
|
43
|
+
status API as well. It can already be disabled with `tamperMonitor: false`.
|
|
44
|
+
|
|
45
|
+
## [1.4.7] — 2026-11-18
|
|
46
|
+
## [1.4.7] — 2026-11-18
|
|
47
|
+
|
|
48
|
+
### Added — panel/remote operations roll back while paused or frozen
|
|
49
|
+
|
|
50
|
+
- The 5 GB freeze (and the 3.9 GB pause without a confirmation) now also covers
|
|
51
|
+
operations started from the panel or the web UI, not just the agent tool:
|
|
52
|
+
after an additive operation settles, the watchdog immediately disables that
|
|
53
|
+
bundle and records a `freeze-rollback` / `pause-rollback` incident. Release
|
|
54
|
+
operations (disable/remove) and a confirmed pause grace window stay allowed.
|
|
55
|
+
- The panel's "Measure plugin budgets now" button is disabled while frozen,
|
|
56
|
+
because each probe spawns a child process.
|
|
57
|
+
|
|
58
|
+
### Fixed — tamper monitor no longer flags the manager's own writes
|
|
59
|
+
|
|
60
|
+
- The operation-window suppression was ±5 s around settle, but pnpm may write
|
|
61
|
+
package.json / pnpm-lock.yaml later than that, so installs of 1.4.5/1.4.6 were
|
|
62
|
+
repeatedly "restored" by the tamper monitor and some installs failed.
|
|
63
|
+
- Any drift within 120 s after the last plugin operation is now treated as a
|
|
64
|
+
manager write; the mtime window still applies to older operations. Real
|
|
65
|
+
out-of-window edits (manual scripts) are still detected and restored.
|
|
66
|
+
|
|
67
|
+
### Tests
|
|
68
|
+
- New `test/watchdog-freeze.test.mjs`: freeze rollback, pause rollback with and
|
|
69
|
+
without grace, and release-class operations never rolled back.
|
|
70
|
+
|
|
71
|
+
## [1.4.6] — 2026-11-18
|
|
5
72
|
## [1.4.6] — 2026-11-18
|
|
6
73
|
|
|
7
74
|
### Added — structured reason / impact / steps / release text
|
package/client.js
CHANGED
|
@@ -460,9 +460,16 @@ window.__ModuleLoader__.load({
|
|
|
460
460
|
topFive.length === 0 ? null : h('div', null,
|
|
461
461
|
h('div', { style: { ...C.key, marginBottom: 4 } }, t('watchdog.topFive', { n: topFive.length })),
|
|
462
462
|
h('table', { style: C.table },
|
|
463
|
+
h('thead', null, h('tr', null,
|
|
464
|
+
h('th', { style: C.th }, t('prison.plugin')),
|
|
465
|
+
h('th', { style: C.th }, t('prison.estimate')),
|
|
466
|
+
h('th', { style: C.th }, t('prison.rss')),
|
|
467
|
+
h('th', { style: C.th }, ''),
|
|
468
|
+
)),
|
|
463
469
|
h('tbody', null, topFive.map((row) => h('tr', { key: row.target },
|
|
464
470
|
h('td', { style: { ...C.td, ...C.mono, fontSize: 11.5, wordBreak: 'break-all' } }, row.target),
|
|
465
471
|
h('td', { style: C.td }, row.estimateMB + ' MB'),
|
|
472
|
+
h('td', { style: C.td }, (row.rssMB || 0) + ' MB'),
|
|
466
473
|
h('td', { style: C.td }, h('button', { style: button, onClick: () => act('close', row.target, '立即关闭 ' + row.target + ' ?') }, t('watchdog.close'))),
|
|
467
474
|
))),
|
|
468
475
|
),
|
|
@@ -473,9 +480,9 @@ window.__ModuleLoader__.load({
|
|
|
473
480
|
plan.at + ' · ' + plan.level + ' · ' + (plan.target || 'unattributed') + (plan.inFlight ? ' (in-flight)' : '') + (plan.crash ? ' · ' + (plan.crash.oom ? 'OOM' : 'exit ' + plan.crash.hostExitCode) : ''))),
|
|
474
481
|
),
|
|
475
482
|
watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
|
|
476
|
-
watchdog.tamper ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '6px 0 0' } }, t('watchdog.tamper', { n: (watchdog.tamper.files || []).length, at: watchdog.tamper.lastCheckAt || '—' })) : null,
|
|
483
|
+
watchdog.tamper ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '6px 0 0' } }, t('watchdog.tamper', { n: (watchdog.tamper.files || []).length, at: watchdog.tamper.lastCheckAt || '—', policy: watchdog.tamper.policy || '' })) : null,
|
|
477
484
|
h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
|
|
478
|
-
h('button', { style: { ...button, padding: '5px 10px' }, onClick: () => act('probe') }, t('watchdog.measure')),
|
|
485
|
+
h('button', { style: { ...button, padding: '5px 10px', opacity: frozen ? 0.5 : 1 }, disabled: frozen, title: frozen ? t('watchdog.measureBlocked') : undefined, onClick: () => { if (!frozen) act('probe') } }, t('watchdog.measure')),
|
|
479
486
|
watchdog.probeProgress ? h('span', { style: { ...C.mono, fontSize: 11.5 } }, `${watchdog.probeProgress.done || 0}/${watchdog.probeProgress.total || 0}`) : null,
|
|
480
487
|
),
|
|
481
488
|
)
|
package/lib/notifier.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Optional desktop notification for enforcement events. Uses the Windows tray
|
|
5
|
+
* balloon through PowerShell so no extra dependency is needed. Disabled by
|
|
6
|
+
* default; enable with `config: { notify: true }` on the watchdog row.
|
|
7
|
+
*/
|
|
8
|
+
const KIND_LABELS = {
|
|
9
|
+
freeze: '内存冻结',
|
|
10
|
+
pause: '内存暂停',
|
|
11
|
+
quarantine: '插件隔离',
|
|
12
|
+
tamper: '配置篡改',
|
|
13
|
+
'crash-enforced': '崩溃隔离',
|
|
14
|
+
budget: '内存超限',
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
let lastAt = 0
|
|
18
|
+
let lastKind = ''
|
|
19
|
+
|
|
20
|
+
export function shouldNotify(kind, now = Date.now(), cooldownMs = 60_000) {
|
|
21
|
+
if (!KIND_LABELS[kind]) return false
|
|
22
|
+
if (kind === lastKind && now - lastAt < cooldownMs) return false
|
|
23
|
+
lastKind = kind
|
|
24
|
+
lastAt = now
|
|
25
|
+
return true
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function notificationFor(incident) {
|
|
29
|
+
const kind = incident && incident.kind
|
|
30
|
+
const label = KIND_LABELS[kind]
|
|
31
|
+
if (!label) return null
|
|
32
|
+
const target = incident.target ? ` ${incident.target}` : ''
|
|
33
|
+
const title = `AI Prison · ${label}`
|
|
34
|
+
const body = String(incident.detail || incident.evidence || target || '').slice(0, 180) || label
|
|
35
|
+
return { title, body }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function powershellScript(title, body) {
|
|
39
|
+
const safeTitle = String(title).replace(/'/g, "''")
|
|
40
|
+
const safeBody = String(body).replace(/'/g, "''")
|
|
41
|
+
return [
|
|
42
|
+
'Add-Type -AssemblyName System.Windows.Forms | Out-Null',
|
|
43
|
+
'Add-Type -AssemblyName System.Drawing | Out-Null',
|
|
44
|
+
'$n = New-Object System.Windows.Forms.NotifyIcon',
|
|
45
|
+
'$n.Icon = [System.Drawing.SystemIcons]::Warning',
|
|
46
|
+
'$n.Visible = $true',
|
|
47
|
+
`$n.ShowBalloonTip(8000, '${safeTitle}', '${safeBody}', [System.Windows.Forms.ToolTipIcon]::Warning)`,
|
|
48
|
+
'Start-Sleep -Seconds 9',
|
|
49
|
+
'$n.Visible = $false',
|
|
50
|
+
'$n.Dispose()',
|
|
51
|
+
].join('; ')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Fire one tray notification (best effort, detached). */
|
|
55
|
+
export function notify(incident, { cooldownMs = 60_000 } = {}) {
|
|
56
|
+
const message = notificationFor(incident)
|
|
57
|
+
if (!message) return { ok: false, reason: 'unsupported-kind' }
|
|
58
|
+
if (process.platform !== 'win32') return { ok: false, reason: 'platform' }
|
|
59
|
+
const now = Date.now()
|
|
60
|
+
if (!shouldNotify(incident.kind, now, cooldownMs)) return { ok: false, reason: 'rate-limited' }
|
|
61
|
+
lastAt = now
|
|
62
|
+
lastKind = incident.kind
|
|
63
|
+
try {
|
|
64
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', powershellScript(message.title, message.body)], {
|
|
65
|
+
detached: true,
|
|
66
|
+
stdio: 'ignore',
|
|
67
|
+
windowsHide: true,
|
|
68
|
+
})
|
|
69
|
+
child.unref()
|
|
70
|
+
return { ok: true, title: message.title }
|
|
71
|
+
} catch (error) {
|
|
72
|
+
return { ok: false, reason: String((error && error.message) || error) }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Test hook. */
|
|
77
|
+
export function resetNotifierState() {
|
|
78
|
+
lastAt = 0
|
|
79
|
+
lastKind = ''
|
|
80
|
+
}
|
package/lib/watchdog-policy.js
CHANGED
|
@@ -222,6 +222,53 @@ export function topOperations(operations, limit = 5) {
|
|
|
222
222
|
return rows.slice(0, Math.max(1, limit))
|
|
223
223
|
}
|
|
224
224
|
|
|
225
|
+
/**
|
|
226
|
+
* Top5 v2: combine measured module-load MB, operation estimates and the RSS of
|
|
227
|
+
* child processes attributed to a plugin. The ranking is smoothed and stable:
|
|
228
|
+
* an item only changes rank when its score moved by more than 20%.
|
|
229
|
+
*/
|
|
230
|
+
export function rankTopPlugins({ operations = [], budgets = {}, rss = {}, previous = {}, alpha = 0.35, limit = 5 } = {}) {
|
|
231
|
+
const rows = new Map()
|
|
232
|
+
for (const row of operations) {
|
|
233
|
+
rows.set(row.target, { target: row.target, operationMB: Number(row.estimateMB) || 0, count: Number(row.count) || 0, version: row.version || null, source: row.source || 'estimate', measuredAt: row.measuredAt || null })
|
|
234
|
+
}
|
|
235
|
+
for (const [target, entry] of Object.entries(budgets)) {
|
|
236
|
+
if (!entry || entry.error || entry.moduleLoadMB === undefined) continue
|
|
237
|
+
const current = rows.get(target) || { target, operationMB: 0, count: 0, version: entry.version || null, source: 'measured', measuredAt: entry.measuredAt || null }
|
|
238
|
+
current.moduleLoadMB = Number(entry.moduleLoadMB) || 0
|
|
239
|
+
current.source = 'measured'
|
|
240
|
+
current.measuredAt = entry.measuredAt || current.measuredAt
|
|
241
|
+
current.version = entry.version || current.version
|
|
242
|
+
rows.set(target, current)
|
|
243
|
+
}
|
|
244
|
+
for (const [target, bytes] of Object.entries(rss)) {
|
|
245
|
+
const current = rows.get(target) || { target, operationMB: 0, count: 0, version: null, source: 'estimate', measuredAt: null }
|
|
246
|
+
const previousRss = Number(previous[target] && previous[target].rssMB) || 0
|
|
247
|
+
current.rssMB = previousRss > 0 ? Math.round(previousRss * (1 - alpha) + (Number(bytes) / (1024 * 1024)) * alpha) : Math.round((Number(bytes) || 0) / (1024 * 1024))
|
|
248
|
+
rows.set(target, current)
|
|
249
|
+
}
|
|
250
|
+
const ranked = [...rows.values()].map((row) => ({
|
|
251
|
+
...row,
|
|
252
|
+
rssMB: row.rssMB || 0,
|
|
253
|
+
score: Math.round((row.moduleLoadMB || row.operationMB || 0) + (row.rssMB || 0)),
|
|
254
|
+
}))
|
|
255
|
+
ranked.sort((a, b) => b.score - a.score)
|
|
256
|
+
const changed = ranked.some((row) => {
|
|
257
|
+
const before = previous[row.target]
|
|
258
|
+
if (!before || !Number.isFinite(before.score)) return true
|
|
259
|
+
const delta = Math.abs(row.score - before.score)
|
|
260
|
+
return delta / Math.max(1, before.score) > 0.2
|
|
261
|
+
})
|
|
262
|
+
const next = {}
|
|
263
|
+
for (const row of ranked) next[row.target] = { score: row.score, rssMB: row.rssMB }
|
|
264
|
+
if (!changed) {
|
|
265
|
+
// keep the last order while scores are stable
|
|
266
|
+
const order = Object.keys(previous)
|
|
267
|
+
ranked.sort((a, b) => order.indexOf(a.target) - order.indexOf(b.target))
|
|
268
|
+
}
|
|
269
|
+
return { rows: ranked.slice(0, Math.max(1, limit)), nextRanking: next }
|
|
270
|
+
}
|
|
271
|
+
|
|
225
272
|
/** Named byte formatting used by the panel/tool text. */
|
|
226
273
|
export function formatBytes(bytes) {
|
|
227
274
|
const value = Number(bytes)
|
package/lib/watchdog-runtime.js
CHANGED
|
@@ -3,10 +3,12 @@ import os from 'node:os'
|
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
import v8 from 'node:v8'
|
|
5
5
|
import crypto from 'node:crypto'
|
|
6
|
+
import { spawn } from 'node:child_process'
|
|
6
7
|
import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
|
|
7
8
|
import { probeBudget } from './budget-probe.js'
|
|
8
9
|
import { createTamperMonitor } from './tamper-monitor.js'
|
|
9
10
|
import { remediationFor } from './remediation.js'
|
|
11
|
+
import { notify } from './notifier.js'
|
|
10
12
|
import {
|
|
11
13
|
attributeCrash,
|
|
12
14
|
classifyWaterline,
|
|
@@ -19,6 +21,7 @@ import {
|
|
|
19
21
|
operationWeight,
|
|
20
22
|
parseCrashLog,
|
|
21
23
|
thresholdsFor,
|
|
24
|
+
rankTopPlugins,
|
|
22
25
|
topOperations,
|
|
23
26
|
} from './watchdog-policy.js'
|
|
24
27
|
|
|
@@ -138,6 +141,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
138
141
|
|
|
139
142
|
let lastFlush = 0
|
|
140
143
|
let operationWindowUntil = 0
|
|
144
|
+
let lastOperationAt = 0
|
|
141
145
|
const operationWindows = []
|
|
142
146
|
let tamperMigrationDone = false
|
|
143
147
|
let tamper = null
|
|
@@ -154,10 +158,10 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
154
158
|
tamper = createTamperMonitor({
|
|
155
159
|
profileDir,
|
|
156
160
|
dataDir,
|
|
157
|
-
policy: config.tamperPolicy === 'alert' ? 'alert' : '
|
|
161
|
+
policy: config.tamperPolicy === 'restore' ? 'restore' : config.tamperPolicy === 'alert' ? 'alert' : 'observe',
|
|
158
162
|
graceMs: Number(config.tamperGraceMs) >= 0 ? Number(config.tamperGraceMs) : 15_000,
|
|
159
163
|
intervalMs: Number(config.tamperIntervalMs) > 0 ? Number(config.tamperIntervalMs) : 30_000,
|
|
160
|
-
shouldIgnore: () => Date.now() < operationWindowUntil,
|
|
164
|
+
shouldIgnore: () => Date.now() < operationWindowUntil || Date.now() - lastOperationAt < 120000,
|
|
161
165
|
isWithinOperationWindow: (mtimeMs) => {
|
|
162
166
|
const now = Date.now()
|
|
163
167
|
return operationWindows.some((window) => mtimeMs >= window.startedAt - 5000 && mtimeMs <= (window.settledAt || now) + 5000)
|
|
@@ -180,7 +184,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
180
184
|
function handleTamper(result) {
|
|
181
185
|
if (!result || !Array.isArray(result.diffs) || result.diffs.length === 0) return
|
|
182
186
|
const files = result.diffs.map((diff) => diff.file)
|
|
183
|
-
|
|
187
|
+
const policy = (watchdogState.tamper && watchdogState.tamper.policy) || 'observe'
|
|
188
|
+
appendIncident({ kind: 'tamper', files, policy, restored: result.restored, detail: '配置漂移:' + files.join(', ') + (policy === 'observe' ? '(observe:仅记录,不恢复不关闭)' : '') })
|
|
184
189
|
let target = null
|
|
185
190
|
let evidence = []
|
|
186
191
|
try {
|
|
@@ -194,7 +199,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
194
199
|
} catch {
|
|
195
200
|
target = null
|
|
196
201
|
}
|
|
197
|
-
const applied = Boolean(watchdogState.enforce && target)
|
|
202
|
+
const applied = Boolean(watchdogState.enforce && target && policy === 'restore')
|
|
198
203
|
const plan = { at: new Date().toISOString(), level: 'L1', crash: null, reason: 'tamper', remediation: remediationFor('tamper'), target, inFlight: false, evidence: { files: result.diffs, candidates: evidence }, applied }
|
|
199
204
|
watchdogState.plans.push(plan)
|
|
200
205
|
if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
|
|
@@ -207,6 +212,63 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
207
212
|
persist(true)
|
|
208
213
|
}
|
|
209
214
|
|
|
215
|
+
const RSS_INTERVAL_MS = 60_000
|
|
216
|
+
let rssTimer = null
|
|
217
|
+
let rssScanning = false
|
|
218
|
+
|
|
219
|
+
function scanChildRss() {
|
|
220
|
+
if (process.platform !== 'win32' || rssScanning) return
|
|
221
|
+
const manager = refs.manager
|
|
222
|
+
if (!manager || typeof manager.listBundles !== 'function') return
|
|
223
|
+
rssScanning = true
|
|
224
|
+
const profileLiteral = String(profileDir).replace(/'/g, "''")
|
|
225
|
+
const script = [
|
|
226
|
+
"$ErrorActionPreference='SilentlyContinue'",
|
|
227
|
+
"Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like '*node_modules*' -and $_.CommandLine -like '*" + profileLiteral + "*' } | ForEach-Object { ($_.ProcessId.ToString() + '|' + [string]$_.WorkingSetSize + '|' + $_.CommandLine) }",
|
|
228
|
+
].join('; ')
|
|
229
|
+
let output = ''
|
|
230
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })
|
|
231
|
+
child.stdout.on('data', (chunk) => {
|
|
232
|
+
output += String(chunk)
|
|
233
|
+
})
|
|
234
|
+
child.on('error', () => {
|
|
235
|
+
rssScanning = false
|
|
236
|
+
})
|
|
237
|
+
child.on('exit', () => {
|
|
238
|
+
rssScanning = false
|
|
239
|
+
void manager
|
|
240
|
+
.listBundles()
|
|
241
|
+
.then((rows) => {
|
|
242
|
+
const enabled = rows.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name)).map((row) => row.name)
|
|
243
|
+
const totals = new Map()
|
|
244
|
+
for (const line of output.split('\n')) {
|
|
245
|
+
const parts = line.trim().split('|')
|
|
246
|
+
if (parts.length < 3) continue
|
|
247
|
+
const bytes = Number(parts[1]) || 0
|
|
248
|
+
const commandLine = parts.slice(2).join('|')
|
|
249
|
+
for (const name of enabled) {
|
|
250
|
+
if (commandLine.includes('node_modules' + path.sep + name) || commandLine.includes('node_modules/' + name)) {
|
|
251
|
+
totals.set(name, (totals.get(name) || 0) + bytes)
|
|
252
|
+
break
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
const rss = { ...(watchdogState.rss || {}) }
|
|
257
|
+
for (const [name, bytes] of totals) rss[name] = bytes
|
|
258
|
+
watchdogState.rss = rss
|
|
259
|
+
watchdogState.rssAt = new Date().toISOString()
|
|
260
|
+
})
|
|
261
|
+
.catch(() => {})
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function startRssScanner() {
|
|
266
|
+
if (rssTimer || process.platform !== 'win32') return
|
|
267
|
+
const timer = setTimeout(scanChildRss, 5000)
|
|
268
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
269
|
+
rssTimer = setInterval(scanChildRss, RSS_INTERVAL_MS)
|
|
270
|
+
if (typeof rssTimer.unref === 'function') rssTimer.unref()
|
|
271
|
+
}
|
|
210
272
|
function persist(force = false) {
|
|
211
273
|
const now = Date.now()
|
|
212
274
|
if (!force && now - lastFlush < FLUSH_MS) return
|
|
@@ -258,6 +320,13 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
258
320
|
|
|
259
321
|
function appendIncident(incident) {
|
|
260
322
|
const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
|
|
323
|
+
if (watchdogState.config && watchdogState.config.notify === true && ['freeze', 'pause', 'quarantine', 'tamper', 'crash-enforced', 'budget'].includes(record.kind)) {
|
|
324
|
+
try {
|
|
325
|
+
notify(record)
|
|
326
|
+
} catch {
|
|
327
|
+
// notifications are best effort
|
|
328
|
+
}
|
|
329
|
+
}
|
|
261
330
|
watchdogState.incidents.push(record)
|
|
262
331
|
if (watchdogState.incidents.length > MAX_INCIDENTS) watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
|
|
263
332
|
try {
|
|
@@ -396,6 +465,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
396
465
|
const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
|
|
397
466
|
if (operation.phase === 'started') {
|
|
398
467
|
operationWindowUntil = Date.now() + 4000
|
|
468
|
+
lastOperationAt = Date.now()
|
|
399
469
|
operationWindows.push({ startedAt: Date.now(), settledAt: null })
|
|
400
470
|
if (operationWindows.length > 20) operationWindows.shift()
|
|
401
471
|
inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
|
|
@@ -405,6 +475,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
405
475
|
}
|
|
406
476
|
if (operation.phase !== 'settled') return
|
|
407
477
|
operationWindowUntil = Date.now() + 4000
|
|
478
|
+
lastOperationAt = Date.now()
|
|
408
479
|
for (let i = operationWindows.length - 1; i >= 0; i -= 1) {
|
|
409
480
|
if (operationWindows[i].settledAt === null) { operationWindows[i].settledAt = Date.now(); break }
|
|
410
481
|
}
|
|
@@ -422,6 +493,24 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
422
493
|
entry.version = operation.version || entry.version
|
|
423
494
|
entry.lastApplication = operation.application || null
|
|
424
495
|
watchdogState.operations.set(target, entry)
|
|
496
|
+
const additive = operation.stage === 'install' || (operation.stage === 'enable' && operation.enabled !== false)
|
|
497
|
+
if (
|
|
498
|
+
watchdogState.enforce &&
|
|
499
|
+
additive &&
|
|
500
|
+
target &&
|
|
501
|
+
!EXEMPT_TARGETS.has(target) &&
|
|
502
|
+
(watchdogState.waterline === 'frost' || watchdogState.waterline === 'pause') &&
|
|
503
|
+
!(Number.isFinite(watchdogState.graceUntil) && Date.now() < watchdogState.graceUntil)
|
|
504
|
+
) {
|
|
505
|
+
const level = watchdogState.waterline
|
|
506
|
+
appendIncident({
|
|
507
|
+
kind: level === 'frost' ? 'freeze-rollback' : 'pause-rollback',
|
|
508
|
+
target,
|
|
509
|
+
level,
|
|
510
|
+
detail: (level === 'frost' ? '冻结' : '暂停') + '期间检测到面板/网页发起的增内存操作,已立即回滚关闭 ' + target,
|
|
511
|
+
})
|
|
512
|
+
void disableTarget(target, level + '-rollback')
|
|
513
|
+
}
|
|
425
514
|
if (operation.reason === 'remove' && operation.application === 'applied') {
|
|
426
515
|
watchdogState.operations.delete(target)
|
|
427
516
|
return
|
|
@@ -718,6 +807,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
718
807
|
refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
|
|
719
808
|
if (refs.manager) {
|
|
720
809
|
void reapplyQuarantine()
|
|
810
|
+
startRssScanner()
|
|
721
811
|
const probeTimer = setTimeout(() => {
|
|
722
812
|
void scheduleProbe()
|
|
723
813
|
}, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
|
|
@@ -852,6 +942,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
852
942
|
disableTarget,
|
|
853
943
|
releaseTarget,
|
|
854
944
|
dispose() {
|
|
945
|
+
if (rssTimer) clearInterval(rssTimer)
|
|
946
|
+
rssTimer = null
|
|
855
947
|
while (cleanups.length > 0) {
|
|
856
948
|
const disposer = cleanups.pop()
|
|
857
949
|
try {
|
|
@@ -864,29 +956,28 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
864
956
|
}
|
|
865
957
|
}
|
|
866
958
|
|
|
867
|
-
/**
|
|
959
|
+
/** Top5 v2: measured + estimate + child RSS with EWMA smoothing and rank hysteresis. */
|
|
868
960
|
function mergedTop(state, limit) {
|
|
869
961
|
const operations = topOperations(state.operations, 50)
|
|
870
|
-
const
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
962
|
+
const { rows, nextRanking } = rankTopPlugins({
|
|
963
|
+
operations,
|
|
964
|
+
budgets: state.budgets || {},
|
|
965
|
+
rss: state.rss || {},
|
|
966
|
+
previous: state.ranking || {},
|
|
967
|
+
limit,
|
|
968
|
+
})
|
|
969
|
+
state.ranking = nextRanking
|
|
970
|
+
return rows.map((row) => ({
|
|
971
|
+
target: row.target,
|
|
972
|
+
count: row.count || 0,
|
|
973
|
+
estimateMB: row.moduleLoadMB || row.operationMB || 0,
|
|
974
|
+
rssMB: row.rssMB || 0,
|
|
975
|
+
totalMB: row.score,
|
|
976
|
+
lastAt: row.measuredAt || null,
|
|
977
|
+
version: row.version || null,
|
|
978
|
+
source: row.source,
|
|
979
|
+
}))
|
|
888
980
|
}
|
|
889
|
-
|
|
890
981
|
/** Serialisable snapshot shared by the tool and the panel route. */
|
|
891
982
|
export function watchdogSnapshot() {
|
|
892
983
|
const s = watchdogState
|
|
@@ -920,6 +1011,8 @@ export function watchdogSnapshot() {
|
|
|
920
1011
|
baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
|
|
921
1012
|
budgets: s.budgets,
|
|
922
1013
|
tamper: s.tamper || null,
|
|
1014
|
+
rss: s.rss || {},
|
|
1015
|
+
rssAt: s.rssAt || null,
|
|
923
1016
|
incidents: s.incidents.slice(-20),
|
|
924
1017
|
generatedAt: new Date().toISOString(),
|
|
925
1018
|
}
|
package/locale/en.json
CHANGED
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
"watchdog.plans": "Crash plans (dry-run)",
|
|
18
18
|
"watchdog.noPlans": "No crash attribution plans.",
|
|
19
19
|
"watchdog.baseline": "Clean baseline: {at}",
|
|
20
|
-
"watchdog.tamper": "Profile watch: {n} critical file(s)
|
|
21
|
-
"watchdog.measure": "Measure plugin budgets now"
|
|
20
|
+
"watchdog.tamper": "Profile watch: {n} critical file(s) · policy {policy} · last check {at}",
|
|
21
|
+
"watchdog.measure": "Measure plugin budgets now",
|
|
22
|
+
"watchdog.measureBlocked": "Heap is frozen: measuring spawns child processes, so it stays disabled until the heap recovers.",
|
|
23
|
+
"prison.rss": "Child RSS",
|
|
24
|
+
"prison.plugin": "Plugin"
|
|
22
25
|
}
|
package/locale/zh.json
CHANGED
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
"watchdog.plans": "崩溃降级计划(dry-run)",
|
|
18
18
|
"watchdog.noPlans": "暂无崩溃归因计划。",
|
|
19
19
|
"watchdog.baseline": "干净基线:{at}",
|
|
20
|
-
"watchdog.tamper": "配置监控:{n}
|
|
21
|
-
"watchdog.measure": "立即测量插件预算"
|
|
20
|
+
"watchdog.tamper": "配置监控:{n} 个关键文件 · 策略 {policy} · 最近检查 {at}",
|
|
21
|
+
"watchdog.measure": "立即测量插件预算",
|
|
22
|
+
"watchdog.measureBlocked": "堆已冻结:测量会启动子进程,恢复前暂停测量。",
|
|
23
|
+
"prison.rss": "子进程 RSS",
|
|
24
|
+
"prison.plugin": "插件"
|
|
22
25
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/ai-prison-dsh-plugin",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.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",
|