@twinsearth/ai-prison-dsh-plugin 1.6.1 → 1.7.1

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.
@@ -0,0 +1,211 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { attributeCrash, hotOperationTriggered, mergeEstimate, operationWeight } from './watchdog-policy.js'
4
+ import { remediationFor } from './remediation.js'
5
+ import { readJournalRecords } from './watchdog-core.js'
6
+
7
+ /**
8
+ * Plugin-operation accounting and enforcement: hot-operation counting, the
9
+ * per-target quarantine registry, rollback of additive operations at the
10
+ * pause/frost waterlines, manual release, and the pending-boot plan written for
11
+ * an external launcher.
12
+ *
13
+ * The module only talks to the plugin manager through `refs.manager`; it never
14
+ * writes plugin files.
15
+ */
16
+ export function createEnforcement({ watchdogState, refs, dataDir, journalDir, exemptions, appendIncident, persist }) {
17
+ const inflight = new Map()
18
+ const operationWindows = []
19
+ let operationWindowUntil = 0
20
+ let lastOperationAt = 0
21
+
22
+ function writePendingBoot(payload) {
23
+ try {
24
+ fs.writeFileSync(path.join(dataDir, 'pending-boot.json'), JSON.stringify({ writtenAt: new Date().toISOString(), ...payload }, null, 2) + '\n')
25
+ } catch {
26
+ // an external launcher reads this file; best effort
27
+ }
28
+ }
29
+
30
+ async function disableTarget(target, reason) {
31
+ const manager = refs.manager
32
+ if (!manager || typeof manager.setBundleEnabled !== 'function') {
33
+ watchdogState.degraded = `disable ${target}: pluginManager unavailable`
34
+ return false
35
+ }
36
+ watchdogState.suppressUntil.set(target, Date.now() + 8000)
37
+ for (let attempt = 0; attempt < 2; attempt += 1) {
38
+ try {
39
+ const rows = typeof manager.listBundles === 'function' ? await manager.listBundles() : []
40
+ const row = rows.find((entry) => entry.name === target)
41
+ if (row && row.enabled === false) return true
42
+ await manager.setBundleEnabled(target, false)
43
+ appendIncident({ kind: 'close', target, reason, detail: `已自动关闭 ${target}(${reason})` })
44
+ return true
45
+ } catch (error) {
46
+ if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 500))
47
+ else {
48
+ appendIncident({ kind: 'close-failed', target, reason, detail: `自动关闭 ${target} 失败:${String((error && error.message) || error)}` })
49
+ watchdogState.degraded = `disable ${target}: ${String((error && error.message) || error)}`
50
+ return false
51
+ }
52
+ }
53
+ }
54
+ return false
55
+ }
56
+
57
+ function releaseTarget(target) {
58
+ const entry = watchdogState.quarantine.get(target)
59
+ if (!entry) return { ok: false, error: 'not quarantined' }
60
+ watchdogState.quarantine.delete(target)
61
+ watchdogState.suppressUntil.set(target, Date.now() + 5000)
62
+ appendIncident({ kind: 'release', target, detail: `用户假释 ${target}(原因 ${entry.reason})` })
63
+ persist(true)
64
+ return { ok: true }
65
+ }
66
+
67
+ async function disableMany(targets, reason) {
68
+ const unique = [...new Set(targets)].filter((target) => target && !exemptions.has(target) && !watchdogState.quarantine.has(target))
69
+ const disabled = []
70
+ for (const target of unique) {
71
+ watchdogState.quarantine.set(target, { reason, level: 'crash', at: new Date().toISOString(), release: 'manual', evidence: reason, remediation: remediationFor(reason) })
72
+ if (await disableTarget(target, reason)) disabled.push(target)
73
+ await new Promise((resolve) => setTimeout(resolve, 300))
74
+ }
75
+ return disabled
76
+ }
77
+
78
+ async function reapplyQuarantine() {
79
+ for (const [target, entry] of watchdogState.quarantine) {
80
+ if (entry.release === 'restart') {
81
+ watchdogState.quarantine.delete(target)
82
+ continue
83
+ }
84
+ void disableTarget(target, 'boot-reapply')
85
+ }
86
+ }
87
+
88
+ function onOperation(operation) {
89
+ try {
90
+ if (!operation || typeof operation !== 'object') return
91
+ const target = typeof operation.target === 'string' && operation.target ? operation.target : null
92
+ if (!target) return
93
+ if ((watchdogState.suppressUntil.get(target) || 0) > Date.now()) return
94
+ const entry = watchdogState.operations.get(target) || { count: 0, estimateMB: 0, lastAt: null, version: operation.version || null, lastApplication: null }
95
+ operationWindowUntil = Date.now() + 4000
96
+ lastOperationAt = Date.now()
97
+ if (operation.phase === 'started') {
98
+ operationWindows.push({ startedAt: Date.now(), settledAt: null })
99
+ if (operationWindows.length > 20) operationWindows.shift()
100
+ inflight.set(operation.id, { target, heapBefore: watchdogState.latest ? watchdogState.latest.heapUsed : 0 })
101
+ entry.lastAt = operation.time || entry.lastAt
102
+ watchdogState.operations.set(target, entry)
103
+ return
104
+ }
105
+ if (operation.phase !== 'settled') return
106
+ for (let i = operationWindows.length - 1; i >= 0; i -= 1) {
107
+ if (operationWindows[i].settledAt === null) {
108
+ operationWindows[i].settledAt = Date.now()
109
+ break
110
+ }
111
+ }
112
+ const weight = operationWeight(operation)
113
+ if (weight > 0 && operation.application !== 'failed' && operation.application !== 'cancelled') {
114
+ entry.count = Math.round((Number(entry.count) + weight) * 10) / 10
115
+ }
116
+ const before = inflight.get(operation.id)
117
+ inflight.delete(operation.id)
118
+ if (before && watchdogState.latest && before.heapBefore > 0) {
119
+ const deltaMB = Math.max(0, Math.round((watchdogState.latest.heapUsed - before.heapBefore) / (1024 * 1024)))
120
+ entry.estimateMB = mergeEstimate(entry.estimateMB, deltaMB)
121
+ }
122
+ entry.lastAt = operation.time || entry.lastAt
123
+ entry.version = operation.version || entry.version
124
+ entry.lastApplication = operation.application || null
125
+ watchdogState.operations.set(target, entry)
126
+ const additive = operation.stage === 'install' || (operation.stage === 'enable' && operation.enabled !== false)
127
+ if (
128
+ watchdogState.enforce
129
+ && additive
130
+ && target
131
+ && !exemptions.has(target)
132
+ && (watchdogState.waterline === 'frost' || watchdogState.waterline === 'pause')
133
+ && !(Number.isFinite(watchdogState.graceUntil) && Date.now() < watchdogState.graceUntil)
134
+ ) {
135
+ const level = watchdogState.waterline
136
+ appendIncident({
137
+ kind: level === 'frost' ? 'freeze-rollback' : 'pause-rollback',
138
+ target,
139
+ level,
140
+ detail: (level === 'frost' ? '冻结' : '暂停') + '期间检测到面板/网页发起的增内存操作,已立即回滚关闭 ' + target,
141
+ })
142
+ void disableTarget(target, level + '-rollback')
143
+ }
144
+ if (operation.reason === 'remove' && operation.application === 'applied') {
145
+ watchdogState.operations.delete(target)
146
+ return
147
+ }
148
+ if (watchdogState.enforce && !exemptions.has(target) && !watchdogState.quarantine.has(target) && hotOperationTriggered(entry.count)) {
149
+ watchdogState.quarantine.set(target, {
150
+ reason: 'hot-ops',
151
+ level: 'L2',
152
+ at: new Date().toISOString(),
153
+ release: 'restart',
154
+ evidence: `本次运行内热操作计数 ${entry.count} > 5(安装/启用/热切换)`,
155
+ remediation: remediationFor('hot-ops', { count: entry.count }),
156
+ })
157
+ appendIncident({ kind: 'quarantine', target, level: 'L2', reason: 'hot-ops', detail: `热操作 ${entry.count} 次 > 5,自动关闭` })
158
+ persist(true)
159
+ void disableTarget(target, 'hot-ops')
160
+ }
161
+ persist(true)
162
+ } catch (error) {
163
+ watchdogState.degraded = `operation handler: ${String((error && error.message) || error)}`
164
+ }
165
+ }
166
+
167
+ /** Profile drift detected by the tamper monitor: record, attribute, optionally enforce. */
168
+ function handleTamper(result) {
169
+ if (!result || !Array.isArray(result.diffs) || result.diffs.length === 0) return
170
+ const files = result.diffs.map((diff) => diff.file)
171
+ const policy = (watchdogState.tamper && watchdogState.tamper.policy) || 'observe'
172
+ appendIncident({ kind: 'tamper', files, policy, restored: result.restored, detail: '配置漂移:' + files.join(', ') + (policy === 'observe' ? '(observe:仅记录,不恢复不关闭)' : '') })
173
+ let target = null
174
+ let evidence = []
175
+ try {
176
+ const records = readJournalRecords(journalDir).filter((record) => {
177
+ const at = Date.parse((record && record.operation && record.operation.time) || 0)
178
+ return Number.isFinite(at) && Date.now() - at < 6 * 3600 * 1000
179
+ })
180
+ const attribution = attributeCrash(records, { hostRunId: null })
181
+ target = attribution.picked ? attribution.picked.target : null
182
+ evidence = attribution.candidates
183
+ } catch {
184
+ target = null
185
+ }
186
+ const applied = Boolean(watchdogState.enforce && target && policy === 'restore')
187
+ 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 }
188
+ watchdogState.plans.push(plan)
189
+ if (watchdogState.plans.length > 20) watchdogState.plans = watchdogState.plans.slice(-20)
190
+ if (applied) {
191
+ watchdogState.quarantine.set(target, { reason: 'tamper', level: 'L1', at: plan.at, release: 'manual', evidence: '配置漂移:' + files.join(', '), remediation: remediationFor('tamper') })
192
+ void disableTarget(target, 'tamper')
193
+ writePendingBoot({ level: 'L1', reason: 'tamper', disable: [target], keep: [] })
194
+ appendIncident({ kind: 'tamper-enforced', target, files, detail: '配置漂移后已隔离 ' + target })
195
+ }
196
+ persist(true)
197
+ }
198
+
199
+ /** True while the plugin manager itself is expected to be writing profile files. */
200
+ function shouldIgnoreWrites() {
201
+ return Date.now() < operationWindowUntil || Date.now() - lastOperationAt < 120000
202
+ }
203
+
204
+ /** True when a file mtime falls inside a recorded plugin-manager operation window. */
205
+ function isWithinOperationWindow(mtimeMs) {
206
+ const now = Date.now()
207
+ return operationWindows.some((window) => mtimeMs >= window.startedAt - 5000 && mtimeMs <= (window.settledAt || now) + 5000)
208
+ }
209
+
210
+ return { onOperation, disableTarget, releaseTarget, disableMany, writePendingBoot, reapplyQuarantine, handleTamper, shouldIgnoreWrites, isWithinOperationWindow }
211
+ }
@@ -0,0 +1,124 @@
1
+ import fs from 'node:fs'
2
+ import { MAX_INCIDENTS } from './watchdog-state.js'
3
+ import { notify } from './notifier.js'
4
+
5
+ /**
6
+ * Durable state of the watchdog: `state.json` for the cross-run snapshot,
7
+ * `incidents.jsonl` for the append-only incident tail, and the restore path for
8
+ * a previous run. All writes are best effort: a broken disk must not break the
9
+ * watchdog's in-memory behavior.
10
+ */
11
+ export function createPersistence({ watchdogState, stateFile, incidentsFile }) {
12
+ let lastFlush = 0
13
+ let tamperMigrationDone = false
14
+
15
+ function persist(force = false) {
16
+ const now = Date.now()
17
+ if (!force && now - lastFlush < 30_000) return
18
+ lastFlush = now
19
+ const payload = {
20
+ startedAt: watchdogState.startedAt,
21
+ lastCrashScan: watchdogState.lastCrashScan,
22
+ incidents: watchdogState.incidents.slice(-50),
23
+ escalation: watchdogState.escalation,
24
+ baseline: watchdogState.baseline,
25
+ budgets: watchdogState.budgets,
26
+ quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
27
+ rss: watchdogState.rss || {},
28
+ rssAt: watchdogState.rssAt || null,
29
+ rssError: watchdogState.rssError || null,
30
+ rssStats: watchdogState.rssStats || null,
31
+ rssServiceError: watchdogState.rssServiceError || null,
32
+ rssAttempts: watchdogState.rssAttempts || 0,
33
+ migratedTamperQuarantine: tamperMigrationDone,
34
+ }
35
+ try {
36
+ // Atomic replace: a crash mid-write must never leave a half state.json.
37
+ const tempFile = `${stateFile}.tmp`
38
+ fs.writeFileSync(tempFile, `${JSON.stringify(payload, null, 2)}\n`)
39
+ fs.renameSync(tempFile, stateFile)
40
+ } catch {
41
+ try {
42
+ fs.rmSync(`${stateFile}.tmp`, { force: true })
43
+ } catch {
44
+ // best effort
45
+ }
46
+ }
47
+ }
48
+
49
+ function restoreState() {
50
+ try {
51
+ const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
52
+ watchdogState.lastCrashScan = Number(parsed.lastCrashScan) > 0 ? Number(parsed.lastCrashScan) : 0
53
+ if (Array.isArray(parsed.incidents)) watchdogState.incidents = parsed.incidents.slice(-MAX_INCIDENTS)
54
+ if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) {
55
+ watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
56
+ }
57
+ if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
58
+ if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
59
+ if (parsed.rss && typeof parsed.rss === 'object') watchdogState.rss = parsed.rss
60
+ if (parsed.rssAt) watchdogState.rssAt = parsed.rssAt
61
+ if (parsed.rssStats) watchdogState.rssStats = parsed.rssStats
62
+ watchdogState.rssAttempts = Number(parsed.rssAttempts) || 0
63
+ tamperMigrationDone = parsed.migratedTamperQuarantine === true
64
+ if (Array.isArray(parsed.quarantine)) {
65
+ let dropped = 0
66
+ for (const entry of parsed.quarantine) {
67
+ if (!tamperMigrationDone && entry && entry.reason === 'tamper') {
68
+ dropped += 1
69
+ continue
70
+ }
71
+ if (entry && typeof entry.target === 'string') {
72
+ watchdogState.quarantine.set(entry.target, {
73
+ reason: entry.reason || 'crash',
74
+ level: entry.level || 'L1',
75
+ at: entry.at || new Date().toISOString(),
76
+ release: entry.release || 'manual',
77
+ evidence: entry.evidence || '',
78
+ })
79
+ }
80
+ }
81
+ if (dropped > 0) {
82
+ watchdogState.incidents.push({
83
+ at: new Date().toISOString(),
84
+ mode: watchdogState.mode,
85
+ kind: 'migration',
86
+ detail: '清理 ' + dropped + ' 条 1.4.3/1.4.4 误判的 tamper 隔离(操作窗口归因已修复)',
87
+ })
88
+ }
89
+ tamperMigrationDone = true
90
+ }
91
+ } catch {
92
+ // first run or unreadable state: start clean
93
+ }
94
+ }
95
+
96
+ function appendIncident(incident) {
97
+ const record = { at: new Date().toISOString(), mode: watchdogState.mode, ...incident }
98
+ if (watchdogState.config && watchdogState.config.notify === true && ['freeze', 'pause', 'quarantine', 'tamper', 'crash-enforced', 'budget'].includes(record.kind)) {
99
+ try {
100
+ notify(record)
101
+ } catch {
102
+ // notifications are best effort
103
+ }
104
+ }
105
+ watchdogState.incidents.push(record)
106
+ if (watchdogState.incidents.length > MAX_INCIDENTS) watchdogState.incidents = watchdogState.incidents.slice(-MAX_INCIDENTS)
107
+ try {
108
+ fs.appendFileSync(incidentsFile, `${JSON.stringify(record)}\n`)
109
+ const stat = fs.statSync(incidentsFile)
110
+ if (stat.size > 1024 * 1024) {
111
+ // Keep a longer tail (2000 lines ≈ several days of typical incidents)
112
+ // and write it atomically so a crash cannot truncate the audit file.
113
+ const lines = fs.readFileSync(incidentsFile, 'utf8').trim().split('\n').slice(-2000)
114
+ fs.writeFileSync(`${incidentsFile}.tmp`, `${lines.join('\n')}\n`)
115
+ fs.renameSync(`${incidentsFile}.tmp`, incidentsFile)
116
+ }
117
+ } catch {
118
+ // auditing is best effort
119
+ }
120
+ return record
121
+ }
122
+
123
+ return { persist, restoreState, appendIncident }
124
+ }
@@ -1,12 +1,14 @@
1
1
  /**
2
- * Pure policy math for the AI Prison watchdog (P1).
2
+ * Pure policy math for the AI Prison watchdog.
3
3
  *
4
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
+ * totalWarn 73% of the heap cap -> yellow waterline
6
+ * totalPause 88% of the cap -> additive plugin operations need a second confirmation
7
+ * totalBlock 93% of the cap -> freeze every plugin operation except the release whitelist
8
+ * opWarn ~67% of the cap -> strong warning once the user continued through pause
9
+ * opBlock ~83% of the cap -> agent-side plugin_manager guard refuses
10
+ * On a 6 GB host that yields 3.0/3.9/5.0 GB and 4.0/5.0 GB operation gates; on a
11
+ * 4 GB host the same ratios map down to 2.99/3.60/3.81 GB and 2.73/3.41 GB.
10
12
  */
11
13
  export const MB = 1024 * 1024
12
14
  export const GB = 1024 * MB
@@ -276,3 +278,45 @@ export function formatBytes(bytes) {
276
278
  if (value >= GB) return `${(value / GB).toFixed(2)} GB`
277
279
  return `${Math.round(value / MB)} MB`
278
280
  }
281
+
282
+ /**
283
+ * Drop accounting rows for bundles that are no longer enabled, or whose version
284
+ * changed since the budget was measured. Keeps Top5/budgets honest after
285
+ * uninstalls and upgrades (state otherwise keeps stale targets forever).
286
+ */
287
+ export function prunePluginState(state, rows) {
288
+ const list = Array.isArray(rows) ? rows : []
289
+ const enabled = new Set(list.filter((row) => row.enabled).map((row) => row.name))
290
+ const versions = new Map(list.filter((row) => row.enabled).map((row) => [row.name, String(row.version || '')]))
291
+ const removed = { operations: [], budgets: [], ranking: [], rss: [] }
292
+
293
+ if (state.operations instanceof Map) {
294
+ for (const target of [...state.operations.keys()]) {
295
+ if (!enabled.has(target)) {
296
+ state.operations.delete(target)
297
+ removed.operations.push(target)
298
+ }
299
+ }
300
+ }
301
+ for (const target of Object.keys(state.budgets || {})) {
302
+ const entry = state.budgets[target]
303
+ const measuredVersion = entry && entry.version ? String(entry.version) : ''
304
+ if (!enabled.has(target) || (measuredVersion && versions.get(target) !== measuredVersion)) {
305
+ delete state.budgets[target]
306
+ removed.budgets.push(target)
307
+ }
308
+ }
309
+ for (const target of Object.keys(state.ranking || {})) {
310
+ if (!enabled.has(target)) {
311
+ delete state.ranking[target]
312
+ removed.ranking.push(target)
313
+ }
314
+ }
315
+ for (const target of Object.keys(state.rss || {})) {
316
+ if (!enabled.has(target)) {
317
+ delete state.rss[target]
318
+ removed.rss.push(target)
319
+ }
320
+ }
321
+ return removed
322
+ }