@twinsearth/ai-prison-dsh-plugin 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,35 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.4.3] — 2026-11-18
6
+
7
+ ### Added — profile tamper monitor (requirement 3, the missing half)
8
+
9
+ - **Hash watch of the critical profile files** (`package.json`,
10
+ `cordis.patch.yml`, `cordis.yml`, `pnpm-workspace.yaml`, `pnpm-lock.yaml`):
11
+ a baseline with the original bytes is captured at watchdog start, the files are
12
+ re-hashed every 30 s, and the first 15 s after startup are treated as normal
13
+ startup writes.
14
+ - A drift **outside a plugin-manager operation window** (±4 s around
15
+ started/settled) is tampering: the changed bytes are copied to
16
+ `.ai-prison-watchdog/tampered/<ts>/`, the original bytes are restored by
17
+ default (`tamperPolicy: 'alert'` keeps the change), and an L1 plan is
18
+ attributed from the operation journal (in-flight install/enable first). In
19
+ enforce mode the attributed plugin is quarantined, closed and queued in
20
+ `pending-boot.json` for the external guard.
21
+ - New `tamper` block in the watchdog snapshot/tool output, and a "Profile
22
+ watch" line in the panel Enforcement card.
23
+
24
+ ### Fixed
25
+ - `lib/budget-child.mjs` was missing from the npm package (`files` only
26
+ matched `lib/*.js`), which made every per-plugin budget probe fail with
27
+ "Cannot find module". `files` now ships `lib/*.mjs` too.
28
+
29
+ ### Tests
30
+ - New `test/tamper-monitor.test.mjs`: snapshot/diff/restore, real runtime drift
31
+ detection with restore, operation-window suppression, and the alert policy.
32
+
33
+ ## [1.4.2] — 2026-11-18
5
34
  ## [1.4.2] — 2026-11-18
6
35
 
7
36
  ### Added
package/client.js CHANGED
@@ -464,6 +464,7 @@ 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,
467
468
  )
468
469
  }
469
470
 
@@ -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
@@ -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
@@ -701,6 +766,12 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
701
766
  snapshot: watchdogSnapshot,
702
767
  sample,
703
768
  readCrashLogs,
769
+ tamperCheck: (options) => {
770
+ if (!tamper) return null
771
+ const result = tamper.checkNow(options)
772
+ refreshTamperStatus()
773
+ return result
774
+ },
704
775
  disableTarget,
705
776
  releaseTarget,
706
777
  dispose() {
@@ -747,6 +818,7 @@ export function watchdogSnapshot() {
747
818
  crashFallback: s.crashFallback || 'enforce',
748
819
  baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
749
820
  budgets: s.budgets,
821
+ tamper: s.tamper || null,
750
822
  incidents: s.incidents.slice(-20),
751
823
  generatedAt: new Date().toISOString(),
752
824
  }
@@ -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,6 @@
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}"
20
21
  }
package/locale/zh.json CHANGED
@@ -16,5 +16,6 @@
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}"
20
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
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",