@twinsearth/ai-prison-dsh-plugin 1.4.3 → 1.4.5
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 +47 -0
- package/client.js +4 -0
- package/lib/budget-child.mjs +27 -2
- package/lib/budget-probe.js +2 -1
- package/lib/tamper-monitor.js +16 -9
- package/lib/watchdog-runtime.js +116 -20
- package/locale/en.json +2 -1
- package/locale/zh.json +2 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,53 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
|
|
4
4
|
|
|
5
|
+
## [1.4.5] — 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Fixed — tamper monitor false positives (important)
|
|
8
|
+
|
|
9
|
+
- The first tamper monitor attributed writes at **poll time**, not at write time, so
|
|
10
|
+
a legitimate plugin-manager write (install/enable rewrites package.json and
|
|
11
|
+
pnpm-lock.yaml) was classified as tampering 30 s later. That closed and jailed
|
|
12
|
+
plugins after every install.
|
|
13
|
+
- Operation windows are now recorded on `started`/`settled` and matched against
|
|
14
|
+
each changed file's **mtime** (±5 s), so a manager write stays legitimate even
|
|
15
|
+
when the poll happens after the window closed.
|
|
16
|
+
- One-time migration: tamper quarantine persisted by 1.4.3/1.4.4 is cleared with
|
|
17
|
+
an audited `migration` incident instead of re-closing those plugins on boot.
|
|
18
|
+
|
|
19
|
+
### Fixed — budget probe could not import plugins that use harness peers
|
|
20
|
+
|
|
21
|
+
- `budget-child.mjs` now resolves `@deepseek-ai/*` and `cordis` from the DSH
|
|
22
|
+
installation via `module.registerHooks`, so plugins like `dsh-context` that
|
|
23
|
+
import `@deepseek-ai/dsh-session` at module scope can be measured.
|
|
24
|
+
- Also fixed a wrong `pathToFileURL` import that broke the probe child entirely.
|
|
25
|
+
|
|
26
|
+
### Tests
|
|
27
|
+
- mtime operation-window suppression, legacy tamper-quarantine migration, and the
|
|
28
|
+
probe child import path are covered by the test suite (70 tests total).
|
|
29
|
+
|
|
30
|
+
## [1.4.4] — 2026-11-18
|
|
31
|
+
## [1.4.4] — 2026-11-18
|
|
32
|
+
|
|
33
|
+
### Fixed — per-plugin budget probe actually works end to end
|
|
34
|
+
|
|
35
|
+
- The probe now covers **every enabled, non-exempt bundle without a current
|
|
36
|
+
measurement** (not only plugins installed/enabled in the last 30 minutes),
|
|
37
|
+
scheduled after boot (max 5 per run) and retried after failures (error entries
|
|
38
|
+
older than 10 minutes, up to 5 attempts).
|
|
39
|
+
- Budgets are version-aware: an entry measured for another version, without a
|
|
40
|
+
version, older than 7 days, or failed is treated as stale and re-measured.
|
|
41
|
+
- A manual "Measure plugin budgets now" button in the Enforcement card and a
|
|
42
|
+
`probe` action on the watchdog route run the queue immediately (up to 15
|
|
43
|
+
targets) and report `probeProgress`.
|
|
44
|
+
- The measured module-load MB **wins over operation estimates in Top5** and is
|
|
45
|
+
labelled `source: "measured"`; operation-derived rows stay `estimate`.
|
|
46
|
+
- >500 MB still quarantines, closes and queues the plugin in
|
|
47
|
+
`pending-boot.json`; 300–500 MB records a warning only.
|
|
48
|
+
- Tests: `test/watchdog-budget.test.mjs` covers the 600 MB quarantine path,
|
|
49
|
+
the 420 MB warning path with measured Top5, and failed-probe retry counting.
|
|
50
|
+
|
|
51
|
+
## [1.4.3] — 2026-11-18
|
|
5
52
|
## [1.4.3] — 2026-11-18
|
|
6
53
|
|
|
7
54
|
### Added — profile tamper monitor (requirement 3, the missing half)
|
package/client.js
CHANGED
|
@@ -465,6 +465,10 @@ window.__ModuleLoader__.load({
|
|
|
465
465
|
),
|
|
466
466
|
watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
|
|
467
467
|
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,
|
|
468
|
+
h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
|
|
469
|
+
h('button', { style: { ...button, padding: '5px 10px' }, onClick: () => act('probe') }, t('watchdog.measure')),
|
|
470
|
+
watchdog.probeProgress ? h('span', { style: { ...C.mono, fontSize: 11.5 } }, `${watchdog.probeProgress.done || 0}/${watchdog.probeProgress.total || 0}`) : null,
|
|
471
|
+
),
|
|
468
472
|
)
|
|
469
473
|
}
|
|
470
474
|
|
package/lib/budget-child.mjs
CHANGED
|
@@ -1,14 +1,39 @@
|
|
|
1
|
+
import * as nodeModule from 'node:module'
|
|
1
2
|
import { createRequire } from 'node:module'
|
|
2
3
|
import { pathToFileURL } from 'node:url'
|
|
4
|
+
import path from 'node:path'
|
|
3
5
|
|
|
4
6
|
// Child side of the AI Prison per-plugin budget probe (see budget-probe.js).
|
|
5
|
-
// argv: [node, --expose-gc, thisFile, profileDir, packageName]
|
|
6
|
-
const [, , profileDir, packageName] = process.argv
|
|
7
|
+
// argv: [node, --expose-gc, thisFile, profileDir, packageName, installDir]
|
|
8
|
+
const [, , profileDir, packageName, installDir] = process.argv
|
|
7
9
|
|
|
8
10
|
function heapMB() {
|
|
9
11
|
return process.memoryUsage().heapUsed / (1024 * 1024)
|
|
10
12
|
}
|
|
11
13
|
|
|
14
|
+
// Plugins import peer packages such as @deepseek-ai/dsh-session that live in the
|
|
15
|
+
// DSH installation, not in the profile. Resolve those from the install root so
|
|
16
|
+
// the probe can measure the real entry module.
|
|
17
|
+
if (installDir && typeof nodeModule.registerHooks === 'function') {
|
|
18
|
+
try {
|
|
19
|
+
const requireFromInstall = createRequire(path.join(installDir, 'package.json'))
|
|
20
|
+
nodeModule.registerHooks({
|
|
21
|
+
resolve(specifier, context, nextResolve) {
|
|
22
|
+
if (specifier.startsWith('@deepseek-ai/') || specifier === 'cordis') {
|
|
23
|
+
try {
|
|
24
|
+
return { url: pathToFileURL(requireFromInstall.resolve(specifier)).href, shortCircuit: true }
|
|
25
|
+
} catch {
|
|
26
|
+
// fall through to the default resolver
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return nextResolve(specifier, context)
|
|
30
|
+
},
|
|
31
|
+
})
|
|
32
|
+
} catch {
|
|
33
|
+
// hooks are best effort; the probe still measures what resolves normally
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
12
37
|
async function main() {
|
|
13
38
|
if (!profileDir || !packageName) {
|
|
14
39
|
console.log(JSON.stringify({ ok: false, error: 'missing-args' }))
|
package/lib/budget-probe.js
CHANGED
|
@@ -12,10 +12,11 @@ const CHILD = fileURLToPath(new URL('./budget-child.mjs', import.meta.url))
|
|
|
12
12
|
export function probeBudget({ profileDir, packageName, timeoutMs = 25_000 } = {}) {
|
|
13
13
|
return new Promise((resolve) => {
|
|
14
14
|
const nodeExe = process.env.DSH_PROBE_NODE || process.execPath
|
|
15
|
+
const installDir = process.env.DSH_INSTALL_DIR || (typeof process.argv[2] === 'string' && process.argv[2].endsWith('package.json') === false ? process.argv[2] : '')
|
|
15
16
|
const env = { ...process.env }
|
|
16
17
|
if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1'
|
|
17
18
|
delete env.NODE_OPTIONS
|
|
18
|
-
const child = spawn(nodeExe, ['--expose-gc', CHILD, profileDir, packageName], {
|
|
19
|
+
const child = spawn(nodeExe, ['--expose-gc', CHILD, profileDir, packageName, installDir || ''], {
|
|
19
20
|
env,
|
|
20
21
|
windowsHide: true,
|
|
21
22
|
stdio: ['ignore', 'pipe', 'pipe'],
|
package/lib/tamper-monitor.js
CHANGED
|
@@ -33,7 +33,9 @@ export function snapshotCriticalFiles(profileDir) {
|
|
|
33
33
|
const file = path.join(profileDir, rel)
|
|
34
34
|
const bytes = readIfExists(file)
|
|
35
35
|
contents.set(rel, bytes)
|
|
36
|
-
|
|
36
|
+
let mtimeMs = 0
|
|
37
|
+
try { mtimeMs = fs.statSync(file).mtimeMs } catch { mtimeMs = 0 }
|
|
38
|
+
files.push({ file: rel, exists: bytes !== null, hash: bytes === null ? null : sha256(bytes), size: bytes === null ? 0 : bytes.length, mtimeMs })
|
|
37
39
|
}
|
|
38
40
|
return { files, contents }
|
|
39
41
|
}
|
|
@@ -45,9 +47,9 @@ export function diffSnapshots(previous, next) {
|
|
|
45
47
|
for (const entry of next || []) {
|
|
46
48
|
const old = before.get(entry.file)
|
|
47
49
|
if (!old) continue
|
|
48
|
-
if (!old.exists && entry.exists) diffs.push({ file: entry.file, kind: 'created' })
|
|
49
|
-
else if (old.exists && !entry.exists) diffs.push({ file: entry.file, kind: 'deleted' })
|
|
50
|
-
else if (old.exists && entry.exists && old.hash !== entry.hash) diffs.push({ file: entry.file, kind: 'modified' })
|
|
50
|
+
if (!old.exists && entry.exists) diffs.push({ file: entry.file, kind: 'created', mtimeMs: entry.mtimeMs })
|
|
51
|
+
else if (old.exists && !entry.exists) diffs.push({ file: entry.file, kind: 'deleted', mtimeMs: entry.mtimeMs })
|
|
52
|
+
else if (old.exists && entry.exists && old.hash !== entry.hash) diffs.push({ file: entry.file, kind: 'modified', mtimeMs: entry.mtimeMs })
|
|
51
53
|
}
|
|
52
54
|
return diffs
|
|
53
55
|
}
|
|
@@ -108,6 +110,7 @@ export function createTamperMonitor({
|
|
|
108
110
|
graceMs = STARTUP_GRACE_MS,
|
|
109
111
|
intervalMs = DEFAULT_INTERVAL_MS,
|
|
110
112
|
shouldIgnore,
|
|
113
|
+
isWithinOperationWindow,
|
|
111
114
|
onTamper,
|
|
112
115
|
log,
|
|
113
116
|
} = {}) {
|
|
@@ -138,9 +141,13 @@ export function createTamperMonitor({
|
|
|
138
141
|
status.skipped = null
|
|
139
142
|
return { ok: true, diffs: [], restored: [] }
|
|
140
143
|
}
|
|
144
|
+
// A changed file written inside a plugin-manager operation window is a
|
|
145
|
+
// legitimate manager write even when this poll runs after the window closed.
|
|
146
|
+
const withinWindow = (mtimeMs) => typeof isWithinOperationWindow === 'function' && isWithinOperationWindow(mtimeMs)
|
|
147
|
+
const suspicious = force ? diffs : diffs.filter((diff) => !withinWindow(diff.mtimeMs))
|
|
141
148
|
const startup = !force && Date.now() - baselineAt < graceMs
|
|
142
149
|
const ignored = !force && typeof shouldIgnore === 'function' && shouldIgnore()
|
|
143
|
-
if (startup || ignored) {
|
|
150
|
+
if (startup || ignored || suspicious.length === 0) {
|
|
144
151
|
baseline = next
|
|
145
152
|
baselineAt = Date.now()
|
|
146
153
|
status.skipped = startup ? 'startup' : 'operation-window'
|
|
@@ -148,16 +155,16 @@ export function createTamperMonitor({
|
|
|
148
155
|
if (typeof log === 'function') log(`tamper monitor: ${diffs.map((d) => d.file).join(', ')} ${status.skipped}(视为正常写入)`)
|
|
149
156
|
return { ok: true, diffs: [], restored: [], skipped: status.skipped }
|
|
150
157
|
}
|
|
151
|
-
const backup = backupTampered(dataDir, profileDir,
|
|
152
|
-
const restored = policy === 'restore' ? restoreBaseline(profileDir, baseline.contents,
|
|
153
|
-
status.lastDiff =
|
|
158
|
+
const backup = backupTampered(dataDir, profileDir, suspicious)
|
|
159
|
+
const restored = policy === 'restore' ? restoreBaseline(profileDir, baseline.contents, suspicious) : []
|
|
160
|
+
status.lastDiff = suspicious
|
|
154
161
|
status.restored = restored
|
|
155
162
|
status.incidents += 1
|
|
156
163
|
// Re-baseline on the post-restore state so one drift yields one alert.
|
|
157
164
|
baseline = snapshotCriticalFiles(profileDir)
|
|
158
165
|
baselineAt = Date.now()
|
|
159
166
|
if (backup.length > 0 && typeof log === 'function') log(`tamper monitor: 备份到 ${backup.length} 个文件`)
|
|
160
|
-
if (typeof onTamper === 'function') onTamper({ diffs, restored, policy, backup })
|
|
167
|
+
if (typeof onTamper === 'function') onTamper({ diffs: suspicious, restored, policy, backup })
|
|
161
168
|
return { ok: true, diffs, restored, backup }
|
|
162
169
|
}
|
|
163
170
|
|
package/lib/watchdog-runtime.js
CHANGED
|
@@ -137,6 +137,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
137
137
|
|
|
138
138
|
let lastFlush = 0
|
|
139
139
|
let operationWindowUntil = 0
|
|
140
|
+
const operationWindows = []
|
|
141
|
+
let tamperMigrationDone = false
|
|
140
142
|
let tamper = null
|
|
141
143
|
restoreState()
|
|
142
144
|
readCrashLogs()
|
|
@@ -155,6 +157,10 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
155
157
|
graceMs: Number(config.tamperGraceMs) >= 0 ? Number(config.tamperGraceMs) : 15_000,
|
|
156
158
|
intervalMs: Number(config.tamperIntervalMs) > 0 ? Number(config.tamperIntervalMs) : 30_000,
|
|
157
159
|
shouldIgnore: () => Date.now() < operationWindowUntil,
|
|
160
|
+
isWithinOperationWindow: (mtimeMs) => {
|
|
161
|
+
const now = Date.now()
|
|
162
|
+
return operationWindows.some((window) => mtimeMs >= window.startedAt - 5000 && mtimeMs <= (window.settledAt || now) + 5000)
|
|
163
|
+
},
|
|
158
164
|
onTamper: handleTamper,
|
|
159
165
|
log: (message) => log.info('[ai-prison-watchdog] ' + message),
|
|
160
166
|
})
|
|
@@ -212,6 +218,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
212
218
|
baseline: watchdogState.baseline,
|
|
213
219
|
budgets: watchdogState.budgets,
|
|
214
220
|
quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
|
|
221
|
+
migratedTamperQuarantine: tamperMigrationDone,
|
|
215
222
|
}
|
|
216
223
|
try {
|
|
217
224
|
fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
|
|
@@ -228,10 +235,20 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
228
235
|
if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
|
|
229
236
|
if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
|
|
230
237
|
if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
|
|
238
|
+
tamperMigrationDone = parsed.migratedTamperQuarantine === true
|
|
231
239
|
if (Array.isArray(parsed.quarantine)) {
|
|
240
|
+
let dropped = 0
|
|
232
241
|
for (const entry of parsed.quarantine) {
|
|
242
|
+
if (!tamperMigrationDone && entry && entry.reason === 'tamper') {
|
|
243
|
+
dropped += 1
|
|
244
|
+
continue
|
|
245
|
+
}
|
|
233
246
|
if (entry && typeof entry.target === 'string') watchdogState.quarantine.set(entry.target, { reason: entry.reason || 'crash', level: entry.level || 'L1', at: entry.at || new Date().toISOString(), release: entry.release || 'manual', evidence: entry.evidence || '' })
|
|
234
247
|
}
|
|
248
|
+
if (dropped > 0) {
|
|
249
|
+
watchdogState.incidents.push({ at: new Date().toISOString(), mode: watchdogState.mode, kind: 'migration', detail: '清理 ' + dropped + ' 条 1.4.3/1.4.4 误判的 tamper 隔离(操作窗口归因已修复)' })
|
|
250
|
+
}
|
|
251
|
+
tamperMigrationDone = true
|
|
235
252
|
}
|
|
236
253
|
} catch {
|
|
237
254
|
// first run or unreadable state: start clean
|
|
@@ -376,6 +393,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
376
393
|
const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
|
|
377
394
|
if (operation.phase === 'started') {
|
|
378
395
|
operationWindowUntil = Date.now() + 4000
|
|
396
|
+
operationWindows.push({ startedAt: Date.now(), settledAt: null })
|
|
397
|
+
if (operationWindows.length > 20) operationWindows.shift()
|
|
379
398
|
inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
|
|
380
399
|
entry.lastAt = operation.time || entry.lastAt
|
|
381
400
|
watchdogState.operations.set(target, entry)
|
|
@@ -383,6 +402,9 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
383
402
|
}
|
|
384
403
|
if (operation.phase !== 'settled') return
|
|
385
404
|
operationWindowUntil = Date.now() + 4000
|
|
405
|
+
for (let i = operationWindows.length - 1; i >= 0; i -= 1) {
|
|
406
|
+
if (operationWindows[i].settledAt === null) { operationWindows[i].settledAt = Date.now(); break }
|
|
407
|
+
}
|
|
386
408
|
const weight = operationWeight(operation)
|
|
387
409
|
if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
|
|
388
410
|
entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
|
|
@@ -515,18 +537,52 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
515
537
|
}
|
|
516
538
|
}
|
|
517
539
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
540
|
+
const probeFn = typeof config.probe === 'function' ? config.probe : probeBudget
|
|
541
|
+
const probeMax = Number(config.probeMax) > 0 ? Number(config.probeMax) : 5
|
|
542
|
+
const probeRetryMs = Number(config.probeRetryMs) > 0 ? Number(config.probeRetryMs) : 10 * 60 * 1000
|
|
543
|
+
const probeMaxAgeMs = 7 * 24 * 3600 * 1000
|
|
544
|
+
|
|
545
|
+
function budgetState(name, version) {
|
|
546
|
+
const entry = watchdogState.budgets[name]
|
|
547
|
+
if (!entry) return 'missing'
|
|
548
|
+
if (entry.error) {
|
|
549
|
+
const age = Date.now() - Date.parse(entry.measuredAt || 0)
|
|
550
|
+
return age > probeRetryMs && (Number(entry.attempts) || 0) < 5 ? 'retry' : 'error'
|
|
551
|
+
}
|
|
552
|
+
if (entry.moduleLoadMB === undefined) return 'stale'
|
|
553
|
+
if (!entry.version || (version && entry.version !== version)) return 'stale'
|
|
554
|
+
if (Date.now() - Date.parse(entry.measuredAt || 0) > probeMaxAgeMs) return 'stale'
|
|
555
|
+
return 'ok'
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async function probeOne(name, version) {
|
|
559
|
+
const previous = watchdogState.budgets[name] || {}
|
|
560
|
+
watchdogState.probeProgress = { ...(watchdogState.probeProgress || { done: 0, total: 0 }), current: name }
|
|
561
|
+
const result = await probeFn({ profileDir, packageName: name })
|
|
562
|
+
if (!result || !result.ok) {
|
|
563
|
+
watchdogState.budgets[name] = {
|
|
564
|
+
error: String((result && result.error) || 'probe-failed').slice(0, 300),
|
|
565
|
+
measuredAt: new Date().toISOString(),
|
|
566
|
+
version: version || previous.version || null,
|
|
567
|
+
attempts: (Number(previous.attempts) || 0) + 1,
|
|
568
|
+
source: 'module-load-probe',
|
|
569
|
+
}
|
|
522
570
|
persist(true)
|
|
523
|
-
return
|
|
571
|
+
return { ok: false }
|
|
572
|
+
}
|
|
573
|
+
watchdogState.budgets[name] = {
|
|
574
|
+
moduleLoadMB: result.moduleLoadMB,
|
|
575
|
+
rssMB: result.rssMB,
|
|
576
|
+
ms: result.ms,
|
|
577
|
+
measuredAt: new Date().toISOString(),
|
|
578
|
+
version: version || null,
|
|
579
|
+
attempts: (Number(previous.attempts) || 0) + 1,
|
|
580
|
+
source: 'module-load-probe',
|
|
524
581
|
}
|
|
525
|
-
watchdogState.budgets[name] = { moduleLoadMB: result.moduleLoadMB, rssMB: result.rssMB, ms: result.ms, measuredAt: new Date().toISOString(), source: 'module-load-probe' }
|
|
526
582
|
const thresholds = watchdogState.thresholds
|
|
527
583
|
const mb = result.moduleLoadMB
|
|
528
584
|
if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
|
|
529
|
-
appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB
|
|
585
|
+
appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,禁止该插件' })
|
|
530
586
|
if (watchdogState.enforce) {
|
|
531
587
|
watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB' })
|
|
532
588
|
void disableTarget(name, 'budget-over-500MB')
|
|
@@ -536,18 +592,18 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
536
592
|
appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
|
|
537
593
|
}
|
|
538
594
|
persist(true)
|
|
595
|
+
return { ok: true }
|
|
539
596
|
}
|
|
540
597
|
|
|
541
|
-
async function scheduleProbe() {
|
|
542
|
-
if (watchdogState.
|
|
543
|
-
watchdogState.probeStarted = true
|
|
598
|
+
async function scheduleProbe({ force = false } = {}) {
|
|
599
|
+
if (watchdogState.probeRunning) return watchdogState.probeProgress
|
|
544
600
|
const manager = refs.manager
|
|
545
|
-
if (!manager || typeof manager.listBundles !== 'function') return
|
|
601
|
+
if (!manager || typeof manager.listBundles !== 'function') return null
|
|
546
602
|
let rows
|
|
547
603
|
try {
|
|
548
604
|
rows = await manager.listBundles()
|
|
549
605
|
} catch {
|
|
550
|
-
return
|
|
606
|
+
return null
|
|
551
607
|
}
|
|
552
608
|
const recent = new Set()
|
|
553
609
|
const cutoff = Date.now() - 30 * 60 * 1000
|
|
@@ -558,14 +614,25 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
558
614
|
if (Date.parse(operation.time || 0) < cutoff) continue
|
|
559
615
|
recent.add(operation.target)
|
|
560
616
|
}
|
|
561
|
-
const
|
|
562
|
-
.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name)
|
|
563
|
-
.map((row) => row.name)
|
|
564
|
-
.
|
|
565
|
-
|
|
617
|
+
const candidates = rows
|
|
618
|
+
.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name))
|
|
619
|
+
.map((row) => ({ name: row.name, version: row.version ? String(row.version) : '', state: budgetState(row.name, row.version ? String(row.version) : '') }))
|
|
620
|
+
.filter((candidate) => candidate.state !== 'ok')
|
|
621
|
+
.sort((a, b) => (recent.has(b.name) ? 1 : 0) - (recent.has(a.name) ? 1 : 0))
|
|
622
|
+
.slice(0, force ? Math.max(probeMax, Number(config.probeMaxForce) > 0 ? Number(config.probeMaxForce) : 15) : probeMax)
|
|
623
|
+
watchdogState.probeProgress = { done: 0, total: candidates.length, current: null, finishedAt: null }
|
|
624
|
+
if (candidates.length === 0) return watchdogState.probeProgress
|
|
625
|
+
watchdogState.probeRunning = true
|
|
626
|
+
for (const candidate of candidates) {
|
|
566
627
|
if (watchdogState.waterline !== 'ok') break
|
|
567
|
-
await probeOne(name)
|
|
628
|
+
const outcome = await probeOne(candidate.name, candidate.version)
|
|
629
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, done: watchdogState.probeProgress.done + 1, current: candidate.name, lastOk: Boolean(outcome && outcome.ok) }
|
|
630
|
+
if (candidates.length > 1) await new Promise((resolve) => setTimeout(resolve, Number(config.probeGapMs) >= 0 ? Number(config.probeGapMs) : 1500))
|
|
568
631
|
}
|
|
632
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, current: null, finishedAt: new Date().toISOString() }
|
|
633
|
+
watchdogState.probeRunning = false
|
|
634
|
+
persist(true)
|
|
635
|
+
return watchdogState.probeProgress
|
|
569
636
|
}
|
|
570
637
|
|
|
571
638
|
// ---- crash attribution and dry-run plans (requirements 3 & 4) -----------
|
|
@@ -737,6 +804,10 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
737
804
|
}
|
|
738
805
|
const action = typeof body.action === 'string' ? body.action : ''
|
|
739
806
|
const target = typeof body.target === 'string' ? body.target : ''
|
|
807
|
+
if (action === 'probe') {
|
|
808
|
+
const progress = await scheduleProbe({ force: true })
|
|
809
|
+
return Response.json({ ok: true, progress })
|
|
810
|
+
}
|
|
740
811
|
if (action === 'confirm-pause') {
|
|
741
812
|
watchdogState.graceUntil = Date.now() + PAUSE_GRACE_MS
|
|
742
813
|
appendIncident({ kind: 'pause-confirmed', detail: `用户二次确认继续插件操作(宽限 10 分钟)` })
|
|
@@ -766,6 +837,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
766
837
|
snapshot: watchdogSnapshot,
|
|
767
838
|
sample,
|
|
768
839
|
readCrashLogs,
|
|
840
|
+
probeNow: (options) => scheduleProbe(options),
|
|
769
841
|
tamperCheck: (options) => {
|
|
770
842
|
if (!tamper) return null
|
|
771
843
|
const result = tamper.checkNow(options)
|
|
@@ -787,6 +859,29 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
787
859
|
}
|
|
788
860
|
}
|
|
789
861
|
|
|
862
|
+
/** Merge live operation estimates with measured module-load budgets (measured wins). */
|
|
863
|
+
function mergedTop(state, limit) {
|
|
864
|
+
const operations = topOperations(state.operations, 50)
|
|
865
|
+
const measured = []
|
|
866
|
+
for (const [target, entry] of Object.entries(state.budgets || {})) {
|
|
867
|
+
if (!entry || entry.error || entry.moduleLoadMB === undefined) continue
|
|
868
|
+
const existing = operations.find((row) => row.target === target)
|
|
869
|
+
measured.push({
|
|
870
|
+
target,
|
|
871
|
+
count: existing ? existing.count : 0,
|
|
872
|
+
estimateMB: entry.moduleLoadMB,
|
|
873
|
+
lastAt: entry.measuredAt || (existing ? existing.lastAt : null),
|
|
874
|
+
version: entry.version || (existing ? existing.version : null),
|
|
875
|
+
source: 'measured',
|
|
876
|
+
measuredAt: entry.measuredAt || null,
|
|
877
|
+
})
|
|
878
|
+
}
|
|
879
|
+
const others = operations
|
|
880
|
+
.filter((row) => !measured.some((entry) => entry.target === row.target))
|
|
881
|
+
.map((row) => ({ ...row, source: 'estimate' }))
|
|
882
|
+
return [...measured, ...others].sort((a, b) => b.estimateMB - a.estimateMB || b.count - a.count).slice(0, Math.max(1, limit))
|
|
883
|
+
}
|
|
884
|
+
|
|
790
885
|
/** Serialisable snapshot shared by the tool and the panel route. */
|
|
791
886
|
export function watchdogSnapshot() {
|
|
792
887
|
const s = watchdogState
|
|
@@ -810,8 +905,9 @@ export function watchdogSnapshot() {
|
|
|
810
905
|
graceUntil: s.graceUntil,
|
|
811
906
|
frozenAt: s.frozenAt,
|
|
812
907
|
samples: s.samples.slice(-30),
|
|
813
|
-
operations:
|
|
814
|
-
topFive:
|
|
908
|
+
operations: mergedTop(s, 10),
|
|
909
|
+
topFive: mergedTop(s, 5),
|
|
910
|
+
probeProgress: s.probeProgress || null,
|
|
815
911
|
quarantine,
|
|
816
912
|
plans: s.plans.slice(-5),
|
|
817
913
|
escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
|
package/locale/en.json
CHANGED
|
@@ -17,5 +17,6 @@
|
|
|
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), last check {at}"
|
|
20
|
+
"watchdog.tamper": "Profile watch: {n} critical file(s), last check {at}",
|
|
21
|
+
"watchdog.measure": "Measure plugin budgets now"
|
|
21
22
|
}
|
package/locale/zh.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twinsearth/ai-prison-dsh-plugin",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.5",
|
|
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",
|