@twinsearth/ai-prison-dsh-plugin 1.5.4 → 1.6.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,42 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.6.1] — 2026-11-19
6
+
7
+ ### Fixed
8
+ - 1.6.0 shipped `watchdog-runtime.js` calling `createBootWatch` without importing
9
+ `./boot-watch.js`, so the watchdog degraded with "createBootWatch is not defined"
10
+ and the startup watch never started. The import is restored and a regression
11
+ test (`test/watchdog-imports.test.mjs`) now asserts every helper module the
12
+ runtime calls is imported.
13
+
14
+ ## [1.6.0] — 2026-11-18
15
+ ## [1.6.0] — 2026-11-18
16
+
17
+ ### Added — startup watchdog, safe boot and panel 6 GB control
18
+
19
+ - **bootWatch**: 500 ms heap sampling from watchdog activation to the clean
20
+ baseline, written to `.ai-prison-watchdog/run-<start>.jsonl` (last 5 kept) so a
21
+ post-crash boot or the guard can inspect the curve even when the host died.
22
+ - **Startup thresholds**: growth > 150 MB/s or total > 2.0 GB (4 GB host) /
23
+ > 3.0 GB (6 GB host) writes a safe-boot plan (base + web-app + ai-prison) and
24
+ records a `startup-memory` incident; the guard enforces it on next launch.
25
+ - **Guard v2**: startup-phase OOM in the newest crash log forces that safe boot,
26
+ moves the ai-prison bundle to position 2, applies pending-boot plans, updates
27
+ the 6 GB heap patch from a flag file, and logs the last startup curve.
28
+ - **Panel 6 GB control**: the Enforcement card can request/cancel "6 GB heap on
29
+ next launch"; the request is a flag file the guard consumes.
30
+ - **Safer defaults**: RSS child scan and automatic budget probes are now **off**
31
+ unless explicitly enabled (`rssScan: true`, `probeAuto: true`); notifications
32
+ stay off. This also removes the 1.5.x periodic subprocess spawns from startup.
33
+ - `ai_prison_watchdog_status` now reports `boot` (run file, peak, trigger) and
34
+ `heap6g`.
35
+
36
+ ### Note
37
+ - The panel heap toggle only takes effect on the next launch through the guard,
38
+ because the archive is locked while DSH runs.
39
+
40
+ ## [1.5.4] — 2026-11-18
5
41
  ## [1.5.4] — 2026-11-18
6
42
 
7
43
  ### Fixed — RSS diagnostics were invisible
package/client.js CHANGED
@@ -429,6 +429,16 @@ window.__ModuleLoader__.load({
429
429
  if (prompt && !window.confirm(prompt)) return
430
430
  postWatchdogAction(name, target).then(() => refresh()).catch(() => refresh())
431
431
  }
432
+ const toggleHeap6g = (enabled) => {
433
+ fetch(new URL(WATCHDOG_ACTION_URL, document.baseURI), {
434
+ method: 'POST',
435
+ credentials: 'same-origin',
436
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
437
+ body: JSON.stringify({ action: 'heap6g', enabled }),
438
+ })
439
+ .then(() => refresh())
440
+ .catch(() => refresh())
441
+ }
432
442
  const frozen = Boolean(watchdog.frozenAt) || watchdog.waterline === 'frost'
433
443
  const paused = Boolean(watchdog.pausedAt) || watchdog.waterline === 'pause'
434
444
  const grace = Number.isFinite(watchdog.graceUntil) && Date.now() < watchdog.graceUntil
@@ -481,6 +491,10 @@ window.__ModuleLoader__.load({
481
491
  ),
482
492
  watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
483
493
  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 || '—', policy: watchdog.tamper.policy || '' })) : null,
494
+ h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
495
+ h('button', { style: button, onClick: () => toggleHeap6g(!watchdog.heap6g) }, watchdog.heap6g ? t('watchdog.heap6gOn') : t('watchdog.heap6gOff')),
496
+ watchdog.heap6g ? h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('watchdog.heap6gPending')) : null,
497
+ ),
484
498
  h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
485
499
  h('button', { style: { ...button, padding: '5px 10px', opacity: frozen ? 0.5 : 1 }, disabled: frozen, title: frozen ? t('watchdog.measureBlocked') : undefined, onClick: () => { if (!frozen) act('probe') } }, t('watchdog.measure')),
486
500
  watchdog.probeProgress ? h('span', { style: { ...C.mono, fontSize: 11.5 } }, `${watchdog.probeProgress.done || 0}/${watchdog.probeProgress.total || 0}`) : null,
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /**
5
+ * Startup-phase memory watch (1.6.0).
6
+ *
7
+ * Samples the host heap every 500 ms from watchdog activation until the clean
8
+ * baseline is recorded (or `maxMs`). Every sample goes to a run-<pid>.jsonl file
9
+ * so that a later boot (or the external guard) can see the curve even when this
10
+ * process dies. Two stricter startup thresholds raise a safe-boot plan:
11
+ * - growth rate > rateMBps (default 150 MB/s), or
12
+ * - total heap > totalMB (2000 on a 4 GB host, 3000 on a 6 GB host).
13
+ */
14
+ export const BOOT_SAMPLE_MS = 500
15
+ export const BOOT_MAX_MS = 120_000
16
+ export const BOOT_RATE_MBPS = 150
17
+ export const RUN_KEEP = 5
18
+
19
+ export function bootThresholdsFor(heapLimitBytes) {
20
+ const limitGB = Number(heapLimitBytes) / (1024 * 1024 * 1024)
21
+ return {
22
+ rateMBps: BOOT_RATE_MBPS,
23
+ totalMB: limitGB >= 5.5 ? 3000 : 2000,
24
+ }
25
+ }
26
+
27
+ export function trimRunFiles(dataDir, keep = RUN_KEEP) {
28
+ let entries
29
+ try {
30
+ entries = fs.readdirSync(dataDir).filter((name) => /^run-(\d+)-\d+\.jsonl$/.test(name)).map((name) => ({ name, at: Number(name.match(/^run-(\d+)-\d+/)[1]) }))
31
+ } catch {
32
+ return
33
+ }
34
+ entries.sort((a, b) => a.at - b.at)
35
+ while (entries.length > keep) {
36
+ try {
37
+ fs.unlinkSync(path.join(dataDir, entries.shift().name))
38
+ } catch {
39
+ break
40
+ }
41
+ }
42
+ }
43
+
44
+ export function createBootWatch({ dataDir, processLike = process, watchdogState, onTrigger, onFinish, sampleMs = BOOT_SAMPLE_MS, maxMs = BOOT_MAX_MS }) {
45
+ const startedAt = Date.now()
46
+ const pid = processLike.pid
47
+ const runFile = path.join(dataDir, `run-${startedAt}-${pid}.jsonl`)
48
+ trimRunFiles(dataDir)
49
+ const samples = []
50
+ let previous = null
51
+ let triggered = null
52
+ let timer = null
53
+ let finished = false
54
+ let bundleCount = null
55
+
56
+ function write(line) {
57
+ try {
58
+ fs.appendFileSync(runFile, `${JSON.stringify(line)}\n`)
59
+ } catch {
60
+ // best effort: the file is diagnostic only
61
+ }
62
+ }
63
+
64
+ function thresholds() {
65
+ const limit = processLike.memoryUsage ? 4 * 1024 * 1024 * 1024 : 4 * 1024 * 1024 * 1024
66
+ return bootThresholdsFor(watchdogState && watchdogState.thresholds ? watchdogState.thresholds.heapLimit : limit)
67
+ }
68
+
69
+ function tick() {
70
+ if (finished) return
71
+ const now = Date.now()
72
+ const usage = typeof processLike.memoryUsage === 'function' ? processLike.memoryUsage() : { heapUsed: 0, rss: 0, heapTotal: 0 }
73
+ const heapUsed = Number(usage.heapUsed) || 0
74
+ const record = {
75
+ t: new Date(now).toISOString(),
76
+ elapsedMs: now - startedAt,
77
+ heapUsed,
78
+ heapTotal: Number(usage.heapTotal) || 0,
79
+ rss: Number(usage.rss) || 0,
80
+ bundles: bundleCount,
81
+ phase: watchdogState && watchdogState.startedAt ? 'startup' : 'init',
82
+ }
83
+ samples.push(record)
84
+ write(record)
85
+
86
+ if (!triggered) {
87
+ const t = thresholds()
88
+ const rate = previous && now > previous.at ? ((heapUsed - previous.heapUsed) / (now - previous.at)) * 1000 / (1024 * 1024) : 0
89
+ const totalMB = heapUsed / (1024 * 1024)
90
+ const reason = totalMB >= t.totalMB ? `startup heap ${Math.round(totalMB)} MB >= ${t.totalMB} MB` : rate >= t.rateMBps ? `startup growth ${Math.round(rate)} MB/s >= ${t.rateMBps} MB/s` : null
91
+ if (reason) {
92
+ triggered = { at: record.t, reason, rateMBps: Math.round(rate), totalMB: Math.round(totalMB) }
93
+ try {
94
+ if (typeof onTrigger === 'function') onTrigger(triggered)
95
+ } catch {
96
+ // the caller records the incident
97
+ }
98
+ }
99
+ }
100
+ previous = { at: now, heapUsed }
101
+
102
+ const clean = watchdogState && watchdogState.baseline
103
+ if (clean || now - startedAt >= maxMs) finish('clean-boot')
104
+ }
105
+
106
+ function finish(reason) {
107
+ if (finished) return
108
+ finished = true
109
+ if (timer) clearInterval(timer)
110
+ const peak = samples.reduce((max, sample) => Math.max(max, sample.heapUsed), 0)
111
+ const summary = {
112
+ reason,
113
+ runFile: path.basename(runFile),
114
+ samples: samples.length,
115
+ peakMB: Math.round(peak / (1024 * 1024)),
116
+ startedAt: new Date(startedAt).toISOString(),
117
+ durationMs: Date.now() - startedAt,
118
+ triggered,
119
+ thresholds: thresholds(),
120
+ }
121
+ write({ t: new Date().toISOString(), summary })
122
+ try {
123
+ if (typeof onFinish === 'function') onFinish(summary)
124
+ } catch {
125
+ // the caller only mirrors the summary
126
+ }
127
+ return summary
128
+ }
129
+
130
+ timer = setInterval(tick, sampleMs)
131
+ if (typeof timer.unref === 'function') timer.unref()
132
+ tick()
133
+
134
+ return {
135
+ runFile,
136
+ setBundleCount(count) {
137
+ bundleCount = Number(count) || 0
138
+ },
139
+ tick,
140
+ stop: finish,
141
+ summary() {
142
+ return { runFile: path.basename(runFile), samples: samples.length, triggered }
143
+ },
144
+ }
145
+ }
package/lib/tools.js CHANGED
@@ -214,6 +214,8 @@ export async function installTools({ ctx, config = {}, logger } = {}) {
214
214
  baselineAt: snapshot.baseline ? snapshot.baseline.at : null,
215
215
  budgets: snapshot.budgets,
216
216
  tamper: snapshot.tamper,
217
+ boot: snapshot.boot,
218
+ heap6g: snapshot.heap6g,
217
219
  rss: snapshot.rss,
218
220
  rssAt: snapshot.rssAt,
219
221
  rssError: snapshot.rssError,
@@ -10,6 +10,7 @@ import { createTamperMonitor } from './tamper-monitor.js'
10
10
  import { remediationFor } from './remediation.js'
11
11
  import { notify } from './notifier.js'
12
12
  import { startRssScannerV2 } from './rss-scan.js'
13
+ import { createBootWatch } from './boot-watch.js'
13
14
  import {
14
15
  attributeCrash,
15
16
  classifyWaterline,
@@ -136,6 +137,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
136
137
  watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
137
138
  watchdogState.crashFallback = config.crashFallback === 'dry-run' ? 'dry-run' : 'enforce'
138
139
  watchdogState.probeStarted = false
140
+ watchdogState.boot = null
141
+ watchdogState.heap6g = false
139
142
  watchdogState.lastCrashScan = 0
140
143
  watchdogState.baseline = null
141
144
  for (const plan of watchdogState.plans) plan.applied = false
@@ -148,6 +151,23 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
148
151
  let tamper = null
149
152
  restoreState()
150
153
  readCrashLogs()
154
+ let bootWatch = null
155
+ try {
156
+ bootWatch = createBootWatch({
157
+ dataDir,
158
+ watchdogState,
159
+ onTrigger: (trigger) => {
160
+ appendIncident({ kind: 'startup-memory', detail: '启动期内存失控:' + trigger.reason, rateMBps: trigger.rateMBps, totalMB: trigger.totalMB })
161
+ writePendingBoot({ level: 'L3', reason: 'startup-memory', safeBoot: true, disable: [], keep: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@twinsearth/ai-prison-dsh-plugin'] })
162
+ },
163
+ onFinish: (summary) => {
164
+ watchdogState.boot = summary
165
+ },
166
+ })
167
+ watchdogState.boot = bootWatch.summary()
168
+ } catch (error) {
169
+ watchdogState.degraded = 'boot watch: ' + String((error && error.message) || error)
170
+ }
151
171
  setupTamperMonitor()
152
172
 
153
173
  function setupTamperMonitor() {
@@ -263,7 +283,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
263
283
  }
264
284
 
265
285
  function startRssScanner() {
266
- if (rssTimer || process.platform !== 'win32' || watchdogState.config.rssScan === false) return
286
+ if (rssTimer || process.platform !== 'win32' || watchdogState.config.rssScan !== true) return
267
287
  const timer = setTimeout(scanChildRss, 5000)
268
288
  if (typeof timer.unref === 'function') timer.unref()
269
289
  rssTimer = setInterval(scanChildRss, RSS_INTERVAL_MS)
@@ -816,12 +836,17 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
816
836
  ctx.inject(['pluginManager'], (child) => {
817
837
  refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
818
838
  if (refs.manager) {
839
+ if (bootWatch && typeof refs.manager.listBundles === 'function') {
840
+ void refs.manager.listBundles().then((rows) => bootWatch.setBundleCount(rows.length)).catch(() => {})
841
+ }
819
842
  void reapplyQuarantine()
820
843
  startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets: EXEMPT_TARGETS })
821
- const probeTimer = setTimeout(() => {
822
- void scheduleProbe()
823
- }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
824
- if (typeof probeTimer.unref === 'function') probeTimer.unref()
844
+ if (config.probeAuto === true) {
845
+ const probeTimer = setTimeout(() => {
846
+ void scheduleProbe()
847
+ }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
848
+ if (typeof probeTimer.unref === 'function') probeTimer.unref()
849
+ }
825
850
  }
826
851
  })
827
852
  }
@@ -909,6 +934,19 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
909
934
  }
910
935
  const action = typeof body.action === 'string' ? body.action : ''
911
936
  const target = typeof body.target === 'string' ? body.target : ''
937
+ if (action === 'heap6g') {
938
+ const enabled = body.enabled === true
939
+ const flagPath = path.join('E:/ToFuture/tools', 'heap6g.flag')
940
+ try {
941
+ if (enabled) fs.writeFileSync(flagPath, JSON.stringify({ enabled: true, at: new Date().toISOString() }, null, 2) + '\n')
942
+ else fs.rmSync(flagPath, { force: true })
943
+ watchdogState.heap6g = enabled
944
+ appendIncident({ kind: 'heap6g', detail: enabled ? '已请求下次启动使用 6GB 堆(由 AI Prison Guard 应用)' : '已取消 6GB 堆请求' })
945
+ } catch (error) {
946
+ return Response.json({ ok: false, error: String((error && error.message) || error) }, { status: 500 })
947
+ }
948
+ return Response.json({ ok: true, enabled })
949
+ }
912
950
  if (action === 'probe') {
913
951
  const progress = await scheduleProbe({ force: true })
914
952
  return Response.json({ ok: true, progress })
@@ -1021,6 +1059,8 @@ export function watchdogSnapshot() {
1021
1059
  baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
1022
1060
  budgets: s.budgets,
1023
1061
  tamper: s.tamper || null,
1062
+ boot: s.boot || null,
1063
+ heap6g: s.heap6g === true,
1024
1064
  rss: s.rss || {},
1025
1065
  rssAt: s.rssAt || null,
1026
1066
  rssError: s.rssError || null,
package/locale/en.json CHANGED
@@ -21,5 +21,8 @@
21
21
  "watchdog.measure": "Measure plugin budgets now",
22
22
  "watchdog.measureBlocked": "Heap is frozen: measuring spawns child processes, so it stays disabled until the heap recovers.",
23
23
  "prison.rss": "Child RSS",
24
- "prison.plugin": "Plugin"
24
+ "prison.plugin": "Plugin",
25
+ "watchdog.heap6gOff": "Request 6 GB heap on next launch",
26
+ "watchdog.heap6gOn": "Cancel the 6 GB heap request",
27
+ "watchdog.heap6gPending": "Guard will apply it on next launch (the app must be closed)."
25
28
  }
package/locale/zh.json CHANGED
@@ -21,5 +21,8 @@
21
21
  "watchdog.measure": "立即测量插件预算",
22
22
  "watchdog.measureBlocked": "堆已冻结:测量会启动子进程,恢复前暂停测量。",
23
23
  "prison.rss": "子进程 RSS",
24
- "prison.plugin": "插件"
24
+ "prison.plugin": "插件",
25
+ "watchdog.heap6gOff": "请求下次启动使用 6GB 堆",
26
+ "watchdog.heap6gOn": "取消 6GB 堆请求",
27
+ "watchdog.heap6gPending": "下次由 AI Prison Guard 启动时应用(需完全退出 DSH)。"
25
28
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.5.4",
3
+ "version": "1.6.1",
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",