@twinsearth/ai-prison-dsh-plugin 1.7.7 → 1.8.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,31 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.8.0] — 2026-11-21
6
+
7
+ ### Added — external memory supervisor
8
+
9
+ - `lib/supervisor.js`: pure decision logic — thresholds derived from the host
10
+ heap cap (warn 73% / kill 93%), one-shot `request-exit`, `graceMs` before
11
+ `kill`, and seven-way post-mortem attribution.
12
+ - `scripts/aiprison-supervise.mjs`: standalone process that samples the host
13
+ RSS and CPU seconds from the OS, writes a JSONL curve plus
14
+ `supervisor-verdict.json`. Hidden by default: observe-only unless
15
+ `--confirm-kill` is passed.
16
+ - Covers the two blind spots of the in-process watchdog: growth while the JS
17
+ thread is synchronously blocked, and growth before the plugin loads.
18
+
19
+ ### Fixed — real-machine attribution
20
+
21
+ - The CLI now actually calls `classifyExit` when the host disappears; before
22
+ this it only wrote `host-exited`, so attribution existed solely in unit tests.
23
+ - `sync-blocked` no longer requires a sampling gap of three intervals, which
24
+ cannot happen in practice (the next tick after death is one interval away).
25
+ The reachable signature is a peak between the warn and kill lines with the
26
+ CPU pegged (≥ 0.8), which is what a stalled host looks like from outside.
27
+ - Added `exit-requested` (we asked it to quit and it did — not a crash) and
28
+ `supervisor-kill` (a forced kill is attributed to the supervisor).
29
+
5
30
  ## [1.7.7] — 2026-11-19
6
31
 
7
32
  ### Fixed
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,102 @@
1
+ # 外部内存 supervisor(1.8.0 · 隐藏功能)
2
+
3
+ 覆盖进程内 watchdog 的两处结构性盲区:
4
+
5
+ 1. **同步阻塞**:宿主 JS 线程被长任务独占时,watchdog 的采样定时器不跳,内存涨到 OOM 也没人看见。
6
+ 2. **启动期**:插件加载前后、baseline 建立之前的暴涨(历史上 5.4 GB / 4.03 GB 的两次 OOM 都在这个窗口)。
7
+
8
+ 设计约束来自 `AI-PRISON-HARDENING-1.6.0.md` §8,本实现未突破任何一条:
9
+
10
+ - 不替换 `app.asar`、不改安装目录、不打宿主补丁;
11
+ - 唯一形态是独立进程,用操作系统 API 读宿主 RSS;
12
+ - 不写客户端 profile、不需要管理员安装、不依赖插件行;
13
+ - 默认隐藏:面板无按钮、工具列表无入口、无配置项;
14
+ - 默认只观察,强制结束必须显式加 `--confirm-kill`。
15
+
16
+ ## 用法
17
+
18
+ ```bash
19
+ # 只观察:每分钟建一条曲线,写 verdict,不动进程
20
+ node scripts/aiprison-supervise.mjs --pid <host-pid> --data-dir <dir>
21
+
22
+ # 采样间隔 500ms
23
+ node scripts/aiprison-supervise.mjs --pid <host-pid> --interval 500
24
+
25
+ # 6GB 宿主,并在越过 kill 线后真的动手
26
+ node scripts/aiprison-supervise.mjs --pid <host-pid> --cap-mb 6144 --confirm-kill
27
+
28
+ # 只取一个样本(排查用)
29
+ node scripts/aiprison-supervise.mjs --pid <host-pid> --once
30
+ ```
31
+
32
+ 产出:
33
+
34
+ | 文件 | 内容 |
35
+ |---|---|
36
+ | `supervisor-<pid>-<ts>.jsonl` | 每个样本一行:`t / rssMB / rate / cpuRatio / action` |
37
+ | `supervisor-verdict.json` | 当前判定、阈值、峰值、CPU 峰值、`gapMs`、一行摘要 |
38
+
39
+ `cpuRatio` 是本周期内目标进程消耗的 CPU 秒数 ÷ 墙钟秒数(1.0 = 占满一个核),
40
+ 与 RSS 同一次 `Get-Process` 查询取回,不增加采样开销。
41
+
42
+ ## 判定规则
43
+
44
+ 阈值按宿主 heap cap 等比换算,与进程内水位线同源:
45
+
46
+ | 档位 | 4 GB 宿主 | 6 GB 宿主 |
47
+ |---|---|---|
48
+ | warn(73%) | 2990 MB | 4485 MB |
49
+ | kill(93%) | 3809 MB | 5714 MB |
50
+
51
+ - 越过 warn:只记录 + `warn` 判定,不动作;
52
+ - 越过 kill **连续 3 次**(默认 1s 间隔,即约 3s):发一次 `request-exit`,宽限 `graceMs`(默认 5s)后仍未退出 → `kill`;
53
+ - 增长速度 **≥ 150 MB/s 连续 2 次**:不等绝对阈值,直接 `request-exit`(这就是启动期和同步阻塞场景的兜底);
54
+ - `request-exit` 只发一次,不会刷屏。
55
+
56
+ ## 事后归因
57
+
58
+ 宿主死掉后,曲线是唯一证据。`classifyExit` 由 CLI 在"读不到进程"时真正调用(此前只在单测里存在)。判据全部基于外部可观测证据:
59
+
60
+ | 值 | 判据 |
61
+ |---|---|
62
+ | `clean-exit` | 调用方明确给了退出码 0 |
63
+ | `startup-died-before-sampling` | 一个样本都没采到:启动期崩溃 |
64
+ | `sync-blocked` | ①采样间隔 ≥ 3 个周期且峰值过 warn(采样器自身被饿死,罕见);或 ②**峰值在 warn 与 kill 之间、且 CPU 占用连续 ≥ 0.8** —— 内存没有继续撞向 kill 线,是线程卡住烧 CPU |
65
+ | `heap-oom` | 峰值过 warn(含越过 kill 线的情况):栈真的往上涨 |
66
+ | `exit-requested` | 加了 `--confirm-kill` 且已发出退出请求,进程随后退出:因我们的动作而死,不报成崩溃 |
67
+ | `supervisor-kill` | 宽限期后仍存活、由 supervisor 强杀(该路径直接写 verdict,不参与推断) |
68
+ | `exit-1` | 退出码 1 的非内存类失败 |
69
+ | `abnormal-exit` | 其余异常(外部无法拿到退出码时也落在这里) |
70
+
71
+ > 为什么不用"采样间隔 ≥ 3 个周期"当主判据:进程一消失,下一个 tick 就会发现并结束采样,`gapMs` 只可能约等于一个间隔。本机实测 493–539ms(间隔 500ms),永远达不到 1500ms,该分支在真实退出路径上不可达。
72
+
73
+ ## 真机验收(Windows,2026-11-21)
74
+
75
+ 受控替身是一个独立 node 进程(不接触 DSH 客户端),行为固定:延迟 N 秒 → 分配并逐页触碰目标内存 → 同步自旋 2 秒(事件循环完全占住)→ 以退出码 3 结束。supervisor 用 `--cap-mb 512`(warn 374 / kill 476)、500ms 间隔。
76
+
77
+ | 用例 | 替身行为 | 采样结果 | 归因 |
78
+ |---|---|---|---|
79
+ | A 同步阻塞 | 420 MB,峰值 456 MB(warn 与 kill 之间),CPU 0.71→0.98 | 8 样本,500ms 节奏不断 | **`sync-blocked`** |
80
+ | B 越过 kill 线 | 620 MB,峰值 656 MB,CPU 0.92 | 3 次连击 → `request-exit`(仅观察) | **`heap-oom`** |
81
+ | C 请求后退出 | 620 MB,`--confirm-kill` | `request-exit` 后进程立即消失 | **`exit-requested`** |
82
+
83
+ A 的价值在于:**宿主线程被完全卡住的 2 秒里,外部 supervisor 的采样一次都没停**,这正是进程内 watchdog 做不到的那一段。B/C 证明 CPU 证据不会把真涨内存误判成阻塞,也不会把"我们请它退出"包装成崩溃。
84
+
85
+ 证据目录:`E:\DB\AiPrison\evidence\ai-prison-1.8.0-supervisor-real-20261121\`(`case-A-sync-blocked` / `case-B-heap-oom` / `case-C-exit-requested`,各含 `supervisor.out.txt`、`supervisor-verdict.json`、曲线、替身日志)。
86
+
87
+ ## 门禁
88
+
89
+ - `test/supervisor.test.mjs`:**12 个用例**,覆盖阈值换算、warn/kill 升级、速率触发、平线不误报、归因七分支(含 CPU 饱和判据、强杀、请求后退出);
90
+ - 全量:**157/157** tests pass;
91
+ - `release-check`:**11/11**。
92
+
93
+ ## 已知边界
94
+
95
+ - 只做 Windows(`Get-Process` / `taskkill`);macOS/Linux 需要换采样与终止实现,尚未做。
96
+ - 采样本身有成本:每次 `powershell -Command` 约 100–200ms,1s 间隔对宿主影响可忽略,500ms 以下不建议。
97
+ - 外部进程拿不到宿主的退出码,因此非内存类死亡只能落在 `abnormal-exit`;`clean-exit` 仅当调用方明确传入 0 时才成立。
98
+ - `sync-blocked` 的 CPU 判据有一个残余误判面:**峰值恰在 warn 与 kill 之间、又因 GC 抖动把 CPU 打满的真实 OOM** 会被归成阻塞。两类的处置动作相同(都是 `request-exit`),归因文案才有差别,暂不为它引入更重的信号(如句柄/ETW)。
99
+ - 不做自动重启、不做外部分级(那是 supervisor 之上的编排层,另案)。
100
+ - 随 1.8.0 发布:CLI 随 npm 包一起分发(`scripts/aiprison-supervise.mjs`),但不会自动运行,也没有面板入口;需要操作者按上面的用法手动启动。
101
+
102
+
@@ -111,6 +111,57 @@ to ~1.5 MB, but it requires publishing seven packages, keeping their versions in
111
111
  lockstep, and reworking the release/2FA flow. The all-platform npm package stays
112
112
  the default until that is explicitly approved.
113
113
 
114
+ ## 6. npm and GitHub must ship the same bundled CLI
115
+
116
+ 1.7.7 was released from two different build paths and nobody noticed, because
117
+ the gate only checked that `aiprison version` exited 0:
118
+
119
+ | Channel | bundled CLI | commit | built |
120
+ |---|---|---|---|
121
+ | GitHub Release tarball / platform packs | `aiprison 1.0.0` | `fdbbef7` | 2026-11-19T16:12:46Z |
122
+ | npm `@twinsearth/ai-prison-dsh-plugin@1.7.7` | `aiprison 1.0.9` | `4275624` | 2026-11-17T09:58:13Z |
123
+
124
+ The two tarballs share 42 of 48 files byte-for-byte; all six binaries differ
125
+ (GitHub ones are 16–24% smaller because `build-binaries.mjs` uses `-trimpath`
126
+ and `-ldflags "-s -w"`). Behaviour was verified identical (`levels`, `demo`,
127
+ `drill` produce byte-identical output), so this is a metadata/packaging defect,
128
+ not a content one — but a user reporting a bug would quote the wrong version.
129
+
130
+ **What now prevents it**
131
+
132
+ 1. The release workflow resolves the version from `cmd/aiprison/main.go` in a
133
+ dedicated step and passes it as `AIPRISON_VERSION` to the build, instead of
134
+ letting the script guess.
135
+ 2. `scripts/build-binaries.mjs` **throws** when no version can be resolved; the
136
+ silent `'1.0.0'` fallback is gone.
137
+ 3. `scripts/release-check.mjs` gained the gate *“the bundled CLI carries the
138
+ declared version, commit and build time”*: the reported semver must equal the
139
+ version declared in `cmd/aiprison/main.go`, and `commit`/`built` must not be
140
+ `unknown`. A build stamped `1.0.0` now fails the gate before packing.
141
+ 4. `package.json` has a `prepublishOnly` hook that re-runs
142
+ `scripts/release-check.mjs`, so `npm publish` refuses to ship a tarball whose
143
+ bundled CLI disagrees with `cmd/aiprison/main.go` or lacks a commit/build
144
+ stamp. (It stays fast — no Go rebuild — and is a no-op gate when publishing a
145
+ tarball that has no Go source beside it.)
146
+
147
+ **Recommended publish path**
148
+
149
+ Publish the tarball the workflow already built, rather than repacking locally:
150
+
151
+ ```bash
152
+ gh run download <run-id> --repo TwinsEarth/Ai-PRISON --name dsh-plugin-assets
153
+ npm publish ./twinsearth-ai-prison-dsh-plugin-<version>.tgz --access public
154
+ ```
155
+
156
+ That keeps npm, the GitHub Release assets and `SHA256SUMS` on one byte-identical
157
+ build. The `prepublishOnly` hook remains the safety net for the manual path.
158
+
159
+ **Known limitation after this change:** the npm tarball and the GitHub tarball
160
+ can still differ at the byte level, because `npm pack` is run separately in each
161
+ place; only the *bundled binaries and file contents* are now pinned to be equal.
162
+ If byte identity across channels is required, publish only the CI artifact.
163
+
164
+
114
165
  ## 5. SignPath OSS signing (CI wired)
115
166
 
116
167
  SignPath.io signs open-source Windows binaries for free. The release workflow
@@ -0,0 +1,169 @@
1
+ /**
2
+ * External memory supervisor — pure decision logic (1.8.0).
3
+ *
4
+ * Covers the two blind spots the in-process watchdog cannot see:
5
+ * 1. growth while the host JS thread is synchronously blocked (no timer ticks), and
6
+ * 2. growth before the plugin is loaded (startup OOM).
7
+ *
8
+ * A separate OS process samples the host RSS from outside and decides when to
9
+ * warn, request a graceful exit, or force a kill. This module holds no timers,
10
+ * opens no files, and never touches the client installation, so it is testable
11
+ * in isolation. Constraints (see docs/AI-PRISON-HARDENING-1.6.0.md §8):
12
+ * - never replace app.asar / modify the install dir;
13
+ * - independent process, OS-level RSS reads only;
14
+ * - writes nothing to the client profile;
15
+ * - hidden by default: no panel control, no tool, no config;
16
+ * - observe-first: forced termination requires an explicit flag.
17
+ */
18
+ export const SUPERVISOR_DEFAULTS = {
19
+ intervalMs: 1000,
20
+ strikeLimit: 3,
21
+ warnRatio: 0.73,
22
+ killRatio: 0.93,
23
+ rateMBps: 150,
24
+ rateStrikes: 2,
25
+ graceMs: 5000,
26
+ staleSamples: 3,
27
+ cpuSaturation: 0.8,
28
+ }
29
+
30
+ /** Absolute thresholds derived from the host heap cap (same ratios as the in-process waterline). */
31
+ export function supervisorThresholds(heapLimitBytes, overrides = {}) {
32
+ const limitBytes = Number(heapLimitBytes)
33
+ const cap = Number.isFinite(limitBytes) && limitBytes > 0 ? limitBytes : 4 * 1024 * 1024 * 1024
34
+ const config = { ...SUPERVISOR_DEFAULTS, ...overrides }
35
+ const capMB = cap / (1024 * 1024)
36
+ return {
37
+ ...config,
38
+ heapLimitMB: Math.round(capMB),
39
+ warnMB: Math.round(capMB * config.warnRatio),
40
+ killMB: Math.round(capMB * config.killRatio),
41
+ }
42
+ }
43
+
44
+ export function createSupervisorState(thresholds) {
45
+ return {
46
+ thresholds,
47
+ strikes: 0,
48
+ rateStrikes: 0,
49
+ samples: 0,
50
+ peakMB: 0,
51
+ lastAt: null,
52
+ lastRssMB: null,
53
+ lastCpuSeconds: null,
54
+ lastCpuRatio: 0,
55
+ peakCpuRatio: 0,
56
+ requestedAt: null,
57
+ verdict: 'ok',
58
+ reason: null,
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Feed one RSS sample. Returns the decision for this tick.
64
+ * action: ok | warn | request-exit | kill
65
+ * `request-exit` is emitted once; a tick after graceMs turns it into `kill`.
66
+ */
67
+ export function evaluateSample(state, sample, now = Date.now()) {
68
+ const t = state.thresholds
69
+ const rssMB = Math.max(0, Math.round((Number(sample.rssBytes) || 0) / (1024 * 1024)))
70
+ const gapMs = state.lastAt === null ? 0 : now - state.lastAt
71
+ const rate = state.lastAt !== null && gapMs > 0 ? Math.round(((rssMB - state.lastRssMB) / (gapMs / 1000)) * 10) / 10 : 0
72
+
73
+ // CPU seconds come from the OS counter, so they keep advancing while the host's
74
+ // JS thread is blocked. A pegged ratio next to a plateau is the only external
75
+ // evidence that the process is spinning rather than filling its heap.
76
+ const cpuSeconds = Number(sample.cpuSeconds)
77
+ if (Number.isFinite(cpuSeconds) && state.lastCpuSeconds !== null && gapMs > 0) {
78
+ const ratio = (cpuSeconds - state.lastCpuSeconds) / (gapMs / 1000)
79
+ state.lastCpuRatio = Math.max(0, Math.min(8, Math.round(ratio * 100) / 100))
80
+ state.peakCpuRatio = Math.max(state.peakCpuRatio, state.lastCpuRatio)
81
+ }
82
+ if (Number.isFinite(cpuSeconds)) state.lastCpuSeconds = cpuSeconds
83
+
84
+ state.samples += 1
85
+ state.peakMB = Math.max(state.peakMB, rssMB)
86
+ state.lastAt = now
87
+ state.lastRssMB = rssMB
88
+
89
+ let action = 'ok'
90
+ let reason = null
91
+
92
+ if (rssMB >= t.warnMB) {
93
+ state.strikes = rssMB >= t.killMB ? state.strikes + 1 : 0
94
+ action = 'warn'
95
+ reason =
96
+ rssMB >= t.killMB
97
+ ? `rss ${rssMB} MB >= kill line ${t.killMB} MB (${state.strikes}/${t.strikeLimit})`
98
+ : `rss ${rssMB} MB >= warn line ${t.warnMB} MB`
99
+ } else {
100
+ state.strikes = 0
101
+ }
102
+
103
+ if (rate >= t.rateMBps) state.rateStrikes += 1
104
+ else if (rate <= 0) state.rateStrikes = 0
105
+
106
+ const rising = rate >= t.rateMBps && state.rateStrikes >= t.rateStrikes
107
+ const atKillLine = rssMB >= t.killMB && state.strikes >= t.strikeLimit
108
+
109
+ if (atKillLine || rising) {
110
+ action = 'request-exit'
111
+ reason = atKillLine ? reason : `growth ${rate} MB/s >= ${t.rateMBps} MB/s on ${state.rateStrikes} samples`
112
+ }
113
+ if (state.requestedAt !== null && action === 'request-exit') action = 'ok'
114
+
115
+ if (state.requestedAt !== null && now - state.requestedAt >= t.graceMs) {
116
+ action = 'kill'
117
+ reason = `still running ${Math.round((now - state.requestedAt) / 1000)}s after the graceful request`
118
+ }
119
+ if (action === 'request-exit') state.requestedAt = now
120
+ if (action === 'kill') state.verdict = 'kill'
121
+ else if (action === 'request-exit') state.verdict = 'request-exit'
122
+ else if (action === 'warn') state.verdict = 'warn'
123
+ state.reason = reason || state.reason
124
+ return { action, rssMB, rate, strikes: state.strikes, reason }
125
+ }
126
+
127
+ /**
128
+ * Post-mortem classification from the recorded curve plus the exit status.
129
+ * The curve is the only evidence left once the host process is gone.
130
+ */
131
+ export function classifyExit(state, { exitCode = null, signal = null, gapMs = null, samples = null, killed = false, requestedBySupervisor = false } = {}) {
132
+ const seen = Number.isFinite(samples) ? samples : state.samples
133
+ const peakMB = state.peakMB
134
+ const t = state.thresholds
135
+ if (killed) return 'supervisor-kill'
136
+ const abnormal = exitCode !== 0 || signal !== null
137
+ if (!abnormal) return 'clean-exit'
138
+ if (seen === 0) return 'startup-died-before-sampling'
139
+ // We asked it to quit and it did: the memory reading explains why we asked,
140
+ // not why it died, so do not dress this up as a crash. Observe-only runs
141
+ // never set this, because there we only logged the request.
142
+ if (requestedBySupervisor) return 'exit-requested'
143
+ // Sampling gaps only grow when the sampler itself was starved; a host that
144
+ // simply vanished is caught on the very next tick, so this branch rarely fires.
145
+ if (Number.isFinite(gapMs) && gapMs >= t.intervalMs * t.staleSamples && peakMB >= t.warnMB) return 'sync-blocked'
146
+ // The reachable signature: high memory that never reached the kill line,
147
+ // with the CPU pegged right up to death. A heap that was truly exhausted
148
+ // climbs past the kill line instead.
149
+ const cpuPegged = state.peakCpuRatio >= (t.cpuSaturation ?? 0.8)
150
+ if (peakMB >= t.warnMB && peakMB < t.killMB && cpuPegged) return 'sync-blocked'
151
+ if (peakMB >= t.warnMB) return 'heap-oom'
152
+ if (exitCode === 1) return 'exit-1'
153
+ return 'abnormal-exit'
154
+ }
155
+
156
+ /** One-line human summary for the incident log. */
157
+ export function describeVerdict(state) {
158
+ const t = state.thresholds
159
+ const parts = [
160
+ `verdict=${state.verdict}`,
161
+ `peak=${state.peakMB}MB`,
162
+ `samples=${state.samples}`,
163
+ `cap=${t.heapLimitMB}MB`,
164
+ `warn=${t.warnMB}MB`,
165
+ `kill=${t.killMB}MB`,
166
+ ]
167
+ if (state.reason) parts.push(`reason=${state.reason}`)
168
+ return parts.join(' ')
169
+ }
@@ -57,15 +57,20 @@ export function createBudget({ watchdogState, refs, profileDir, journalDir, exem
57
57
  }
58
58
  const thresholds = watchdogState.thresholds
59
59
  const mb = result.moduleLoadMB
60
- if (thresholds && mb >= Math.round(thresholds.singleBlock / (1024 * 1024))) {
61
- appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > 500 MB,禁止该插件' })
60
+ // Thresholds are clamped to the real heap cap, so a small-heap host has a
61
+ // lower absolute limit than the documented 300/500 MB. Report the value
62
+ // that actually applied instead of the documentation default.
63
+ const blockMB = thresholds ? Math.round(thresholds.singleBlock / (1024 * 1024)) : 500
64
+ const warnMB = thresholds ? Math.round(thresholds.singleWarn / (1024 * 1024)) : 300
65
+ if (thresholds && mb >= blockMB) {
66
+ appendIncident({ kind: 'plugin-budget', target: name, level: 'block', detail: '启动实测 ' + mb + ' MB > ' + blockMB + ' MB,禁止该插件' })
62
67
  if (watchdogState.enforce) {
63
- watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > 500 MB', remediation: remediationFor('budget') })
68
+ watchdogState.quarantine.set(name, { reason: 'budget', level: 'L1', at: new Date().toISOString(), release: 'manual', evidence: mb + ' MB > ' + blockMB + ' MB', remediation: remediationFor('budget') })
64
69
  void enforcement.disableTarget(name, 'budget-over-500MB')
65
70
  enforcement.writePendingBoot({ level: 'L1', reason: 'budget', disable: [name], keep: [] })
66
71
  }
67
- } else if (thresholds && mb >= Math.round(thresholds.singleWarn / (1024 * 1024))) {
68
- appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > 300 MB,仅提醒' })
72
+ } else if (thresholds && mb >= warnMB) {
73
+ appendIncident({ kind: 'plugin-budget', target: name, level: 'warn', detail: '启动实测 ' + mb + ' MB > ' + warnMB + ' MB,仅提醒' })
69
74
  }
70
75
  persist(true)
71
76
  return { ok: true }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.7.7",
3
+ "version": "1.8.0",
4
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",
@@ -53,12 +53,14 @@
53
53
  "README.md",
54
54
  "CHANGELOG.md",
55
55
  "LICENSE",
56
- "bin"
56
+ "bin",
57
+ "scripts/aiprison-supervise.mjs"
57
58
  ],
58
59
  "scripts": {
59
60
  "test": "node --test test/*.test.mjs",
60
61
  "coverage": "node --test --experimental-test-coverage --test-coverage-lines=70 --test-coverage-branches=65 --test-coverage-functions=75 test/*.test.mjs",
61
- "check": "node scripts/release-check.mjs"
62
+ "check": "node scripts/release-check.mjs",
63
+ "prepublishOnly": "node scripts/release-check.mjs"
62
64
  },
63
65
  "dsh": {
64
66
  "bundle": {
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * aiprison-supervise — external memory supervisor CLI (1.8.0, hidden feature).
4
+ *
5
+ * Runs as its own process, outside the DSH host, and samples that host's RSS at
6
+ * a fixed interval. It never loads into the client, never writes the profile,
7
+ * and never touches the installation. By default it only observes: it records
8
+ * the curve and a verdict. Terminating the host needs `--confirm-kill`.
9
+ *
10
+ * node bin/aiprison-supervise.mjs --pid 1234
11
+ * node bin/aiprison-supervise.mjs --pid 1234 --cap-mb 6144 --confirm-kill
12
+ * node bin/aiprison-supervise.mjs --pid 1234 --interval 500 --dry-run --once
13
+ */
14
+ import fs from 'node:fs'
15
+ import path from 'node:path'
16
+ import { spawnSync } from 'node:child_process'
17
+ import { createSupervisorState, evaluateSample, supervisorThresholds, describeVerdict, classifyExit } from '../lib/supervisor.js'
18
+
19
+ const args = process.argv.slice(2)
20
+ const flag = (name) => args.includes(`--${name}`)
21
+ const value = (name, fallback) => {
22
+ const i = args.indexOf(`--${name}`)
23
+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : fallback
24
+ }
25
+
26
+ const pid = Number(value('pid', 0))
27
+ if (!Number.isInteger(pid) || pid <= 0) {
28
+ console.error('usage: aiprison-supervise --pid <host-pid> [--cap-mb N] [--interval MS] [--data-dir DIR] [--confirm-kill] [--once]')
29
+ process.exit(2)
30
+ }
31
+
32
+ const interval = Math.max(200, Number(value('interval', 1000)))
33
+ const capMB = Number(value('cap-mb', 4096))
34
+ const dataDir = path.resolve(value('data-dir', path.join(process.cwd(), '.ai-prison-supervisor')))
35
+ const confirmKill = flag('confirm-kill')
36
+ const once = flag('once')
37
+
38
+ const thresholds = supervisorThresholds(capMB * 1024 * 1024, { intervalMs: interval })
39
+ const state = createSupervisorState(thresholds)
40
+
41
+ fs.mkdirSync(dataDir, { recursive: true })
42
+ const curveFile = path.join(dataDir, `supervisor-${pid}-${Date.now()}.jsonl`)
43
+ const verdictFile = path.join(dataDir, 'supervisor-verdict.json')
44
+
45
+ function readSample(pidToRead) {
46
+ // One process query returns both memory and CPU seconds, so the extra
47
+ // evidence costs no additional powershell spawn per tick.
48
+ const r = spawnSync(
49
+ 'powershell.exe',
50
+ ['-NoProfile', '-Command', `$p=Get-Process -Id ${pidToRead} -ErrorAction SilentlyContinue; if($p){"$([int64]$p.WorkingSet64) $([double]$p.CPU)"}else{"-1"}`],
51
+ { windowsHide: true, encoding: 'utf8' },
52
+ )
53
+ const parts = String(r.stdout || '').trim().split(/\s+/)
54
+ const rss = Number(parts[0])
55
+ if (!Number.isFinite(rss) || rss <= 0) return null
56
+ const cpu = Number(parts[1])
57
+ return { rssBytes: rss, cpuSeconds: Number.isFinite(cpu) ? cpu : undefined }
58
+ }
59
+
60
+ function requestExit(pidToStop) {
61
+ // taskkill without /F asks for a normal termination; /F is the forced fallback.
62
+ spawnSync('taskkill.exe', ['/PID', String(pidToStop)], { windowsHide: true })
63
+ }
64
+
65
+ function forceKill(pidToStop) {
66
+ spawnSync('taskkill.exe', ['/PID', String(pidToStop), '/F'], { windowsHide: true })
67
+ }
68
+
69
+ function writeVerdict(extra = {}) {
70
+ const payload = { at: new Date().toISOString(), pid, thresholds: thresholds, state: { ...state, thresholds: undefined }, summary: describeVerdict(state), ...extra }
71
+ try {
72
+ fs.writeFileSync(verdictFile, JSON.stringify(payload, null, 2))
73
+ } catch {
74
+ // verdict is diagnostic only
75
+ }
76
+ }
77
+
78
+ let stopping = false
79
+ let timer = null
80
+
81
+ function tick() {
82
+ if (stopping) return
83
+ const sample = readSample(pid)
84
+ if (!sample) {
85
+ stopping = true
86
+ if (timer) clearInterval(timer)
87
+ const gapMs = state.lastAt === null ? null : Date.now() - state.lastAt
88
+ const verdict = state.lastAt === null
89
+ ? 'host-gone-before-sampling'
90
+ : classifyExit(state, { gapMs, samples: state.samples, requestedBySupervisor: confirmKill && state.requestedAt !== null })
91
+ writeVerdict({ verdict, gapMs, cpuPeakRatio: state.peakCpuRatio, curveFile: path.basename(curveFile) })
92
+ console.log(`[supervise] ${verdict} ${describeVerdict(state)} gap=${gapMs ?? 'n/a'}ms cpuPeak=${state.peakCpuRatio}`)
93
+ process.exit(0)
94
+ }
95
+ const decision = evaluateSample(state, sample, Date.now())
96
+ try {
97
+ fs.appendFileSync(curveFile, `${JSON.stringify({ t: new Date().toISOString(), rssMB: decision.rssMB, rate: decision.rate, cpuRatio: state.lastCpuRatio, action: decision.action })}\n`)
98
+ } catch {
99
+ // curve file is diagnostic only
100
+ }
101
+ if (decision.action === 'warn') console.log(`[supervise] warn ${decision.reason}`)
102
+ if (decision.action === 'request-exit') {
103
+ console.log(`[supervise] request-exit ${decision.reason}${confirmKill ? '' : ' (observe-only, pass --confirm-kill to act)'}`)
104
+ writeVerdict({ curveFile: path.basename(curveFile) })
105
+ if (confirmKill) {
106
+ requestExit(pid)
107
+ const fallback = setTimeout(() => {
108
+ const alive = readSample(pid)
109
+ if (alive) {
110
+ console.log('[supervise] graceful request did not take effect, forcing kill')
111
+ forceKill(pid)
112
+ }
113
+ }, thresholds.graceMs)
114
+ if (typeof fallback.unref === 'function') fallback.unref()
115
+ }
116
+ }
117
+ if (decision.action === 'kill') {
118
+ console.log(`[supervise] killing ${pid} ${decision.reason}`)
119
+ forceKill(pid)
120
+ writeVerdict({ verdict: 'supervisor-kill', cpuPeakRatio: state.peakCpuRatio, curveFile: path.basename(curveFile) })
121
+ stopping = true
122
+ if (timer) clearInterval(timer)
123
+ process.exit(0)
124
+ }
125
+ if (once) {
126
+ console.log(`[supervise] ${describeVerdict(state)}`)
127
+ writeVerdict({ curveFile: path.basename(curveFile) })
128
+ process.exit(0)
129
+ }
130
+ }
131
+
132
+ console.log(`[supervise] watching pid ${pid} cap=${thresholds.heapLimitMB}MB warn=${thresholds.warnMB}MB kill=${thresholds.killMB}MB interval=${interval}ms`)
133
+ tick()
134
+ if (!once) {
135
+ timer = setInterval(tick, interval)
136
+ process.on('SIGINT', () => {
137
+ stopping = true
138
+ if (timer) clearInterval(timer)
139
+ writeVerdict({ curveFile: path.basename(curveFile) })
140
+ process.exit(0)
141
+ })
142
+ }