@twinsearth/ai-prison-dsh-plugin 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md 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.0] — 2026-11-18
6
+
7
+ ### Added — P2 crash enforcement + per-plugin budgets, P3 external guard
8
+
9
+ - **Crash enforcement (requirement 3/4)**: `crashFallback` defaults to `enforce`
10
+ now. A crash attributed to a plugin quarantines it, disables it live, and with
11
+ L2/L3 also closes the bundles that exceed the clean baseline (L2) or everything
12
+ outside the baseline (L3, never below base + web-app). Plans persist in
13
+ `state.json`, a machine-readable `pending-boot.json` is written for the
14
+ external guard, and quarantined targets are re-disabled on the next boot.
15
+ - **Per-plugin startup budget (requirement 1)**: a new isolated probe
16
+ (`lib/budget-probe.js` + `lib/budget-child.mjs`) spawns the bundled Node with
17
+ `--expose-gc`, imports one plugin package from the profile and reports its
18
+ retained module-load delta. Plugins installed or enabled in the last 30 minutes
19
+ are probed automatically after boot (max 5, only at the `ok` waterline);
20
+ results land in `budgets` inside `state.json`. Above 500 MB the plugin is
21
+ quarantined and closed (pending the next boot for a hard block); above 300 MB
22
+ an incident is recorded.
23
+ - **External guard (P3)**: `E:ToFuture oolsaiprison-guard.ps1/.cmd` runs before
24
+ DSH, reads `pending-boot.json`, backs up the profile `package.json`, removes
25
+ the bundles that must stay closed (or keeps only the L3 baseline), and then
26
+ launches DSH. It is the only component that can break an import-phase crash
27
+ loop, where the in-process watchdog never runs.
28
+
29
+ ### Fixed
30
+ - Watchdog probes keep the event loop alive no longer (timer `unref`), keeping
31
+ the test suite fast and the host responsive.
32
+
33
+ ## [1.3.0] — 2026-11-18
5
34
  ## [1.3.0] — 2026-11-18
6
35
 
7
36
  ### Added — P1 enforcement (requirements 2, 3, 4 dry-run, 5)
@@ -0,0 +1,56 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { fileURLToPath } from 'node:url'
3
+
4
+ const CHILD = fileURLToPath(new URL('./budget-child.mjs', import.meta.url))
5
+
6
+ /**
7
+ * Measure a plugin package's module-load heap cost in an isolated child process.
8
+ * The child runs with --expose-gc, resolves the package from the profile, imports
9
+ * its entry module, forces GC and reports the retained delta. This is the
10
+ * "启动内存" budget that feeds the 300/500 MB per-plugin thresholds.
11
+ */
12
+ export function probeBudget({ profileDir, packageName, timeoutMs = 25_000 } = {}) {
13
+ return new Promise((resolve) => {
14
+ const nodeExe = process.env.DSH_PROBE_NODE || process.execPath
15
+ const env = { ...process.env }
16
+ if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1'
17
+ delete env.NODE_OPTIONS
18
+ const child = spawn(nodeExe, ['--expose-gc', CHILD, profileDir, packageName], {
19
+ env,
20
+ windowsHide: true,
21
+ stdio: ['ignore', 'pipe', 'pipe'],
22
+ })
23
+ let stdout = ''
24
+ let stderr = ''
25
+ let settled = false
26
+ const finish = (value) => {
27
+ if (settled) return
28
+ settled = true
29
+ clearTimeout(timer)
30
+ try {
31
+ child.kill()
32
+ } catch {
33
+ // already gone
34
+ }
35
+ resolve(value)
36
+ }
37
+ const timer = setTimeout(() => finish({ ok: false, error: 'probe-timeout' }), timeoutMs)
38
+ child.stdout.on('data', (chunk) => {
39
+ stdout += String(chunk)
40
+ })
41
+ child.stderr.on('data', (chunk) => {
42
+ stderr = (stderr + String(chunk)).slice(-2000)
43
+ })
44
+ child.on('error', (error) => finish({ ok: false, error: String(error && error.message) }))
45
+ child.on('exit', (code) => {
46
+ const line = stdout.trim().split('\n').filter(Boolean).pop()
47
+ if (!line) return finish({ ok: false, error: `probe-exit-${code}: ${stderr.slice(0, 300)}` })
48
+ try {
49
+ const parsed = JSON.parse(line)
50
+ finish(parsed)
51
+ } catch {
52
+ finish({ ok: false, error: `probe-bad-json: ${line.slice(0, 300)}` })
53
+ }
54
+ })
55
+ })
56
+ }
@@ -4,6 +4,7 @@ import path from 'node:path'
4
4
  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
+ import { probeBudget } from './budget-probe.js'
7
8
  import {
8
9
  attributeCrash,
9
10
  classifyWaterline,
@@ -127,6 +128,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
127
128
  watchdogState.runId = crypto.randomUUID()
128
129
  watchdogState.dataDir = dataDir
129
130
  watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
131
+ watchdogState.crashFallback = config.crashFallback === 'dry-run' ? 'dry-run' : 'enforce'
132
+ watchdogState.probeStarted = false
130
133
  watchdogState.lastCrashScan = 0
131
134
  watchdogState.baseline = null
132
135
  for (const plan of watchdogState.plans) plan.applied = false
@@ -146,6 +149,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
146
149
  escalation: watchdogState.escalation,
147
150
  baseline: watchdogState.baseline,
148
151
  budgets: watchdogState.budgets,
152
+ quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
149
153
  }
150
154
  try {
151
155
  fs.writeFileSync(stateFile, `${JSON.stringify(payload, null, 2)}\n`)
@@ -162,6 +166,11 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
162
166
  if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
163
167
  if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
164
168
  if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
169
+ if (Array.isArray(parsed.quarantine)) {
170
+ for (const entry of parsed.quarantine) {
171
+ 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 || '' })
172
+ }
173
+ }
165
174
  } catch {
166
175
  // first run or unreadable state: start clean
167
176
  }
@@ -382,6 +391,118 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
382
391
  return { ok: true }
383
392
  }
384
393
 
394
+ function writePendingBoot(payload) {
395
+ try {
396
+ fs.writeFileSync(path.join(dataDir, 'pending-boot.json'), JSON.stringify({ writtenAt: new Date().toISOString(), ...payload }, null, 2) + '\n')
397
+ } catch {
398
+ // wrapper reads this file; best effort
399
+ }
400
+ }
401
+
402
+ async function disableMany(targets, reason) {
403
+ const unique = [...new Set(targets)].filter((target) => target && !EXEMPT_TARGETS.has(target) && !watchdogState.quarantine.has(target))
404
+ const disabled = []
405
+ for (const target of unique) {
406
+ watchdogState.quarantine.set(target, { reason, level: 'crash', at: new Date().toISOString(), release: 'manual', evidence: reason })
407
+ if (await disableTarget(target, reason)) disabled.push(target)
408
+ await new Promise((resolve) => setTimeout(resolve, 300))
409
+ }
410
+ return disabled
411
+ }
412
+
413
+ async function enforceCrashPlan(plan) {
414
+ if (!plan || !plan.target || watchdogState.crashFallback !== 'enforce') return
415
+ try {
416
+ watchdogState.quarantine.set(plan.target, { reason: 'crash', level: plan.level, at: new Date().toISOString(), release: 'manual', evidence: plan.reason })
417
+ const disabled = [plan.target].filter((target) => !EXEMPT_TARGETS.has(target))
418
+ await disableTarget(plan.target, 'crash-' + plan.level)
419
+ let targets = [plan.target]
420
+ if (plan.level === 'L2' || plan.level === 'L3') {
421
+ const manager = refs.manager
422
+ const rows = manager && typeof manager.listBundles === 'function' ? await manager.listBundles() : []
423
+ const baselineNames = watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : []
424
+ targets = plan.level === 'L3'
425
+ ? rows.filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name) && !baselineNames.includes(row.name)).map((row) => row.name)
426
+ : diffBaseline(rows, watchdogState.baseline).changed.map((row) => row.name).concat(plan.target)
427
+ disabled.push(...(await disableMany(targets, 'crash-' + plan.level)))
428
+ }
429
+ writePendingBoot({
430
+ level: plan.level,
431
+ reason: 'crash',
432
+ attribution: plan.target,
433
+ disable: [...new Set(targets)],
434
+ keep: watchdogState.baseline ? watchdogState.baseline.bundles.map((row) => row.name) : [],
435
+ })
436
+ appendIncident({ kind: 'crash-enforced', level: plan.level, target: plan.target, detail: '已按 ' + plan.level + ' 隔离 ' + disabled.length + ' 个目标(pending-boot.json 供外部包装器下次启动前使用)' })
437
+ persist(true)
438
+ } catch (error) {
439
+ watchdogState.degraded = 'crash enforce: ' + String((error && error.message) || error)
440
+ }
441
+ }
442
+
443
+ async function reapplyQuarantine() {
444
+ for (const [target, entry] of watchdogState.quarantine) {
445
+ if (entry.release === 'restart') {
446
+ watchdogState.quarantine.delete(target)
447
+ continue
448
+ }
449
+ void disableTarget(target, 'boot-reapply')
450
+ }
451
+ }
452
+
453
+ async function probeOne(name) {
454
+ const result = await probeBudget({ profileDir, packageName: name })
455
+ if (!result.ok) {
456
+ watchdogState.budgets[name] = { error: String(result.error || 'probe-failed').slice(0, 300), measuredAt: new Date().toISOString(), source: 'module-load-probe' }
457
+ persist(true)
458
+ return
459
+ }
460
+ watchdogState.budgets[name] = { moduleLoadMB: result.moduleLoadMB, rssMB: result.rssMB, ms: result.ms, measuredAt: new Date().toISOString(), source: 'module-load-probe' }
461
+ const thresholds = watchdogState.thresholds
462
+ const mb = result.moduleLoadMB
463
+ if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
464
+ appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,建议禁止该插件' })
465
+ if (watchdogState.enforce) {
466
+ watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB' })
467
+ void disableTarget(name, 'budget-over-500MB')
468
+ writePendingBoot({ level: 'L1', reason: 'budget', disable: [name], keep: [] })
469
+ }
470
+ } else if (thresholds && mb >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
471
+ appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
472
+ }
473
+ persist(true)
474
+ }
475
+
476
+ async function scheduleProbe() {
477
+ if (watchdogState.probeStarted) return
478
+ watchdogState.probeStarted = true
479
+ const manager = refs.manager
480
+ if (!manager || typeof manager.listBundles !== 'function') return
481
+ let rows
482
+ try {
483
+ rows = await manager.listBundles()
484
+ } catch {
485
+ return
486
+ }
487
+ const recent = new Set()
488
+ const cutoff = Date.now() - 30 * 60 * 1000
489
+ for (const record of readJournalRecords(journalDir)) {
490
+ const operation = record && record.operation
491
+ if (!operation || !operation.target) continue
492
+ if (operation.stage !== 'install' && operation.stage !== 'enable') continue
493
+ if (Date.parse(operation.time || 0) < cutoff) continue
494
+ recent.add(operation.target)
495
+ }
496
+ const targets = rows
497
+ .filter((row) => row.enabled && !EXEMPT_TARGETS.has(row.name) && !watchdogState.budgets[row.name] && recent.has(row.name))
498
+ .map((row) => row.name)
499
+ .slice(0, 5)
500
+ for (const name of targets) {
501
+ if (watchdogState.waterline !== 'ok') break
502
+ await probeOne(name)
503
+ }
504
+ }
505
+
385
506
  // ---- crash attribution and dry-run plans (requirements 3 & 4) -----------
386
507
  function readCrashLogs() {
387
508
  let entries
@@ -445,6 +566,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
445
566
  ? `崩溃归因:${plan.target}${plan.inFlight ? '(崩溃时操作仍在途)' : ''};${watchdogState.enforce ? 'enforce' : 'dry-run'}`
446
567
  : '崩溃归因失败:本 run 无安装/启用记录,不自动关闭',
447
568
  })
569
+ if (watchdogState.enforce && watchdogState.crashFallback === 'enforce') void enforceCrashPlan(plan)
448
570
  }
449
571
  if (newest > watchdogState.lastCrashScan) {
450
572
  watchdogState.lastCrashScan = newest
@@ -457,6 +579,13 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
457
579
  if (typeof ctx.inject === 'function') {
458
580
  ctx.inject(['pluginManager'], (child) => {
459
581
  refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
582
+ if (refs.manager) {
583
+ void reapplyQuarantine()
584
+ const probeTimer = setTimeout(() => {
585
+ void scheduleProbe()
586
+ }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
587
+ if (typeof probeTimer.unref === 'function') probeTimer.unref()
588
+ }
460
589
  })
461
590
  }
462
591
  } catch (error) {
@@ -615,6 +744,7 @@ export function watchdogSnapshot() {
615
744
  quarantine,
616
745
  plans: s.plans.slice(-5),
617
746
  escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
747
+ crashFallback: s.crashFallback || 'enforce',
618
748
  baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
619
749
  budgets: s.budgets,
620
750
  incidents: s.incidents.slice(-20),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "AI Prison for DSH: six governance tools wrapping the aiprison CLI (levels, demo, drill, inspect, verify, repair-tail) plus a panel for the L0–L5 matrix and the audit-chain state. The CLI ships bundled for Windows, macOS and Linux; every capability-removal backend stays simulated.",
5
5
  "type": "module",
6
6
  "main": "index.js",