@twinsearth/ai-prison-dsh-plugin 1.4.2 → 1.4.4
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 +50 -0
- package/client.js +5 -0
- package/lib/budget-child.mjs +53 -0
- package/lib/tamper-monitor.js +182 -0
- package/lib/tools.js +1 -0
- package/lib/watchdog-runtime.js +167 -21
- package/lib/watchdog-state.js +3 -0
- package/locale/en.json +3 -1
- package/locale/zh.json +3 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,56 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
|
|
4
4
|
|
|
5
|
+
## [1.4.4] — 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Fixed — per-plugin budget probe actually works end to end
|
|
8
|
+
|
|
9
|
+
- The probe now covers **every enabled, non-exempt bundle without a current
|
|
10
|
+
measurement** (not only plugins installed/enabled in the last 30 minutes),
|
|
11
|
+
scheduled after boot (max 5 per run) and retried after failures (error entries
|
|
12
|
+
older than 10 minutes, up to 5 attempts).
|
|
13
|
+
- Budgets are version-aware: an entry measured for another version, without a
|
|
14
|
+
version, older than 7 days, or failed is treated as stale and re-measured.
|
|
15
|
+
- A manual "Measure plugin budgets now" button in the Enforcement card and a
|
|
16
|
+
`probe` action on the watchdog route run the queue immediately (up to 15
|
|
17
|
+
targets) and report `probeProgress`.
|
|
18
|
+
- The measured module-load MB **wins over operation estimates in Top5** and is
|
|
19
|
+
labelled `source: "measured"`; operation-derived rows stay `estimate`.
|
|
20
|
+
- >500 MB still quarantines, closes and queues the plugin in
|
|
21
|
+
`pending-boot.json`; 300–500 MB records a warning only.
|
|
22
|
+
- Tests: `test/watchdog-budget.test.mjs` covers the 600 MB quarantine path,
|
|
23
|
+
the 420 MB warning path with measured Top5, and failed-probe retry counting.
|
|
24
|
+
|
|
25
|
+
## [1.4.3] — 2026-11-18
|
|
26
|
+
## [1.4.3] — 2026-11-18
|
|
27
|
+
|
|
28
|
+
### Added — profile tamper monitor (requirement 3, the missing half)
|
|
29
|
+
|
|
30
|
+
- **Hash watch of the critical profile files** (`package.json`,
|
|
31
|
+
`cordis.patch.yml`, `cordis.yml`, `pnpm-workspace.yaml`, `pnpm-lock.yaml`):
|
|
32
|
+
a baseline with the original bytes is captured at watchdog start, the files are
|
|
33
|
+
re-hashed every 30 s, and the first 15 s after startup are treated as normal
|
|
34
|
+
startup writes.
|
|
35
|
+
- A drift **outside a plugin-manager operation window** (±4 s around
|
|
36
|
+
started/settled) is tampering: the changed bytes are copied to
|
|
37
|
+
`.ai-prison-watchdog/tampered/<ts>/`, the original bytes are restored by
|
|
38
|
+
default (`tamperPolicy: 'alert'` keeps the change), and an L1 plan is
|
|
39
|
+
attributed from the operation journal (in-flight install/enable first). In
|
|
40
|
+
enforce mode the attributed plugin is quarantined, closed and queued in
|
|
41
|
+
`pending-boot.json` for the external guard.
|
|
42
|
+
- New `tamper` block in the watchdog snapshot/tool output, and a "Profile
|
|
43
|
+
watch" line in the panel Enforcement card.
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
- `lib/budget-child.mjs` was missing from the npm package (`files` only
|
|
47
|
+
matched `lib/*.js`), which made every per-plugin budget probe fail with
|
|
48
|
+
"Cannot find module". `files` now ships `lib/*.mjs` too.
|
|
49
|
+
|
|
50
|
+
### Tests
|
|
51
|
+
- New `test/tamper-monitor.test.mjs`: snapshot/diff/restore, real runtime drift
|
|
52
|
+
detection with restore, operation-window suppression, and the alert policy.
|
|
53
|
+
|
|
54
|
+
## [1.4.2] — 2026-11-18
|
|
5
55
|
## [1.4.2] — 2026-11-18
|
|
6
56
|
|
|
7
57
|
### Added
|
package/client.js
CHANGED
|
@@ -464,6 +464,11 @@ window.__ModuleLoader__.load({
|
|
|
464
464
|
plan.at + ' · ' + plan.level + ' · ' + (plan.target || 'unattributed') + (plan.inFlight ? ' (in-flight)' : '') + (plan.crash ? ' · ' + (plan.crash.oom ? 'OOM' : 'exit ' + plan.crash.hostExitCode) : ''))),
|
|
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
|
+
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
|
+
),
|
|
467
472
|
)
|
|
468
473
|
}
|
|
469
474
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
|
|
4
|
+
// 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
|
+
|
|
8
|
+
function heapMB() {
|
|
9
|
+
return process.memoryUsage().heapUsed / (1024 * 1024)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function main() {
|
|
13
|
+
if (!profileDir || !packageName) {
|
|
14
|
+
console.log(JSON.stringify({ ok: false, error: 'missing-args' }))
|
|
15
|
+
return
|
|
16
|
+
}
|
|
17
|
+
if (typeof global.gc !== 'function') {
|
|
18
|
+
console.log(JSON.stringify({ ok: false, error: 'no-gc' }))
|
|
19
|
+
return
|
|
20
|
+
}
|
|
21
|
+
let entry
|
|
22
|
+
try {
|
|
23
|
+
const require = createRequire(`${profileDir}/package.json`)
|
|
24
|
+
entry = require.resolve(packageName)
|
|
25
|
+
} catch (error) {
|
|
26
|
+
try {
|
|
27
|
+
entry = import.meta.resolve(packageName)
|
|
28
|
+
} catch {
|
|
29
|
+
console.log(JSON.stringify({ ok: false, error: `unresolved: ${String((error && error.message) || error)}` }))
|
|
30
|
+
return
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
global.gc()
|
|
34
|
+
const before = heapMB()
|
|
35
|
+
const started = Date.now()
|
|
36
|
+
try {
|
|
37
|
+
await import(pathToFileURL(entry).href)
|
|
38
|
+
} catch (error) {
|
|
39
|
+
console.log(JSON.stringify({ ok: false, error: `import-failed: ${String((error && error.message) || error).slice(0, 300)}` }))
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
global.gc()
|
|
43
|
+
const after = heapMB()
|
|
44
|
+
console.log(JSON.stringify({
|
|
45
|
+
ok: true,
|
|
46
|
+
moduleLoadMB: Math.max(0, Math.round(after - before)),
|
|
47
|
+
rssMB: Math.round(process.memoryUsage().rss / (1024 * 1024)),
|
|
48
|
+
ms: Date.now() - started,
|
|
49
|
+
entry,
|
|
50
|
+
}))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
await main()
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Hash watch for the profile files a plugin must never change behind the plugin
|
|
7
|
+
* manager's back. A drift outside a plugin-manager operation window is treated
|
|
8
|
+
* as tampering: the original bytes are restored (policy "restore") and the
|
|
9
|
+
* watchdog raises an L1 plan for the last installed/updated plugin.
|
|
10
|
+
*/
|
|
11
|
+
export const CRITICAL_FILES = ['package.json', 'cordis.patch.yml', 'cordis.yml', 'pnpm-workspace.yaml', 'pnpm-lock.yaml']
|
|
12
|
+
export const OPERATION_GRACE_MS = 4000
|
|
13
|
+
export const STARTUP_GRACE_MS = 15000
|
|
14
|
+
export const DEFAULT_INTERVAL_MS = 30000
|
|
15
|
+
|
|
16
|
+
export function sha256(buffer) {
|
|
17
|
+
return crypto.createHash('sha256').update(buffer).digest('hex')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function readIfExists(file) {
|
|
21
|
+
try {
|
|
22
|
+
return fs.readFileSync(file)
|
|
23
|
+
} catch {
|
|
24
|
+
return null
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Snapshot the critical profile files, keeping the bytes needed for restore. */
|
|
29
|
+
export function snapshotCriticalFiles(profileDir) {
|
|
30
|
+
const files = []
|
|
31
|
+
const contents = new Map()
|
|
32
|
+
for (const rel of CRITICAL_FILES) {
|
|
33
|
+
const file = path.join(profileDir, rel)
|
|
34
|
+
const bytes = readIfExists(file)
|
|
35
|
+
contents.set(rel, bytes)
|
|
36
|
+
files.push({ file: rel, exists: bytes !== null, hash: bytes === null ? null : sha256(bytes), size: bytes === null ? 0 : bytes.length })
|
|
37
|
+
}
|
|
38
|
+
return { files, contents }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Difference between two snapshot file lists. */
|
|
42
|
+
export function diffSnapshots(previous, next) {
|
|
43
|
+
const before = new Map((previous || []).map((entry) => [entry.file, entry]))
|
|
44
|
+
const diffs = []
|
|
45
|
+
for (const entry of next || []) {
|
|
46
|
+
const old = before.get(entry.file)
|
|
47
|
+
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' })
|
|
51
|
+
}
|
|
52
|
+
return diffs
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Persist the tampered bytes next to the watchdog state for evidence. */
|
|
56
|
+
export function backupTampered(dataDir, profileDir, diffs) {
|
|
57
|
+
if (!Array.isArray(diffs) || diffs.length === 0) return []
|
|
58
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
59
|
+
const dir = path.join(dataDir, 'tampered', stamp)
|
|
60
|
+
const written = []
|
|
61
|
+
try {
|
|
62
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
63
|
+
} catch {
|
|
64
|
+
return written
|
|
65
|
+
}
|
|
66
|
+
for (const diff of diffs) {
|
|
67
|
+
const bytes = readIfExists(path.join(profileDir, diff.file))
|
|
68
|
+
if (bytes === null) continue
|
|
69
|
+
const target = path.join(dir, diff.file.replace(/[\\/]/g, '__'))
|
|
70
|
+
try {
|
|
71
|
+
fs.writeFileSync(target, bytes)
|
|
72
|
+
written.push(target)
|
|
73
|
+
} catch {
|
|
74
|
+
// evidence is best effort
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return written
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Restore the baseline bytes for modified/deleted files. Created files are not removed. */
|
|
81
|
+
export function restoreBaseline(profileDir, baselineContents, diffs) {
|
|
82
|
+
const restored = []
|
|
83
|
+
for (const diff of diffs || []) {
|
|
84
|
+
if (diff.kind === 'created') continue
|
|
85
|
+
const bytes = baselineContents instanceof Map ? baselineContents.get(diff.file) : null
|
|
86
|
+
if (!bytes) continue
|
|
87
|
+
try {
|
|
88
|
+
fs.mkdirSync(path.dirname(path.join(profileDir, diff.file)), { recursive: true })
|
|
89
|
+
fs.writeFileSync(path.join(profileDir, diff.file), bytes)
|
|
90
|
+
restored.push(diff.file)
|
|
91
|
+
} catch {
|
|
92
|
+
// restore is best effort; the incident still reports the drift
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return restored
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Create the profile tamper monitor.
|
|
100
|
+
* `shouldIgnore()` lets the caller suppress legitimate write windows (plugin
|
|
101
|
+
* manager operations); `onTamper({diffs, restored, files})` fires once per
|
|
102
|
+
* detected drift.
|
|
103
|
+
*/
|
|
104
|
+
export function createTamperMonitor({
|
|
105
|
+
profileDir,
|
|
106
|
+
dataDir,
|
|
107
|
+
policy = 'restore',
|
|
108
|
+
graceMs = STARTUP_GRACE_MS,
|
|
109
|
+
intervalMs = DEFAULT_INTERVAL_MS,
|
|
110
|
+
shouldIgnore,
|
|
111
|
+
onTamper,
|
|
112
|
+
log,
|
|
113
|
+
} = {}) {
|
|
114
|
+
const base = snapshotCriticalFiles(profileDir)
|
|
115
|
+
let baseline = base
|
|
116
|
+
let baselineAt = Date.now()
|
|
117
|
+
let timer = null
|
|
118
|
+
const status = {
|
|
119
|
+
enabled: true,
|
|
120
|
+
policy,
|
|
121
|
+
files: base.files.map((entry) => entry.file),
|
|
122
|
+
baselineAt: new Date(baselineAt).toISOString(),
|
|
123
|
+
lastCheckAt: null,
|
|
124
|
+
lastDiff: [],
|
|
125
|
+
restored: [],
|
|
126
|
+
skipped: null,
|
|
127
|
+
incidents: 0,
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function checkNow({ force = false } = {}) {
|
|
131
|
+
const next = snapshotCriticalFiles(profileDir)
|
|
132
|
+
const diffs = diffSnapshots(baseline.files, next.files)
|
|
133
|
+
status.lastCheckAt = new Date().toISOString()
|
|
134
|
+
if (diffs.length === 0) {
|
|
135
|
+
baseline = next
|
|
136
|
+
baselineAt = Date.now()
|
|
137
|
+
status.lastDiff = []
|
|
138
|
+
status.skipped = null
|
|
139
|
+
return { ok: true, diffs: [], restored: [] }
|
|
140
|
+
}
|
|
141
|
+
const startup = !force && Date.now() - baselineAt < graceMs
|
|
142
|
+
const ignored = !force && typeof shouldIgnore === 'function' && shouldIgnore()
|
|
143
|
+
if (startup || ignored) {
|
|
144
|
+
baseline = next
|
|
145
|
+
baselineAt = Date.now()
|
|
146
|
+
status.skipped = startup ? 'startup' : 'operation-window'
|
|
147
|
+
status.lastDiff = []
|
|
148
|
+
if (typeof log === 'function') log(`tamper monitor: ${diffs.map((d) => d.file).join(', ')} ${status.skipped}(视为正常写入)`)
|
|
149
|
+
return { ok: true, diffs: [], restored: [], skipped: status.skipped }
|
|
150
|
+
}
|
|
151
|
+
const backup = backupTampered(dataDir, profileDir, diffs)
|
|
152
|
+
const restored = policy === 'restore' ? restoreBaseline(profileDir, baseline.contents, diffs) : []
|
|
153
|
+
status.lastDiff = diffs
|
|
154
|
+
status.restored = restored
|
|
155
|
+
status.incidents += 1
|
|
156
|
+
// Re-baseline on the post-restore state so one drift yields one alert.
|
|
157
|
+
baseline = snapshotCriticalFiles(profileDir)
|
|
158
|
+
baselineAt = Date.now()
|
|
159
|
+
if (backup.length > 0 && typeof log === 'function') log(`tamper monitor: 备份到 ${backup.length} 个文件`)
|
|
160
|
+
if (typeof onTamper === 'function') onTamper({ diffs, restored, policy, backup })
|
|
161
|
+
return { ok: true, diffs, restored, backup }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function start() {
|
|
165
|
+
if (timer || !(intervalMs > 0)) return
|
|
166
|
+
timer = setInterval(() => {
|
|
167
|
+
try {
|
|
168
|
+
checkNow()
|
|
169
|
+
} catch {
|
|
170
|
+
// keep polling; a read failure must not stop the monitor
|
|
171
|
+
}
|
|
172
|
+
}, intervalMs)
|
|
173
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function stop() {
|
|
177
|
+
if (timer) clearInterval(timer)
|
|
178
|
+
timer = null
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return { checkNow, start, stop, status: () => ({ ...status }), snapshot: () => baseline.files }
|
|
182
|
+
}
|
package/lib/tools.js
CHANGED
|
@@ -213,6 +213,7 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
|
|
|
213
213
|
escalation: snapshot.escalation,
|
|
214
214
|
baselineAt: snapshot.baseline ? snapshot.baseline.at : null,
|
|
215
215
|
budgets: snapshot.budgets,
|
|
216
|
+
tamper: snapshot.tamper,
|
|
216
217
|
operations: snapshot.operations,
|
|
217
218
|
incidents: snapshot.incidents,
|
|
218
219
|
note: snapshot.enforce
|
package/lib/watchdog-runtime.js
CHANGED
|
@@ -5,6 +5,7 @@ import v8 from 'node:v8'
|
|
|
5
5
|
import crypto from 'node:crypto'
|
|
6
6
|
import { watchdogState, MAX_SAMPLES, MAX_INCIDENTS } from './watchdog-state.js'
|
|
7
7
|
import { probeBudget } from './budget-probe.js'
|
|
8
|
+
import { createTamperMonitor } from './tamper-monitor.js'
|
|
8
9
|
import {
|
|
9
10
|
attributeCrash,
|
|
10
11
|
classifyWaterline,
|
|
@@ -97,7 +98,7 @@ function readJournalRecords(journalDir) {
|
|
|
97
98
|
|
|
98
99
|
/** Read-only watchdog runtime. Enforcement never touches plugin files, only the manager API. */
|
|
99
100
|
export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
100
|
-
const profileDir = resolveProfileDir()
|
|
101
|
+
const profileDir = config.profileDir ? path.resolve(String(config.profileDir)) : resolveProfileDir()
|
|
101
102
|
const dataDir = config.dataDir ? path.resolve(String(config.dataDir)) : path.join(profileDir, '.ai-prison-watchdog')
|
|
102
103
|
const logsDir = config.logsDir ? path.resolve(String(config.logsDir)) : resolveLogsDir()
|
|
103
104
|
const journalDir = config.journalDir ? path.resolve(String(config.journalDir)) : resolveJournalDir()
|
|
@@ -135,8 +136,69 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
135
136
|
for (const plan of watchdogState.plans) plan.applied = false
|
|
136
137
|
|
|
137
138
|
let lastFlush = 0
|
|
139
|
+
let operationWindowUntil = 0
|
|
140
|
+
let tamper = null
|
|
138
141
|
restoreState()
|
|
139
142
|
readCrashLogs()
|
|
143
|
+
setupTamperMonitor()
|
|
144
|
+
|
|
145
|
+
function setupTamperMonitor() {
|
|
146
|
+
if (config.tamperMonitor === false) {
|
|
147
|
+
watchdogState.tamper = { enabled: false, policy: 'off', files: [], lastCheckAt: null, lastDiff: [], restored: [], incidents: 0 }
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
tamper = createTamperMonitor({
|
|
152
|
+
profileDir,
|
|
153
|
+
dataDir,
|
|
154
|
+
policy: config.tamperPolicy === 'alert' ? 'alert' : 'restore',
|
|
155
|
+
graceMs: Number(config.tamperGraceMs) >= 0 ? Number(config.tamperGraceMs) : 15_000,
|
|
156
|
+
intervalMs: Number(config.tamperIntervalMs) > 0 ? Number(config.tamperIntervalMs) : 30_000,
|
|
157
|
+
shouldIgnore: () => Date.now() < operationWindowUntil,
|
|
158
|
+
onTamper: handleTamper,
|
|
159
|
+
log: (message) => log.info('[ai-prison-watchdog] ' + message),
|
|
160
|
+
})
|
|
161
|
+
watchdogState.tamper = tamper.status()
|
|
162
|
+
const interval = Number(config.tamperIntervalMs)
|
|
163
|
+
if (interval !== 0) tamper.start()
|
|
164
|
+
} catch (error) {
|
|
165
|
+
watchdogState.degraded = 'tamper monitor: ' + String((error && error.message) || error)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function refreshTamperStatus() {
|
|
170
|
+
if (tamper) watchdogState.tamper = tamper.status()
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function handleTamper(result) {
|
|
174
|
+
if (!result || !Array.isArray(result.diffs) || result.diffs.length === 0) return
|
|
175
|
+
const files = result.diffs.map((diff) => diff.file)
|
|
176
|
+
appendIncident({ kind: 'tamper', files, policy: result.policy, restored: result.restored, detail: '配置漂移:' + files.join(', ') })
|
|
177
|
+
let target = null
|
|
178
|
+
let evidence = []
|
|
179
|
+
try {
|
|
180
|
+
const records = readJournalRecords(journalDir).filter((record) => {
|
|
181
|
+
const at = Date.parse((record && record.operation && record.operation.time) || 0)
|
|
182
|
+
return Number.isFinite(at) && Date.now() - at < 6 * 3600 * 1000
|
|
183
|
+
})
|
|
184
|
+
const attribution = attributeCrash(records, { hostRunId: null })
|
|
185
|
+
target = attribution.picked ? attribution.picked.target : null
|
|
186
|
+
evidence = attribution.candidates
|
|
187
|
+
} catch {
|
|
188
|
+
target = null
|
|
189
|
+
}
|
|
190
|
+
const applied = Boolean(watchdogState.enforce && target)
|
|
191
|
+
const plan = { at: new Date().toISOString(), level: 'L1', crash: null, reason: 'tamper', target, inFlight: false, evidence: { files: result.diffs, candidates: evidence }, applied }
|
|
192
|
+
watchdogState.plans.push(plan)
|
|
193
|
+
if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
|
|
194
|
+
if (applied) {
|
|
195
|
+
watchdogState.quarantine.set(target, { reason: 'tamper', level: 'L1', at: plan.at, release: 'manual', evidence: '配置漂移:' + files.join(', ') })
|
|
196
|
+
void disableTarget(target, 'tamper')
|
|
197
|
+
writePendingBoot({ level: 'L1', reason: 'tamper', disable: [target], keep: [] })
|
|
198
|
+
appendIncident({ kind: 'tamper-enforced', target, files, detail: '配置漂移后已隔离 ' + target })
|
|
199
|
+
}
|
|
200
|
+
persist(true)
|
|
201
|
+
}
|
|
140
202
|
|
|
141
203
|
function persist(force = false) {
|
|
142
204
|
const now = Date.now()
|
|
@@ -260,6 +322,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
260
322
|
appendIncident({ kind: 'strong-warn', level: 'pause', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ 强警告 ${formatBytes(thresholds.opWarn)}` })
|
|
261
323
|
}
|
|
262
324
|
maybeWriteBaseline()
|
|
325
|
+
refreshTamperStatus()
|
|
263
326
|
}
|
|
264
327
|
|
|
265
328
|
// ---- clean baseline (requirement 4, dry-run in P1) ----------------------
|
|
@@ -312,12 +375,14 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
312
375
|
if ((watchdogState.suppressUntil.get(target) || 0) > Date.now()) return
|
|
313
376
|
const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
|
|
314
377
|
if (operation.phase === 'started') {
|
|
378
|
+
operationWindowUntil = Date.now() + 4000
|
|
315
379
|
inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
|
|
316
380
|
entry.lastAt = operation.time || entry.lastAt
|
|
317
381
|
watchdogState.operations.set(target, entry)
|
|
318
382
|
return
|
|
319
383
|
}
|
|
320
384
|
if (operation.phase !== 'settled') return
|
|
385
|
+
operationWindowUntil = Date.now() + 4000
|
|
321
386
|
const weight = operationWeight(operation)
|
|
322
387
|
if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
|
|
323
388
|
entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
|
|
@@ -450,18 +515,52 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
450
515
|
}
|
|
451
516
|
}
|
|
452
517
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
518
|
+
const probeFn = typeof config.probe === 'function' ? config.probe : probeBudget
|
|
519
|
+
const probeMax = Number(config.probeMax) > 0 ? Number(config.probeMax) : 5
|
|
520
|
+
const probeRetryMs = Number(config.probeRetryMs) > 0 ? Number(config.probeRetryMs) : 10 * 60 * 1000
|
|
521
|
+
const probeMaxAgeMs = 7 * 24 * 3600 * 1000
|
|
522
|
+
|
|
523
|
+
function budgetState(name, version) {
|
|
524
|
+
const entry = watchdogState.budgets[name]
|
|
525
|
+
if (!entry) return 'missing'
|
|
526
|
+
if (entry.error) {
|
|
527
|
+
const age = Date.now() - Date.parse(entry.measuredAt || 0)
|
|
528
|
+
return age > probeRetryMs && (Number(entry.attempts) || 0) < 5 ? 'retry' : 'error'
|
|
529
|
+
}
|
|
530
|
+
if (entry.moduleLoadMB === undefined) return 'stale'
|
|
531
|
+
if (!entry.version || (version && entry.version !== version)) return 'stale'
|
|
532
|
+
if (Date.now() - Date.parse(entry.measuredAt || 0) > probeMaxAgeMs) return 'stale'
|
|
533
|
+
return 'ok'
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function probeOne(name, version) {
|
|
537
|
+
const previous = watchdogState.budgets[name] || {}
|
|
538
|
+
watchdogState.probeProgress = { ...(watchdogState.probeProgress || { done: 0, total: 0 }), current: name }
|
|
539
|
+
const result = await probeFn({ profileDir, packageName: name })
|
|
540
|
+
if (!result || !result.ok) {
|
|
541
|
+
watchdogState.budgets[name] = {
|
|
542
|
+
error: String((result && result.error) || 'probe-failed').slice(0, 300),
|
|
543
|
+
measuredAt: new Date().toISOString(),
|
|
544
|
+
version: version || previous.version || null,
|
|
545
|
+
attempts: (Number(previous.attempts) || 0) + 1,
|
|
546
|
+
source: 'module-load-probe',
|
|
547
|
+
}
|
|
457
548
|
persist(true)
|
|
458
|
-
return
|
|
549
|
+
return { ok: false }
|
|
550
|
+
}
|
|
551
|
+
watchdogState.budgets[name] = {
|
|
552
|
+
moduleLoadMB: result.moduleLoadMB,
|
|
553
|
+
rssMB: result.rssMB,
|
|
554
|
+
ms: result.ms,
|
|
555
|
+
measuredAt: new Date().toISOString(),
|
|
556
|
+
version: version || null,
|
|
557
|
+
attempts: (Number(previous.attempts) || 0) + 1,
|
|
558
|
+
source: 'module-load-probe',
|
|
459
559
|
}
|
|
460
|
-
watchdogState.budgets[name] = { moduleLoadMB: result.moduleLoadMB, rssMB: result.rssMB, ms: result.ms, measuredAt: new Date().toISOString(), source: 'module-load-probe' }
|
|
461
560
|
const thresholds = watchdogState.thresholds
|
|
462
561
|
const mb = result.moduleLoadMB
|
|
463
562
|
if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
|
|
464
|
-
appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB
|
|
563
|
+
appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,禁止该插件' })
|
|
465
564
|
if (watchdogState.enforce) {
|
|
466
565
|
watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB' })
|
|
467
566
|
void disableTarget(name, 'budget-over-500MB')
|
|
@@ -471,18 +570,18 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
471
570
|
appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
|
|
472
571
|
}
|
|
473
572
|
persist(true)
|
|
573
|
+
return { ok: true }
|
|
474
574
|
}
|
|
475
575
|
|
|
476
|
-
async function scheduleProbe() {
|
|
477
|
-
if (watchdogState.
|
|
478
|
-
watchdogState.probeStarted = true
|
|
576
|
+
async function scheduleProbe({ force = false } = {}) {
|
|
577
|
+
if (watchdogState.probeRunning) return watchdogState.probeProgress
|
|
479
578
|
const manager = refs.manager
|
|
480
|
-
if (!manager || typeof manager.listBundles !== 'function') return
|
|
579
|
+
if (!manager || typeof manager.listBundles !== 'function') return null
|
|
481
580
|
let rows
|
|
482
581
|
try {
|
|
483
582
|
rows = await manager.listBundles()
|
|
484
583
|
} catch {
|
|
485
|
-
return
|
|
584
|
+
return null
|
|
486
585
|
}
|
|
487
586
|
const recent = new Set()
|
|
488
587
|
const cutoff = Date.now() - 30 * 60 * 1000
|
|
@@ -493,14 +592,25 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
493
592
|
if (Date.parse(operation.time || 0) < cutoff) continue
|
|
494
593
|
recent.add(operation.target)
|
|
495
594
|
}
|
|
496
|
-
const
|
|
497
|
-
.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name)
|
|
498
|
-
.map((row) => row.name)
|
|
499
|
-
.
|
|
500
|
-
|
|
595
|
+
const candidates = rows
|
|
596
|
+
.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name))
|
|
597
|
+
.map((row) => ({ name: row.name, version: row.version ? String(row.version) : '', state: budgetState(row.name, row.version ? String(row.version) : '') }))
|
|
598
|
+
.filter((candidate) => candidate.state !== 'ok')
|
|
599
|
+
.sort((a, b) => (recent.has(b.name) ? 1 : 0) - (recent.has(a.name) ? 1 : 0))
|
|
600
|
+
.slice(0, force ? Math.max(probeMax, Number(config.probeMaxForce) > 0 ? Number(config.probeMaxForce) : 15) : probeMax)
|
|
601
|
+
watchdogState.probeProgress = { done: 0, total: candidates.length, current: null, finishedAt: null }
|
|
602
|
+
if (candidates.length === 0) return watchdogState.probeProgress
|
|
603
|
+
watchdogState.probeRunning = true
|
|
604
|
+
for (const candidate of candidates) {
|
|
501
605
|
if (watchdogState.waterline !== 'ok') break
|
|
502
|
-
await probeOne(name)
|
|
606
|
+
const outcome = await probeOne(candidate.name, candidate.version)
|
|
607
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, done: watchdogState.probeProgress.done + 1, current: candidate.name, lastOk: Boolean(outcome && outcome.ok) }
|
|
608
|
+
if (candidates.length > 1) await new Promise((resolve) => setTimeout(resolve, Number(config.probeGapMs) >= 0 ? Number(config.probeGapMs) : 1500))
|
|
503
609
|
}
|
|
610
|
+
watchdogState.probeProgress = { ...watchdogState.probeProgress, current: null, finishedAt: new Date().toISOString() }
|
|
611
|
+
watchdogState.probeRunning = false
|
|
612
|
+
persist(true)
|
|
613
|
+
return watchdogState.probeProgress
|
|
504
614
|
}
|
|
505
615
|
|
|
506
616
|
// ---- crash attribution and dry-run plans (requirements 3 & 4) -----------
|
|
@@ -672,6 +782,10 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
672
782
|
}
|
|
673
783
|
const action = typeof body.action === 'string' ? body.action : ''
|
|
674
784
|
const target = typeof body.target === 'string' ? body.target : ''
|
|
785
|
+
if (action === 'probe') {
|
|
786
|
+
const progress = await scheduleProbe({ force: true })
|
|
787
|
+
return Response.json({ ok: true, progress })
|
|
788
|
+
}
|
|
675
789
|
if (action === 'confirm-pause') {
|
|
676
790
|
watchdogState.graceUntil = Date.now() + PAUSE_GRACE_MS
|
|
677
791
|
appendIncident({ kind: 'pause-confirmed', detail: `用户二次确认继续插件操作(宽限 10 分钟)` })
|
|
@@ -701,6 +815,13 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
701
815
|
snapshot: watchdogSnapshot,
|
|
702
816
|
sample,
|
|
703
817
|
readCrashLogs,
|
|
818
|
+
probeNow: (options) => scheduleProbe(options),
|
|
819
|
+
tamperCheck: (options) => {
|
|
820
|
+
if (!tamper) return null
|
|
821
|
+
const result = tamper.checkNow(options)
|
|
822
|
+
refreshTamperStatus()
|
|
823
|
+
return result
|
|
824
|
+
},
|
|
704
825
|
disableTarget,
|
|
705
826
|
releaseTarget,
|
|
706
827
|
dispose() {
|
|
@@ -716,6 +837,29 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
|
|
|
716
837
|
}
|
|
717
838
|
}
|
|
718
839
|
|
|
840
|
+
/** Merge live operation estimates with measured module-load budgets (measured wins). */
|
|
841
|
+
function mergedTop(state, limit) {
|
|
842
|
+
const operations = topOperations(state.operations, 50)
|
|
843
|
+
const measured = []
|
|
844
|
+
for (const [target, entry] of Object.entries(state.budgets || {})) {
|
|
845
|
+
if (!entry || entry.error || entry.moduleLoadMB === undefined) continue
|
|
846
|
+
const existing = operations.find((row) => row.target === target)
|
|
847
|
+
measured.push({
|
|
848
|
+
target,
|
|
849
|
+
count: existing ? existing.count : 0,
|
|
850
|
+
estimateMB: entry.moduleLoadMB,
|
|
851
|
+
lastAt: entry.measuredAt || (existing ? existing.lastAt : null),
|
|
852
|
+
version: entry.version || (existing ? existing.version : null),
|
|
853
|
+
source: 'measured',
|
|
854
|
+
measuredAt: entry.measuredAt || null,
|
|
855
|
+
})
|
|
856
|
+
}
|
|
857
|
+
const others = operations
|
|
858
|
+
.filter((row) => !measured.some((entry) => entry.target === row.target))
|
|
859
|
+
.map((row) => ({ ...row, source: 'estimate' }))
|
|
860
|
+
return [...measured, ...others].sort((a, b) => b.estimateMB - a.estimateMB || b.count - a.count).slice(0, Math.max(1, limit))
|
|
861
|
+
}
|
|
862
|
+
|
|
719
863
|
/** Serialisable snapshot shared by the tool and the panel route. */
|
|
720
864
|
export function watchdogSnapshot() {
|
|
721
865
|
const s = watchdogState
|
|
@@ -739,14 +883,16 @@ export function watchdogSnapshot() {
|
|
|
739
883
|
graceUntil: s.graceUntil,
|
|
740
884
|
frozenAt: s.frozenAt,
|
|
741
885
|
samples: s.samples.slice(-30),
|
|
742
|
-
operations:
|
|
743
|
-
topFive:
|
|
886
|
+
operations: mergedTop(s, 10),
|
|
887
|
+
topFive: mergedTop(s, 5),
|
|
888
|
+
probeProgress: s.probeProgress || null,
|
|
744
889
|
quarantine,
|
|
745
890
|
plans: s.plans.slice(-5),
|
|
746
891
|
escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
|
|
747
892
|
crashFallback: s.crashFallback || 'enforce',
|
|
748
893
|
baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
|
|
749
894
|
budgets: s.budgets,
|
|
895
|
+
tamper: s.tamper || null,
|
|
750
896
|
incidents: s.incidents.slice(-20),
|
|
751
897
|
generatedAt: new Date().toISOString(),
|
|
752
898
|
}
|
package/lib/watchdog-state.js
CHANGED
|
@@ -36,6 +36,8 @@ export const watchdogState = {
|
|
|
36
36
|
plans: [],
|
|
37
37
|
/** Escalation counters: crash timestamps (ms) and applied level. */
|
|
38
38
|
escalation: { crashes: [], level: 'L0' },
|
|
39
|
+
/** Profile file tamper monitor status. */
|
|
40
|
+
tamper: null,
|
|
39
41
|
/** Recent incidents (newest last), capped. */
|
|
40
42
|
incidents: [],
|
|
41
43
|
/** Last crash-log scan marker (ms). */
|
|
@@ -69,6 +71,7 @@ export function resetWatchdogState(overrides = {}) {
|
|
|
69
71
|
watchdogState.baseline = null
|
|
70
72
|
watchdogState.plans = []
|
|
71
73
|
watchdogState.escalation = { crashes: [], level: 'L0' }
|
|
74
|
+
watchdogState.tamper = null
|
|
72
75
|
watchdogState.incidents = []
|
|
73
76
|
watchdogState.lastCrashScan = 0
|
|
74
77
|
watchdogState.degraded = null
|
package/locale/en.json
CHANGED
|
@@ -16,5 +16,7 @@
|
|
|
16
16
|
"watchdog.close": "Close now",
|
|
17
17
|
"watchdog.plans": "Crash plans (dry-run)",
|
|
18
18
|
"watchdog.noPlans": "No crash attribution plans.",
|
|
19
|
-
"watchdog.baseline": "Clean baseline: {at}"
|
|
19
|
+
"watchdog.baseline": "Clean baseline: {at}",
|
|
20
|
+
"watchdog.tamper": "Profile watch: {n} critical file(s), last check {at}",
|
|
21
|
+
"watchdog.measure": "Measure plugin budgets now"
|
|
20
22
|
}
|
package/locale/zh.json
CHANGED
|
@@ -16,5 +16,7 @@
|
|
|
16
16
|
"watchdog.close": "立即关闭",
|
|
17
17
|
"watchdog.plans": "崩溃降级计划(dry-run)",
|
|
18
18
|
"watchdog.noPlans": "暂无崩溃归因计划。",
|
|
19
|
-
"watchdog.baseline": "干净基线:{at}"
|
|
19
|
+
"watchdog.baseline": "干净基线:{at}",
|
|
20
|
+
"watchdog.tamper": "配置监控:{n} 个关键文件,最近检查 {at}",
|
|
21
|
+
"watchdog.measure": "立即测量插件预算"
|
|
20
22
|
}
|
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.4",
|
|
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",
|
|
@@ -45,6 +45,7 @@
|
|
|
45
45
|
"client.js",
|
|
46
46
|
"watchdog.js",
|
|
47
47
|
"lib/*.js",
|
|
48
|
+
"lib/*.mjs",
|
|
48
49
|
"cordis.patch.yml",
|
|
49
50
|
"locale/*.json",
|
|
50
51
|
"icon.svg",
|