@twinsearth/ai-prison-dsh-plugin 1.6.1 → 1.7.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.
@@ -0,0 +1,85 @@
1
+ import v8 from 'node:v8'
2
+ import { MAX_SAMPLES } from './watchdog-state.js'
3
+ import { classifyWaterline, formatBytes, thresholdsFor } from './watchdog-policy.js'
4
+ import { remediationFor } from './remediation.js'
5
+
6
+ /**
7
+ * Heap sampling and waterline transitions (ok -> warn -> pause -> frost).
8
+ *
9
+ * `sample()` records one metric sample, emits the first incident per level and
10
+ * calls `onAfterSample` so the runtime can schedule the clean baseline and
11
+ * refresh the tamper status. It never touches the plugin manager.
12
+ */
13
+ export function createSampler({ watchdogState, persist, appendIncident, log, onAfterSample }) {
14
+ function sample() {
15
+ let heap
16
+ try {
17
+ heap = v8.getHeapStatistics()
18
+ } catch {
19
+ heap = { heap_size_limit: 0, used_heap_size: 0, total_heap_size: 0 }
20
+ }
21
+ const usage = process.memoryUsage()
22
+ const heapLimit = Number(heap.heap_size_limit) > 0 ? Number(heap.heap_size_limit) : 4 * 1024 * 1024 * 1024
23
+ const thresholds = thresholdsFor(heapLimit)
24
+ watchdogState.thresholds = thresholds
25
+ const heapUsed = Number(usage.heapUsed) > 0 ? Number(usage.heapUsed) : Number(heap.used_heap_size) || 0
26
+ const previous = watchdogState.waterline
27
+ const waterline = classifyWaterline(heapUsed, thresholds, previous)
28
+ const record = {
29
+ t: new Date().toISOString(),
30
+ heapUsed,
31
+ heapTotal: Number(usage.heapTotal) || Number(heap.total_heap_size) || 0,
32
+ external: Number(usage.external) || 0,
33
+ rss: Number(usage.rss) || 0,
34
+ heapLimit,
35
+ waterline,
36
+ }
37
+ watchdogState.latest = record
38
+ watchdogState.waterline = waterline
39
+ watchdogState.strongWarn = waterline !== 'ok' && heapUsed >= thresholds.opWarn
40
+ watchdogState.samples.push(record)
41
+ if (watchdogState.samples.length > MAX_SAMPLES) watchdogState.samples = watchdogState.samples.slice(-MAX_SAMPLES)
42
+
43
+ if (waterline === 'frost' && !watchdogState.frozenAt) {
44
+ watchdogState.frozenAt = record.t
45
+ const incident = appendIncident({
46
+ kind: 'freeze',
47
+ level: 'frost',
48
+ heapUsed,
49
+ heapLimit,
50
+ detail: `heap ${formatBytes(heapUsed)} ≥ block ${formatBytes(thresholds.totalBlock)}:冻结插件操作`,
51
+ remediation: remediationFor('freeze'),
52
+ })
53
+ log.warn(`[ai-prison-watchdog] ${incident.detail}`)
54
+ persist(true)
55
+ } else if (waterline === 'pause' && !watchdogState.pausedAt) {
56
+ watchdogState.pausedAt = record.t
57
+ appendIncident({
58
+ kind: 'pause',
59
+ level: 'pause',
60
+ heapUsed,
61
+ heapLimit,
62
+ detail: `heap ${formatBytes(heapUsed)} ≥ pause ${formatBytes(thresholds.totalPause)}:插件操作需二次确认`,
63
+ remediation: remediationFor('pause'),
64
+ })
65
+ persist(true)
66
+ } else if (waterline === 'warn' && previous !== 'warn' && previous === 'ok') {
67
+ appendIncident({ kind: 'waterline', level: 'warn', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ warn ${formatBytes(thresholds.totalWarn)}` })
68
+ }
69
+ if (waterline === 'ok') {
70
+ watchdogState.pausedAt = null
71
+ watchdogState.frozenAt = null
72
+ watchdogState.graceUntil = null
73
+ }
74
+ if (waterline === 'warn') {
75
+ watchdogState.frozenAt = null
76
+ watchdogState.graceUntil = null
77
+ }
78
+ if (watchdogState.strongWarn && waterline === 'pause') {
79
+ appendIncident({ kind: 'strong-warn', level: 'pause', heapUsed, heapLimit, detail: `heap ${formatBytes(heapUsed)} ≥ 强警告 ${formatBytes(thresholds.opWarn)}` })
80
+ }
81
+ if (typeof onAfterSample === 'function') onAfterSample()
82
+ }
83
+
84
+ return { sample }
85
+ }
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { topOperations, rankTopPlugins } from './watchdog-policy.js'
4
+ import { watchdogState } from './watchdog-state.js'
5
+
6
+ /** Top5 v2: measured + estimate + child RSS with EWMA smoothing and rank hysteresis. */
7
+ function mergedTop(state, limit) {
8
+ const operations = topOperations(state.operations, 50)
9
+ const { rows, nextRanking } = rankTopPlugins({
10
+ operations,
11
+ budgets: state.budgets || {},
12
+ rss: state.rss || {},
13
+ previous: state.ranking || {},
14
+ limit,
15
+ })
16
+ state.ranking = nextRanking
17
+ return rows.map((row) => ({
18
+ target: row.target,
19
+ count: row.count || 0,
20
+ estimateMB: row.moduleLoadMB || row.operationMB || 0,
21
+ rssMB: row.rssMB || 0,
22
+ totalMB: row.score,
23
+ lastAt: row.measuredAt || null,
24
+ version: row.version || null,
25
+ source: row.source,
26
+ }))
27
+ }
28
+
29
+ /** The pending-boot plan exists, but no external consumer ships with the plugin. */
30
+ function pendingBootInfo(state) {
31
+ const file = state.dataDir ? path.join(state.dataDir, 'pending-boot.json') : null
32
+ if (!file || !fs.existsSync(file)) return { exists: false, file: null, consumer: 'none', appliesNextBoot: false }
33
+ let plan = null
34
+ try {
35
+ plan = JSON.parse(fs.readFileSync(file, 'utf8'))
36
+ } catch {
37
+ plan = null
38
+ }
39
+ return {
40
+ exists: true,
41
+ file,
42
+ level: plan && plan.level ? plan.level : null,
43
+ writtenAt: plan && plan.writtenAt ? plan.writtenAt : null,
44
+ consumer: 'none',
45
+ appliesNextBoot: false,
46
+ hint: 'pending-boot 已写入,但当前插件不附带外部消费器:仅本次运行的进程内隔离生效,下次启动需人工处理。',
47
+ }
48
+ }
49
+
50
+ /** Serialisable snapshot shared by the status tool, the panel route and tests. */
51
+ export function watchdogSnapshot() {
52
+ const s = watchdogState
53
+ const quarantine = []
54
+ for (const [target, entry] of s.quarantine instanceof Map ? s.quarantine : []) {
55
+ quarantine.push({ target, ...entry })
56
+ }
57
+ return {
58
+ ok: Boolean(s.startedAt),
59
+ mode: s.mode,
60
+ enforce: s.enforce,
61
+ startedAt: s.startedAt,
62
+ runId: s.runId,
63
+ dataDir: s.dataDir,
64
+ degraded: s.degraded,
65
+ heap: s.latest,
66
+ thresholds: s.thresholds,
67
+ waterline: s.waterline,
68
+ strongWarn: s.strongWarn,
69
+ pausedAt: s.pausedAt,
70
+ graceUntil: s.graceUntil,
71
+ frozenAt: s.frozenAt,
72
+ samples: s.samples.slice(-30),
73
+ operations: mergedTop(s, 10),
74
+ topFive: mergedTop(s, 5),
75
+ probeProgress: s.probeProgress || null,
76
+ quarantine,
77
+ plans: s.plans.slice(-5),
78
+ escalation: { level: s.escalation.level, crashes: s.escalation.crashes.slice(-10) },
79
+ crashFallback: s.crashFallback || 'enforce',
80
+ baseline: s.baseline ? { at: s.baseline.at, runId: s.baseline.runId, bundles: s.baseline.bundles } : null,
81
+ pendingBoot: pendingBootInfo(s),
82
+ budgets: s.budgets,
83
+ tamper: s.tamper || null,
84
+ boot: s.boot || null,
85
+ heap6g: s.heap6g === true,
86
+ heap6gRequest: s.dataDir && fs.existsSync(path.join(s.dataDir, 'heap6g-request.json')) ? path.join(s.dataDir, 'heap6g-request.json') : null,
87
+ rss: s.rss || {},
88
+ rssAt: s.rssAt || null,
89
+ rssError: s.rssError || null,
90
+ rssStats: s.rssStats || null,
91
+ rssServiceError: s.rssServiceError || null,
92
+ incidents: s.incidents.slice(-20),
93
+ generatedAt: new Date().toISOString(),
94
+ }
95
+ }
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Shared in-process state of the AI Prison watchdog.
3
3
  *
4
- * P0 wrote it in observe mode; P1 keeps the same shape and adds the enforcement
5
- * registries (quarantine, pause grace, hot-operation counters, budget table,
6
- * baseline, crash plans). Nothing here touches the plugin manager by itself.
4
+ * The shape started as a P0 observe-only snapshot; it now also holds the
5
+ * enforcement registries (quarantine, pause grace, hot-operation counters,
6
+ * budget table, baseline, crash plans). Enforcement is the default; observe
7
+ * mode (`config.enforce: false`) uses the same state and only skips actions.
8
+ * Nothing here touches the plugin manager by itself.
7
9
  */
8
10
  export const watchdogState = {
9
11
  mode: 'enforce',
package/locale/en.json CHANGED
@@ -1,28 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "AI Prison",
4
- "description": "Wraps the aiprison CLI as six DSH tools (levels, status, demo, drill, inspect, verify, repair-tail) and adds a sidebar panel showing the L0–L5 grading matrix together with the durable ledger's audit-chain integrity and record count. Open it from the sidebar's shield entry; the panel is read-only and never writes to the ledger. Ledgers live in <session working directory>/.ai-prison unless a data directory is configured. Every capability-removal backend (GRAM, TLM, hardware binding, MicroVM isolation) stays simulated, so the tools audit and demonstrate governance instead of enforcing real isolation.",
4
+ "description": "Wraps the aiprison CLI as eight DSH tools (levels, status, watchdog status, demo, drill, inspect, verify, repair-tail) and adds a sidebar panel showing the L0–L5 grading matrix together with the durable ledger's audit-chain integrity and record count. Open it from the sidebar's shield entry; the panel is read-only and never writes to the ledger. Ledgers live in <session working directory>/.ai-prison unless a data directory is configured. Every capability-removal backend (GRAM, TLM, hardware binding, MicroVM isolation) stays simulated, so the tools audit and demonstrate governance instead of enforcing real isolation.",
5
5
  "detail": "docs/DETAIL.md"
6
- },
7
- "watchdog.enforceTitle": "Enforcement",
8
- "watchdog.enforceOn": "enforce",
9
- "watchdog.observeOnly": "observe only",
10
- "watchdog.freezeHint": "Heap is frozen at {level}: plugin operations are blocked except release actions. Close the biggest plugins below or restart DSH.",
11
- "watchdog.confirmPause": "I understand: allow plugin operations for 10 minutes",
12
- "watchdog.quarantine": "Plugin prison",
13
- "watchdog.noQuarantine": "No quarantined plugins.",
14
- "watchdog.release": "Release",
15
- "watchdog.topFive": "Top {n} by estimated heap",
16
- "watchdog.close": "Close now",
17
- "watchdog.plans": "Crash plans (dry-run)",
18
- "watchdog.noPlans": "No crash attribution plans.",
19
- "watchdog.baseline": "Clean baseline: {at}",
20
- "watchdog.tamper": "Profile watch: {n} critical file(s) · policy {policy} · last check {at}",
21
- "watchdog.measure": "Measure plugin budgets now",
22
- "watchdog.measureBlocked": "Heap is frozen: measuring spawns child processes, so it stays disabled until the heap recovers.",
23
- "prison.rss": "Child RSS",
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)."
6
+ }
28
7
  }
package/locale/zh.json CHANGED
@@ -1,28 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "AI Prison · AI 监狱",
4
- "description": "把 aiprison CLI 封装为六个 DSH 工具(levels、status、demo、drill、inspect、verify、repair-tail),并在侧边栏增加一个面板:展示 L0–L5 分级矩阵,以及落盘账本的审计链完整性与记录数。从侧边栏的盾牌入口打开;面板只读,不会写入数据目录。账本默认写到 <会话工作目录>/.ai-prison,也可在配置里指定数据目录。GRAM、TLM、硬件绑定、MicroVM 隔离等能力摘除后端全部为内存模拟 —— 这些工具用于审计与演示治理流程,并不执行真实隔离。",
4
+ "description": "把 aiprison CLI 封装为八个 DSH 工具(levels、status、watchdog status、demo、drill、inspect、verify、repair-tail),并在侧边栏增加一个面板:展示 L0–L5 分级矩阵,以及落盘账本的审计链完整性与记录数。从侧边栏的盾牌入口打开;面板只读,不会写入数据目录。账本默认写到 <会话工作目录>/.ai-prison,也可在配置里指定数据目录。GRAM、TLM、硬件绑定、MicroVM 隔离等能力摘除后端全部为内存模拟 —— 这些工具用于审计与演示治理流程,并不执行真实隔离。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
- },
7
- "watchdog.enforceTitle": "执行状态",
8
- "watchdog.enforceOn": "enforce",
9
- "watchdog.observeOnly": "仅观察",
10
- "watchdog.freezeHint": "堆水位已冻结({level}):除释放类操作外,所有插件操作被禁止。请关闭下方内存最大的插件或重启 DSH。",
11
- "watchdog.confirmPause": "我已知晓:允许插件操作 10 分钟",
12
- "watchdog.quarantine": "插件监狱",
13
- "watchdog.noQuarantine": "没有被隔离的插件。",
14
- "watchdog.release": "假释",
15
- "watchdog.topFive": "按估算内存排序的前 {n} 个插件",
16
- "watchdog.close": "立即关闭",
17
- "watchdog.plans": "崩溃降级计划(dry-run)",
18
- "watchdog.noPlans": "暂无崩溃归因计划。",
19
- "watchdog.baseline": "干净基线:{at}",
20
- "watchdog.tamper": "配置监控:{n} 个关键文件 · 策略 {policy} · 最近检查 {at}",
21
- "watchdog.measure": "立即测量插件预算",
22
- "watchdog.measureBlocked": "堆已冻结:测量会启动子进程,恢复前暂停测量。",
23
- "prison.rss": "子进程 RSS",
24
- "prison.plugin": "插件",
25
- "watchdog.heap6gOff": "请求下次启动使用 6GB 堆",
26
- "watchdog.heap6gOn": "取消 6GB 堆请求",
27
- "watchdog.heap6gPending": "下次由 AI Prison Guard 启动时应用(需完全退出 DSH)。"
6
+ }
28
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.6.1",
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.",
3
+ "version": "1.7.0",
4
+ "description": "AI Prison for DSH: eight governance tools wrapping the aiprison CLI (levels, status, watchdog status, 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",
7
7
  "license": "MIT",
@@ -57,6 +57,7 @@
57
57
  ],
58
58
  "scripts": {
59
59
  "test": "node --test test/*.test.mjs",
60
+ "coverage": "node --test --experimental-test-coverage --test-coverage-lines=70 --test-coverage-branches=65 --test-coverage-functions=75 test/*.test.mjs",
60
61
  "check": "node scripts/release-check.mjs"
61
62
  },
62
63
  "dsh": {
package/watchdog.js CHANGED
@@ -1,12 +1,18 @@
1
1
  import { createWatchdog } from './lib/watchdog-runtime.js'
2
2
 
3
3
  /**
4
- * AI Prison watchdog loader row (P0: observe only).
4
+ * AI Prison watchdog loader row.
5
5
  *
6
- * It samples the host heap, accounts plugin operations, reads recent host crash
7
- * logs and serves a read-only snapshot at /api/ai-prison/watchdog/status.
8
- * It never enables or disables a plugin: enforcement stays in later phases until
9
- * the design is confirmed.
6
+ * Samples the host heap, accounts plugin operations, reads recent host crash
7
+ * logs, watches the profile files and startup memory, and serves the status and
8
+ * action routes under /api/ai-prison/watchdog/*.
9
+ *
10
+ * Enforcement is on by default (`enforce: true`): at the pause/freeze waterlines
11
+ * it can roll back additive operations and, at the hot-operation limit, close
12
+ * and quarantine the offending plugin. Set `config.enforce: false` to run in
13
+ * observe mode, where everything is recorded but no plugin is ever touched.
14
+ * Capability-removal backends of the AI Prison prototype remain simulated; this
15
+ * row only governs DSH plugin operations and memory pressure.
10
16
  */
11
17
  export function apply(ctx, config = {}) {
12
18
  const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined