@twinsearth/ai-prison-dsh-plugin 1.5.3 → 1.6.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,42 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.6.0] — 2026-11-18
6
+
7
+ ### Added — startup watchdog, safe boot and panel 6 GB control
8
+
9
+ - **bootWatch**: 500 ms heap sampling from watchdog activation to the clean
10
+ baseline, written to `.ai-prison-watchdog/run-<start>.jsonl` (last 5 kept) so a
11
+ post-crash boot or the guard can inspect the curve even when the host died.
12
+ - **Startup thresholds**: growth > 150 MB/s or total > 2.0 GB (4 GB host) /
13
+ > 3.0 GB (6 GB host) writes a safe-boot plan (base + web-app + ai-prison) and
14
+ records a `startup-memory` incident; the guard enforces it on next launch.
15
+ - **Guard v2**: startup-phase OOM in the newest crash log forces that safe boot,
16
+ moves the ai-prison bundle to position 2, applies pending-boot plans, updates
17
+ the 6 GB heap patch from a flag file, and logs the last startup curve.
18
+ - **Panel 6 GB control**: the Enforcement card can request/cancel "6 GB heap on
19
+ next launch"; the request is a flag file the guard consumes.
20
+ - **Safer defaults**: RSS child scan and automatic budget probes are now **off**
21
+ unless explicitly enabled (`rssScan: true`, `probeAuto: true`); notifications
22
+ stay off. This also removes the 1.5.x periodic subprocess spawns from startup.
23
+ - `ai_prison_watchdog_status` now reports `boot` (run file, peak, trigger) and
24
+ `heap6g`.
25
+
26
+ ### Note
27
+ - The panel heap toggle only takes effect on the next launch through the guard,
28
+ because the archive is locked while DSH runs.
29
+
30
+ ## [1.5.4] — 2026-11-18
31
+ ## [1.5.4] — 2026-11-18
32
+
33
+ ### Fixed — RSS diagnostics were invisible
34
+
35
+ - `state.json` and `ai_prison_watchdog_status` now carry `rss`, `rssAt`,
36
+ `rssError`, `rssStats`, `rssServiceError` and `rssAttempts`, and the values are
37
+ restored on reload. Before this, a working (or failing) scan could not be
38
+ observed outside the panel route.
39
+
40
+ ## [1.5.3] — 2026-11-18
5
41
  ## [1.5.3] — 2026-11-18
6
42
 
7
43
  ### Fixed — CI
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,13 @@ 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,
219
+ rss: snapshot.rss,
220
+ rssAt: snapshot.rssAt,
221
+ rssError: snapshot.rssError,
222
+ rssStats: snapshot.rssStats,
223
+ rssServiceError: snapshot.rssServiceError,
217
224
  operations: snapshot.operations,
218
225
  incidents: snapshot.incidents,
219
226
  note: snapshot.enforce
@@ -136,6 +136,8 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
136
136
  watchdogState.config = { sampleMs: SAMPLE_MS, ...config }
137
137
  watchdogState.crashFallback = config.crashFallback === 'dry-run' ? 'dry-run' : 'enforce'
138
138
  watchdogState.probeStarted = false
139
+ watchdogState.boot = null
140
+ watchdogState.heap6g = false
139
141
  watchdogState.lastCrashScan = 0
140
142
  watchdogState.baseline = null
141
143
  for (const plan of watchdogState.plans) plan.applied = false
@@ -148,6 +150,23 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
148
150
  let tamper = null
149
151
  restoreState()
150
152
  readCrashLogs()
153
+ let bootWatch = null
154
+ try {
155
+ bootWatch = createBootWatch({
156
+ dataDir,
157
+ watchdogState,
158
+ onTrigger: (trigger) => {
159
+ appendIncident({ kind: 'startup-memory', detail: '启动期内存失控:' + trigger.reason, rateMBps: trigger.rateMBps, totalMB: trigger.totalMB })
160
+ writePendingBoot({ level: 'L3', reason: 'startup-memory', safeBoot: true, disable: [], keep: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@twinsearth/ai-prison-dsh-plugin'] })
161
+ },
162
+ onFinish: (summary) => {
163
+ watchdogState.boot = summary
164
+ },
165
+ })
166
+ watchdogState.boot = bootWatch.summary()
167
+ } catch (error) {
168
+ watchdogState.degraded = 'boot watch: ' + String((error && error.message) || error)
169
+ }
151
170
  setupTamperMonitor()
152
171
 
153
172
  function setupTamperMonitor() {
@@ -263,7 +282,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
263
282
  }
264
283
 
265
284
  function startRssScanner() {
266
- if (rssTimer || process.platform !== 'win32' || watchdogState.config.rssScan === false) return
285
+ if (rssTimer || process.platform !== 'win32' || watchdogState.config.rssScan !== true) return
267
286
  const timer = setTimeout(scanChildRss, 5000)
268
287
  if (typeof timer.unref === 'function') timer.unref()
269
288
  rssTimer = setInterval(scanChildRss, RSS_INTERVAL_MS)
@@ -281,6 +300,12 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
281
300
  baseline: watchdogState.baseline,
282
301
  budgets: watchdogState.budgets,
283
302
  quarantine: [...watchdogState.quarantine].map(([target, entry]) => ({ target, ...entry })),
303
+ rss: watchdogState.rss || {},
304
+ rssAt: watchdogState.rssAt || null,
305
+ rssError: watchdogState.rssError || null,
306
+ rssStats: watchdogState.rssStats || null,
307
+ rssServiceError: watchdogState.rssServiceError || null,
308
+ rssAttempts: watchdogState.rssAttempts || 0,
284
309
  migratedTamperQuarantine: tamperMigrationDone,
285
310
  }
286
311
  try {
@@ -298,6 +323,10 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
298
323
  if (parsed.escalation && Array.isArray(parsed.escalation.crashes)) watchdogState.escalation = { crashes: parsed.escalation.crashes.slice(-50), level: parsed.escalation.level || 'L0' }
299
324
  if (parsed.baseline && Array.isArray(parsed.baseline.bundles)) watchdogState.baseline = parsed.baseline
300
325
  if (parsed.budgets && typeof parsed.budgets === 'object') watchdogState.budgets = parsed.budgets
326
+ if (parsed.rss && typeof parsed.rss === 'object') watchdogState.rss = parsed.rss
327
+ if (parsed.rssAt) watchdogState.rssAt = parsed.rssAt
328
+ if (parsed.rssStats) watchdogState.rssStats = parsed.rssStats
329
+ watchdogState.rssAttempts = Number(parsed.rssAttempts) || 0
301
330
  tamperMigrationDone = parsed.migratedTamperQuarantine === true
302
331
  if (Array.isArray(parsed.quarantine)) {
303
332
  let dropped = 0
@@ -806,12 +835,17 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
806
835
  ctx.inject(['pluginManager'], (child) => {
807
836
  refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
808
837
  if (refs.manager) {
838
+ if (bootWatch && typeof refs.manager.listBundles === 'function') {
839
+ void refs.manager.listBundles().then((rows) => bootWatch.setBundleCount(rows.length)).catch(() => {})
840
+ }
809
841
  void reapplyQuarantine()
810
842
  startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets: EXEMPT_TARGETS })
811
- const probeTimer = setTimeout(() => {
812
- void scheduleProbe()
813
- }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
814
- if (typeof probeTimer.unref === 'function') probeTimer.unref()
843
+ if (config.probeAuto === true) {
844
+ const probeTimer = setTimeout(() => {
845
+ void scheduleProbe()
846
+ }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
847
+ if (typeof probeTimer.unref === 'function') probeTimer.unref()
848
+ }
815
849
  }
816
850
  })
817
851
  }
@@ -899,6 +933,19 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
899
933
  }
900
934
  const action = typeof body.action === 'string' ? body.action : ''
901
935
  const target = typeof body.target === 'string' ? body.target : ''
936
+ if (action === 'heap6g') {
937
+ const enabled = body.enabled === true
938
+ const flagPath = path.join('E:/ToFuture/tools', 'heap6g.flag')
939
+ try {
940
+ if (enabled) fs.writeFileSync(flagPath, JSON.stringify({ enabled: true, at: new Date().toISOString() }, null, 2) + '\n')
941
+ else fs.rmSync(flagPath, { force: true })
942
+ watchdogState.heap6g = enabled
943
+ appendIncident({ kind: 'heap6g', detail: enabled ? '已请求下次启动使用 6GB 堆(由 AI Prison Guard 应用)' : '已取消 6GB 堆请求' })
944
+ } catch (error) {
945
+ return Response.json({ ok: false, error: String((error && error.message) || error) }, { status: 500 })
946
+ }
947
+ return Response.json({ ok: true, enabled })
948
+ }
902
949
  if (action === 'probe') {
903
950
  const progress = await scheduleProbe({ force: true })
904
951
  return Response.json({ ok: true, progress })
@@ -1011,6 +1058,8 @@ export function watchdogSnapshot() {
1011
1058
  baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
1012
1059
  budgets: s.budgets,
1013
1060
  tamper: s.tamper || null,
1061
+ boot: s.boot || null,
1062
+ heap6g: s.heap6g === true,
1014
1063
  rss: s.rss || {},
1015
1064
  rssAt: s.rssAt || null,
1016
1065
  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.3",
3
+ "version": "1.6.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",