@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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,52 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.7.0] — 2026-11-19
6
+
7
+ ### Changed — structural cleanup and safer defaults
8
+
9
+ - **watchdog-runtime split** into `watchdog-core / persistence / sampler / enforcement / crash / budget / api / snapshot`;
10
+ the orchestrator dropped from 1,072 to 332 lines. Public API unchanged
11
+ (`createWatchdog` return shape and the `watchdogSnapshot` re-export).
12
+ - **RSS child scan is opt-in**: only `rssScan: true` starts the 60 s scan; the
13
+ subprocess-service path is exported as `scanViaService()` and covered by tests.
14
+ - **i18n single source**: runtime strings live only in the `client.js` inline
15
+ dictionaries (77 keys per language); `locale/*.json` keeps market metadata only.
16
+ - **Docs/tool surface**: README documents all 8 `ai_prison_*` tools, patch/loader
17
+ comments describe enforce-first defaults, and a docs-consistency test guards it.
18
+ - **Enforcement visibility**: `snapshot.pendingBoot` reports
19
+ `consumer: none` / `appliesNextBoot: false`; the panel warns that only the
20
+ current run’s in-process isolation applies. No external consumer ships.
21
+ - **Tamper policy** defaults to `observe` (library and runtime, unknown values
22
+ fail safe); only `restore` rewrites profile files.
23
+
24
+ ### Fixed
25
+
26
+ - HTTP `data_dir` is restricted to the configured ledger or `<cwd>/.ai-prison`
27
+ (403 `data-dir-not-allowed` before any CLI call); `POST /run` is throttled to
28
+ one execution per second (429 + `retryAfterMs`).
29
+ - `heap6g` requests are written to the profile state directory
30
+ (`heap6g-request.json`) instead of the old hardcoded `E:/ToFuture` path, and
31
+ the response marks `consumer: external-launcher-required`.
32
+ - `prunePluginState()` removes operations/budgets/ranking/RSS for uninstalled or
33
+ version-changed bundles, so Top5 and budgets no longer go stale.
34
+ - `state.json` is replaced atomically; `incidents.jsonl` rotates to the last
35
+ 2,000 lines atomically instead of 500.
36
+ - Startup-watch thresholds are derived from the heap cap (4 GB → 2,007 MB,
37
+ 6 GB → 3,011 MB) instead of two hard-coded constants.
38
+ - Removed the tracked `.tmp-watchdog-*` scratch directories; added
39
+ `dsh-plugin/.gitignore`.
40
+
41
+ ### Tests and CI
42
+
43
+ - Test suite: 89 → **120 tests** across 27 files, including watchdog failure
44
+ modes (startup OOM, exit-1, L3 escalation, observe mode), persistence,
45
+ pruning, API throttling and the subprocess-service contract.
46
+ - `npm run coverage` gates lines 70 / branches 65 / functions 75 (currently
47
+ 74.35 / 70.85 / 79.26); the release workflow runs it on ubuntu and adds a
48
+ `windows-latest` job for the Windows-only code paths.
49
+
50
+ ## [1.6.1] — 2026-11-19
5
51
  ## [1.6.1] — 2026-11-19
6
52
 
7
53
  ### Fixed
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  AI Prison for DSH — the defensive agent-governance prototype of
4
4
  [Ai-PRISON](https://github.com/TwinsEarth/Ai-PRISON), exposed as a DeepSeek
5
- Harness bundle: six `ai_prison_*` tools plus a sidebar panel that renders the
5
+ Harness bundle: eight `ai_prison_*` tools plus a sidebar panel that renders the
6
6
  L0–L5 grading matrix and the durable ledger's audit-chain state.
7
7
 
8
8
  Everything here is **defensive**: detection, graduated capability deprivation,
@@ -18,7 +18,7 @@ MicroVM isolation are **simulated backends**, not shipped controls.
18
18
  absolute package directory to the plugin manager).
19
19
 
20
20
  After enabling the bundle, a shield entry appears in the sidebar. Open it for the
21
- panel; the six tools become visible to the Agent on the next session step.
21
+ panel; the eight tools become visible to the Agent on the next session step.
22
22
 
23
23
  ## Tools
24
24
 
@@ -26,6 +26,7 @@ panel; the six tools become visible to the Agent on the next session step.
26
26
  |---|---|---|
27
27
  | `ai_prison_levels` | read-only | Print the L0–L5 matrix (codes, names, duration class, deprived capabilities). |
28
28
  | `ai_prison_status` | read-only | CLI path/source/version, the matrix, and the ledger's integrity + record count. Same data as the panel. |
29
+ | `ai_prison_watchdog_status` | read-only | Watchdog snapshot: memory waterline/thresholds, hot-operation Top5, quarantined plugins, crash plans, budgets, incidents. Same data as the Enforcement cards. |
29
30
  | `ai_prison_demo` | writes ledger | End-to-end governance demo: detect → seven-stage adjudication → layered enforcement → audit → appeal/rehabilitation → recovery. |
30
31
  | `ai_prison_drill` | writes ledger | v1.0.0 recovery drill over the reversibility matrix with per-assertion PASS/FAIL and an overall verdict. |
31
32
  | `ai_prison_inspect` | read-only | Replay the ledger: hash chain, agents, sentences, revocations, receipts, sealed snapshots. |
@@ -43,17 +44,35 @@ deleted and the action runs, because the CLI replays an existing ledger and
43
44
  refuses to re-seed credentials that earlier runs already revoked (`demo` twice,
44
45
  or a second `drill`, would otherwise fail).
45
46
 
46
- ## Memory watchdog (P0, observe only)
47
+ ## Memory watchdog and plugin enforcement
47
48
 
48
49
  A second loader row (`ai-prison-watchdog`) samples the host heap every 5 seconds,
49
- derives the design thresholds from the real heap limit (300/500 MB per plugin,
50
- 3.0/3.9/5.0 GB total, 4/5 GB operation gates), accounts plugin operations
50
+ derives the design thresholds from the real heap limit (300/500 MB per plugin;
51
+ 3.0/3.9/5.0 GB and operation gates 4/5 GB on a 6 GB host, mapped down to
52
+ 2.99/3.60/3.81 and 2.73/3.41 GB on a 4 GB host), accounts plugin operations
51
53
  (install/remove = 1, enable = 1, disable = 0.5), estimates each plugin's heap
52
- delta around those operations and reads new `crash-*-host.log` files at startup.
53
- It exposes `GET /api/ai-prison/watchdog/status` and the read-only
54
- `ai_prison_watchdog_status` tool; the panel adds **Memory watchdog** and
55
- **Plugin prison** cards. **Observe mode never enables or disables a plugin** —
56
- enforcement (P1–P3) is not implemented and needs explicit confirmation.
54
+ delta around those operations, reads new `crash-*-host.log` files at startup and
55
+ records a 500 ms startup curve into `.ai-prison-watchdog/run-*.jsonl`.
56
+ It exposes `GET /api/ai-prison/watchdog/status`, `POST /api/ai-prison/watchdog/action`
57
+ and the read-only `ai_prison_watchdog_status` tool; the panel adds **Memory
58
+ watchdog**, **Plugin prison** and **Enforcement** cards.
59
+
60
+ **Enforcement is on by default.** Exceeding the hot-operation limit (more than
61
+ five additive operations for one plugin in a run) closes and quarantines that
62
+ plugin; at the pause/freeze waterlines additive operations are blocked and
63
+ already-started ones are rolled back; agent-side `plugin_manager` calls are
64
+ rejected too. Set `config.enforce: false` on the watchdog row for observe-only
65
+ mode, which records everything but never touches a plugin.
66
+
67
+ Things that are **off by default** because they spawn processes or rewrite
68
+ files: child-process RSS scanning (`rssScan: true`), automatic budget probes
69
+ (`probeAuto: true`), tray notifications (`notify: true`); profile tamper policy
70
+ defaults to `observe` (`tamperPolicy: restore` opts into rewriting files).
71
+
72
+ Enforcement plans are also written to `.ai-prison-watchdog/pending-boot.json`
73
+ for a launcher/guard to apply **before the next start**. No such external
74
+ consumer ships with the plugin, so that file alone does not disable anything:
75
+ the in-process close/quarantine is what takes effect in the current run.
57
76
  State lives in `<profile>/.ai-prison-watchdog/`.
58
77
 
59
78
  ## Ledger directory
@@ -75,6 +94,12 @@ config:
75
94
  Resolution order for the CLI: `config.cliPath` → `AIPRISON_BIN` → the bundled
76
95
  build for this platform → `aiprison` on `PATH`.
77
96
 
97
+ The panel's HTTP routes are deliberately narrower than the tools: a `data_dir`
98
+ sent to `GET /api/ai-prison/status` or `POST /api/ai-prison/run` must resolve to
99
+ the configured ledger directory or `<working directory>/.ai-prison`; anything
100
+ else is rejected with `403 data-dir-not-allowed` before the CLI runs. The
101
+ agent-facing tools keep the explicit `data_dir` argument.
102
+
78
103
  ## Bundled CLIs
79
104
 
80
105
  `bin/<platform>-<arch>/aiprison` ships six cross-compiled builds: `windows`,
@@ -82,6 +107,24 @@ build for this platform → `aiprison` on `PATH`.
82
107
  repository with `node dsh-plugin/scripts/build-binaries.mjs` (pure standard
83
108
  library, `CGO_ENABLED=0`, no module downloads) and are not committed to git.
84
109
 
110
+ ### Per-platform packaging (size)
111
+
112
+ The published tarball carries all six CLIs (about 8.8 MB packed). For a
113
+ single-machine deployment you can build a platform-lite tarball that keeps only
114
+ one `bin/<platform>-<arch>/` tree:
115
+
116
+ ```bash
117
+ cd dsh-plugin
118
+ node scripts/pack-platform.mjs --platform windows --arch amd64 --out ../dist
119
+ # prints { target, tarball, sizeMB, fullSizeMB, skippedTargets }
120
+ node scripts/pack-platform.mjs --platform macos --arch arm64 --dry-run
121
+ ```
122
+
123
+ For reference, the all-platform tarball is about 8.8 MB; the windows-amd64
124
+ lite tarball is about 1.6 MB. This script does not change the main package
125
+ layout; the regular `npm pack`/release flow still publishes the all-platform
126
+ tarball.
127
+
85
128
  On a platform without a bundled build, point `cliPath` / `AIPRISON_BIN` at a
86
129
  binary built from `cmd/aiprison`.
87
130
 
@@ -102,6 +145,9 @@ the release check, packs the npm tarball and publishes the GitHub Release assets
102
145
 
103
146
  - Backends are simulations: no real isolation, revocation distribution,
104
147
  hardware binding or capability removal happens.
148
+ - The watchdog is an in-process observer: it cannot sample or act while the host
149
+ event loop is blocked, before its loader row is initialized, or after the host
150
+ exits; it does not replace a process-external memory guard.
105
151
  - The plugin never writes the ledger from status calls; only the two explicit
106
152
  panel buttons and the `demo`, `drill` and `repair-tail` tools mutate it.
107
153
  - A wrong `data_dir` reveals that directory's integrity state only; the plugin
package/client.js CHANGED
@@ -53,6 +53,26 @@ window.__ModuleLoader__.load({
53
53
  'meta.readonly': 'Read-only view: the panel never writes by itself; only the buttons above do.',
54
54
  'watchdog.title': 'Memory watchdog',
55
55
  'watchdog.mode': 'Observe mode: records only, never closes plugins',
56
+ 'watchdog.modeEnforce': 'Enforce mode: over-limit operations are rolled back, closed or quarantined',
57
+ 'watchdog.enforceTitle': 'Enforcement',
58
+ 'watchdog.enforceOn': 'enforce',
59
+ 'watchdog.observeOnly': 'observe only',
60
+ 'watchdog.freezeHint': 'Heap is frozen at {level}: plugin operations are blocked except release actions. Close the biggest plugins below or restart DSH.',
61
+ 'watchdog.confirmPause': 'I understand: allow plugin operations for 10 minutes',
62
+ 'watchdog.quarantine': 'Plugin prison',
63
+ 'watchdog.noQuarantine': 'No quarantined plugins.',
64
+ 'watchdog.release': 'Release',
65
+ 'watchdog.topFive': 'Top {n} by estimated heap',
66
+ 'watchdog.close': 'Close now',
67
+ 'watchdog.plans': 'Crash plans',
68
+ 'watchdog.baseline': 'Clean baseline: {at}',
69
+ 'watchdog.tamper': 'Profile watch: {n} critical file(s) · policy {policy} · last check {at}',
70
+ 'watchdog.measure': 'Measure plugin budgets now',
71
+ 'watchdog.measureBlocked': 'Heap is frozen: measuring spawns child processes, so it stays disabled until the heap recovers.',
72
+ 'watchdog.heap6gOff': 'Request 6 GB heap on next launch',
73
+ 'watchdog.heap6gOn': 'Cancel the 6 GB heap request',
74
+ 'watchdog.heap6gPending': 'Written to the watchdog state directory; an external launcher must consume it (none is installed right now).',
75
+ 'watchdog.pendingBoot': 'pending-boot plan ({level}) was written, but no external consumer is installed: only this run\'s in-process isolation applies. Handle the next start manually.',
56
76
  'watchdog.disabled': 'Watchdog row not enabled; heap observation is unavailable.',
57
77
  'watchdog.heap': 'Heap used',
58
78
  'watchdog.limit': 'Heap limit',
@@ -67,8 +87,10 @@ window.__ModuleLoader__.load({
67
87
  'prison.top': 'Top {n} plugins by estimated heap',
68
88
  'prison.ops': 'Hot ops',
69
89
  'prison.estimate': 'Est.',
90
+ 'prison.plugin': 'Plugin',
91
+ 'prison.rss': 'Child RSS',
70
92
  'prison.incidents': 'Recent incidents',
71
- 'prison.empty': 'No quarantined plugins: observe mode never closes one.',
93
+ 'prison.empty': 'No quarantined plugins.',
72
94
  'prison.noestimates': 'No plugin operations observed yet.',
73
95
  'error.title': 'Cannot read the status',
74
96
  'error.hint': 'Check that the bundle is enabled and the aiprison CLI resolves for this platform.',
@@ -111,6 +133,26 @@ window.__ModuleLoader__.load({
111
133
  'meta.readonly': '只读视图:面板不会自行写入账本,只有上方按钮会写入。',
112
134
  'watchdog.title': '内存看护',
113
135
  'watchdog.mode': '观察模式:只记录,不关闭插件',
136
+ 'watchdog.modeEnforce': '执行模式:超限操作会被回滚、关闭或隔离',
137
+ 'watchdog.enforceTitle': '执行状态',
138
+ 'watchdog.enforceOn': '执行中',
139
+ 'watchdog.observeOnly': '仅观察',
140
+ 'watchdog.freezeHint': '堆水位已冻结({level}):除释放类操作外,所有插件操作被禁止。请关闭下方内存最大的插件或重启 DSH。',
141
+ 'watchdog.confirmPause': '我已知晓:允许插件操作 10 分钟',
142
+ 'watchdog.quarantine': '插件监狱',
143
+ 'watchdog.noQuarantine': '没有被隔离的插件。',
144
+ 'watchdog.release': '假释',
145
+ 'watchdog.topFive': '按估算内存排序的前 {n} 个插件',
146
+ 'watchdog.close': '立即关闭',
147
+ 'watchdog.plans': '崩溃降级计划',
148
+ 'watchdog.baseline': '干净基线:{at}',
149
+ 'watchdog.tamper': '配置监控:{n} 个关键文件 · 策略 {policy} · 最近检查 {at}',
150
+ 'watchdog.measure': '立即测量插件预算',
151
+ 'watchdog.measureBlocked': '堆已冻结:测量会启动子进程,恢复前暂停测量。',
152
+ 'watchdog.heap6gOff': '请求下次启动使用 6GB 堆',
153
+ 'watchdog.heap6gOn': '取消 6GB 堆请求',
154
+ 'watchdog.heap6gPending': '已写入 watchdog 状态目录;需要外部启动器消费(当前未安装)。',
155
+ 'watchdog.pendingBoot': '已写入 pending-boot 计划({level}),但当前未安装外部消费器:只有本次运行内的进程内隔离生效,下次启动需人工处理。',
114
156
  'watchdog.disabled': 'watchdog 行未启用,暂时无法观察内存。',
115
157
  'watchdog.heap': '已用堆',
116
158
  'watchdog.limit': '堆上限',
@@ -125,8 +167,10 @@ window.__ModuleLoader__.load({
125
167
  'prison.top': '按估算内存排序的前 {n} 个插件',
126
168
  'prison.ops': '热操作',
127
169
  'prison.estimate': '估算',
170
+ 'prison.plugin': '插件',
171
+ 'prison.rss': '子进程 RSS',
128
172
  'prison.incidents': '最近事件',
129
- 'prison.empty': '没有被隔离的插件:观察模式不会关闭任何插件。',
173
+ 'prison.empty': '没有被隔离的插件。',
130
174
  'prison.noestimates': '还没有观察到插件操作。',
131
175
  'error.title': '无法读取状态',
132
176
  'error.hint': '请确认插件已启用,且本平台能解析到 aiprison CLI。',
@@ -337,7 +381,7 @@ window.__ModuleLoader__.load({
337
381
  'div',
338
382
  { style: C.cardHead },
339
383
  t('watchdog.title'),
340
- h('span', { style: { ...C.chip, marginLeft: 8 } }, t('watchdog.mode')),
384
+ h('span', { style: { ...C.chip, marginLeft: 8 } }, (watchdog.enforce ? t('watchdog.modeEnforce') : t('watchdog.mode'))),
341
385
  h(Pill, { tone: watchdog.waterline === 'ok' ? 'ok' : 'error', text: `${t('watchdog.waterline')}: ${waterlineText(watchdog.waterline)}` }),
342
386
  ),
343
387
  h(
@@ -376,7 +420,7 @@ window.__ModuleLoader__.load({
376
420
  return h(
377
421
  'section',
378
422
  { style: C.card },
379
- h('div', { style: C.cardHead }, t('prison.title'), h('span', { style: { ...C.chip, marginLeft: 8 } }, t('watchdog.mode'))),
423
+ h('div', { style: C.cardHead }, t('prison.title'), h('span', { style: { ...C.chip, marginLeft: 8 } }, (watchdog.enforce ? t('watchdog.modeEnforce') : t('watchdog.mode')))),
380
424
  operations.length === 0
381
425
  ? h('p', { style: { ...C.muted, fontSize: 12, margin: '0 0 6px' } }, t('prison.noestimates'))
382
426
  : h(
@@ -491,6 +535,9 @@ window.__ModuleLoader__.load({
491
535
  ),
492
536
  watchdog.baseline ? h('p', { style: { ...C.muted, fontSize: 11.5, margin: '10px 0 0' } }, t('watchdog.baseline', { at: watchdog.baseline.at })) : null,
493
537
  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,
538
+ watchdog.pendingBoot && watchdog.pendingBoot.exists
539
+ ? h('p', { style: { color: '#b45309', fontSize: 11.5, margin: '6px 0 0' } }, t('watchdog.pendingBoot', { level: watchdog.pendingBoot.level || '?' }))
540
+ : null,
494
541
  h('div', { style: { marginTop: 10, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
495
542
  h('button', { style: button, onClick: () => toggleHeap6g(!watchdog.heap6g) }, watchdog.heap6g ? t('watchdog.heap6gOn') : t('watchdog.heap6gOff')),
496
543
  watchdog.heap6g ? h('span', { style: { ...C.muted, fontSize: 11.5 } }, t('watchdog.heap6gPending')) : null,
package/cordis.patch.yml CHANGED
@@ -3,10 +3,13 @@
3
3
  # Two rows:
4
4
  # ai-prison Host tools + read-only status API + the sidebar panel
5
5
  # (L0-L5 matrix, audit chain, plugin prison and memory cards).
6
- # ai-prison-watchdog P0 watchdog in OBSERVE mode: samples the host heap,
7
- # accounts plugin operations, reads recent host crash logs and
8
- # serves /api/ai-prison/watchdog/status. It never enables or
9
- # disables a plugin; enforcement arrives in later phases.
6
+ # ai-prison-watchdog Memory watchdog + plugin-operation enforcement. It samples
7
+ # the host heap and startup memory, accounts plugin operations,
8
+ # reads recent host crash logs, watches the profile files and
9
+ # serves /api/ai-prison/watchdog/*. Enforcement is ON by
10
+ # default: pause/freeze rolls back additive operations and a
11
+ # hot-operation limit closes + quarantines the plugin.
12
+ # Set enforce: false for observe-only (record, never touch).
10
13
  #
11
14
  # Optional config (a profile-level patch replaces this block wholesale, so
12
15
  # restate every field you want to keep):
@@ -16,11 +19,16 @@
16
19
  # dataDir: '' # durable ledger directory (default <session cwd>/.ai-prison)
17
20
  # timeoutMs: 120000 # per-call CLI timeout
18
21
  #
19
- # The watchdog accepts:
22
+ # The watchdog accepts (defaults shown; all security-sensitive extras are off):
20
23
  #
21
24
  # config:
22
- # sampleMs: 5000 # heap sampling interval
23
- # observe: true # P0 is observe-only; enforcement is not implemented yet
25
+ # enforce: true # false = observe only (records, never closes a plugin)
26
+ # sampleMs: 5000 # heap sampling interval
27
+ # rssScan: false # child-process RSS scan (spawns PowerShell every 60s)
28
+ # probeAuto: false # automatic budget probes at startup (spawns node)
29
+ # tamperPolicy: observe # observe | alert | restore (restore rewrites profile)
30
+ # crashFallback: enforce # enforce | dry-run (pending-boot plan only)
31
+ # notify: false # Windows tray notifications
24
32
  - insert:
25
33
  - id: ai-prison
26
34
  name: '@twinsearth/ai-prison-dsh-plugin'
package/docs/preview.svg CHANGED
@@ -1,30 +1,66 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300" fill="none">
2
- <rect x="24" y="24" width="592" height="252" rx="16" fill="#f8fafc"/>
3
- <rect x="24" y="24" width="592" height="252" rx="16" stroke="#e2e8f0" stroke-width="2"/>
4
- <path d="M132 58 214 91v58c0 44-82 86-82 86S50 193 50 149V91z" stroke="#334155" stroke-width="6" stroke-linejoin="round"/>
5
- <path d="M104 116v64M132 108v80M160 116v64" stroke="#334155" stroke-width="6" stroke-linecap="round"/>
6
- <circle cx="132" cy="228" r="10" fill="#334155"/>
7
- <rect x="268" y="62" width="52" height="22" rx="11" fill="#334155"/>
8
- <rect x="336" y="62" width="196" height="22" rx="11" fill="#cbd5e1"/>
9
- <rect x="268" y="100" width="52" height="22" rx="11" fill="#475569"/>
10
- <rect x="336" y="100" width="164" height="22" rx="11" fill="#cbd5e1"/>
11
- <rect x="268" y="138" width="52" height="22" rx="11" fill="#64748b"/>
12
- <rect x="336" y="138" width="132" height="22" rx="11" fill="#cbd5e1"/>
13
- <rect x="268" y="176" width="52" height="22" rx="11" fill="#94a3b8"/>
14
- <rect x="336" y="176" width="100" height="22" rx="11" fill="#cbd5e1"/>
15
- <rect x="268" y="214" width="52" height="22" rx="11" fill="#2563eb"/>
16
- <rect x="336" y="214" width="68" height="22" rx="11" fill="#bfdbfe"/>
17
- <g stroke="#2563eb" stroke-width="3" fill="none">
18
- <rect x="464" y="88" width="44" height="26" rx="13"/>
19
- <rect x="520" y="88" width="44" height="26" rx="13"/>
20
- <rect x="464" y="150" width="44" height="26" rx="13"/>
21
- <rect x="520" y="150" width="44" height="26" rx="13"/>
22
- <rect x="464" y="212" width="44" height="26" rx="13"/>
23
- <rect x="520" y="212" width="44" height="26" rx="13"/>
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="640" height="300" viewBox="0 0 640 300" fill="none" role="img" aria-label="AI Prison panel preview">
2
+ <rect width="640" height="300" rx="14" fill="#0b1020"/>
3
+ <rect x="10" y="10" width="620" height="280" rx="10" fill="#121a2e" stroke="#26345a"/>
4
+
5
+ <rect x="22" y="20" width="22" height="24" rx="6" fill="#14203a" stroke="#334155"/>
6
+ <path d="M33 24 40 27v5c0 4-7 8-7 8s-7-4-7-8v-5z" fill="none" stroke="#7dd3fc" stroke-width="1.6" stroke-linejoin="round"/>
7
+ <path d="M30 30v6M33 29v8M36 30v6" stroke="#7dd3fc" stroke-width="1.4" stroke-linecap="round"/>
8
+ <rect x="52" y="22" width="110" height="9" rx="4.5" fill="#e8eefc" opacity="0.9"/>
9
+ <rect x="52" y="36" width="170" height="6" rx="3" fill="#9fb0d0" opacity="0.5"/>
10
+ <rect x="500" y="20" width="60" height="16" rx="8" fill="#14203a" stroke="#2f5d50"/>
11
+ <circle cx="510" cy="28" r="3" fill="#34d399"/>
12
+ <rect x="518" y="25" width="34" height="6" rx="3" fill="#6ee7b7" opacity="0.8"/>
13
+ <rect x="568" y="20" width="50" height="16" rx="8" fill="#14203a" stroke="#2f5d50"/>
14
+ <circle cx="578" cy="28" r="3" fill="#34d399"/>
15
+ <rect x="586" y="25" width="24" height="6" rx="3" fill="#6ee7b7" opacity="0.8"/>
16
+
17
+ <rect x="22" y="52" width="286" height="226" rx="9" fill="#0f172b" stroke="#26345a"/>
18
+ <rect x="36" y="66" width="120" height="8" rx="4" fill="#e8eefc" opacity="0.85"/>
19
+ <line x1="36" y1="82" x2="294" y2="82" stroke="#26345a"/>
20
+ <g opacity="0.9">
21
+ <rect x="36" y="92" width="34" height="8" rx="4" fill="#7dd3fc"/>
22
+ <rect x="80" y="92" width="60" height="8" rx="4" fill="#e8eefc" opacity="0.7"/>
23
+ <rect x="150" y="90" width="52" height="12" rx="6" fill="#14203a" stroke="#26345a"/>
24
+ <rect x="208" y="90" width="52" height="12" rx="6" fill="#14203a" stroke="#26345a"/>
25
+ <rect x="36" y="114" width="34" height="8" rx="4" fill="#7dd3fc"/>
26
+ <rect x="80" y="114" width="60" height="8" rx="4" fill="#e8eefc" opacity="0.7"/>
27
+ <rect x="150" y="112" width="64" height="12" rx="6" fill="#14203a" stroke="#26345a"/>
28
+ <rect x="36" y="136" width="34" height="8" rx="4" fill="#7dd3fc"/>
29
+ <rect x="80" y="136" width="60" height="8" rx="4" fill="#e8eefc" opacity="0.7"/>
30
+ <rect x="150" y="134" width="58" height="12" rx="6" fill="#3a2a12" stroke="#78350f"/>
31
+ <rect x="36" y="158" width="34" height="8" rx="4" fill="#7dd3fc"/>
32
+ <rect x="80" y="158" width="60" height="8" rx="4" fill="#e8eefc" opacity="0.7"/>
33
+ <rect x="150" y="156" width="70" height="12" rx="6" fill="#3a2a12" stroke="#78350f"/>
34
+ <rect x="36" y="180" width="34" height="8" rx="4" fill="#7dd3fc"/>
35
+ <rect x="80" y="180" width="60" height="8" rx="4" fill="#e8eefc" opacity="0.7"/>
36
+ <rect x="150" y="178" width="78" height="12" rx="6" fill="#3a1a1a" stroke="#7f1d1d"/>
37
+ <rect x="36" y="202" width="34" height="8" rx="4" fill="#7dd3fc"/>
38
+ <rect x="80" y="202" width="60" height="8" rx="4" fill="#e8eefc" opacity="0.7"/>
39
+ <rect x="150" y="200" width="64" height="12" rx="6" fill="#3a1a1a" stroke="#7f1d1d"/>
24
40
  </g>
25
- <path d="M508 101h12M508 163h12M508 225h12" stroke="#2563eb" stroke-width="3"/>
26
- <path d="M452 101h8M452 163h8M452 225h8" stroke="#94a3b8" stroke-width="3"/>
27
- <circle cx="576" cy="101" r="7" fill="#16a34a"/>
28
- <circle cx="576" cy="163" r="7" fill="#16a34a"/>
29
- <circle cx="576" cy="225" r="7" fill="#16a34a"/>
41
+ <rect x="36" y="230" width="240" height="7" rx="3.5" fill="#9fb0d0" opacity="0.45"/>
42
+ <rect x="36" y="244" width="180" height="7" rx="3.5" fill="#6ee7b7" opacity="0.7"/>
43
+ <rect x="36" y="258" width="210" height="7" rx="3.5" fill="#9fb0d0" opacity="0.4"/>
44
+
45
+ <rect x="320" y="52" width="298" height="104" rx="9" fill="#0f172b" stroke="#26345a"/>
46
+ <rect x="334" y="66" width="82" height="8" rx="4" fill="#e8eefc" opacity="0.85"/>
47
+ <rect x="334" y="82" width="54" height="14" rx="7" fill="#14203a" stroke="#2f5d50"/>
48
+ <circle cx="343" cy="89" r="3" fill="#34d399"/>
49
+ <rect x="352" y="86" width="28" height="6" rx="3" fill="#86efac" opacity="0.8"/>
50
+ <rect x="398" y="85" width="54" height="8" rx="4" fill="#6ee7b7" opacity="0.7"/>
51
+ <rect x="334" y="110" width="270" height="8" rx="4" fill="#1b2946"/>
52
+ <rect x="334" y="110" width="16" height="8" rx="4" fill="#34d399"/>
53
+ <rect x="334" y="128" width="150" height="7" rx="3.5" fill="#9fb0d0" opacity="0.55"/>
54
+ <rect x="334" y="142" width="120" height="7" rx="3.5" fill="#9fb0d0" opacity="0.4"/>
55
+
56
+ <rect x="320" y="166" width="298" height="112" rx="9" fill="#0f172b" stroke="#26345a"/>
57
+ <rect x="334" y="180" width="120" height="8" rx="4" fill="#e8eefc" opacity="0.85"/>
58
+ <rect x="334" y="196" width="270" height="46" rx="7" fill="#121a2e" stroke="#26345a"/>
59
+ <rect x="344" y="206" width="120" height="7" rx="3.5" fill="#fca5a5" opacity="0.75"/>
60
+ <rect x="344" y="220" width="170" height="6" rx="3" fill="#9fb0d0" opacity="0.4"/>
61
+ <rect x="344" y="231" width="140" height="6" rx="3" fill="#9fb0d0" opacity="0.3"/>
62
+ <rect x="548" y="206" width="46" height="16" rx="6" fill="#14203a" stroke="#334155"/>
63
+ <rect x="560" y="211" width="22" height="6" rx="3" fill="#e8eefc" opacity="0.8"/>
64
+ <rect x="334" y="254" width="250" height="7" rx="3.5" fill="#fbbf24" opacity="0.6"/>
65
+ <rect x="334" y="266" width="180" height="6" rx="3" fill="#9fb0d0" opacity="0.35"/>
30
66
  </svg>
package/lib/api.js CHANGED
@@ -1,3 +1,4 @@
1
+ import path from 'node:path'
1
2
  import { resolveCli, resolveDataDir, runCli } from './cli.js'
2
3
  import { listSegments, resetLedger } from './ledger.js'
3
4
  import { buildStatus, summarizeRun } from './status.js'
@@ -31,8 +32,51 @@ export function resolveSessionCwd(ctx) {
31
32
  return undefined
32
33
  }
33
34
 
35
+ function samePath(left, right) {
36
+ const normalize = (value) => {
37
+ const resolved = path.resolve(String(value))
38
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved
39
+ }
40
+ return normalize(left) === normalize(right)
41
+ }
42
+
43
+ /**
44
+ * Resolve a `data_dir` requested over HTTP against the ledger directories the
45
+ * panel is allowed to touch: the configured directory and `<cwd>/.ai-prison`.
46
+ * The agent-facing tools keep their explicit-path freedom, but a web route must
47
+ * not be able to point `reset`/`demo` at an arbitrary directory on disk.
48
+ */
49
+ export function resolveAllowedDataDir({ requested, config = {}, cwd } = {}) {
50
+ const baseCwd = cwd || process.cwd()
51
+ const defaultDir = path.resolve(resolveDataDir({ config, cwd: baseCwd }))
52
+ const allowed = [...new Set([defaultDir, path.resolve(baseCwd, '.ai-prison')])]
53
+ if (requested === undefined || requested === null) return { ok: true, dir: defaultDir, allowed }
54
+ if (typeof requested !== 'string' || requested.trim() === '') {
55
+ return { ok: false, reason: 'invalid', error: 'data_dir must be a non-empty string', allowed }
56
+ }
57
+ const resolved = path.resolve(baseCwd, requested.trim())
58
+ const match = allowed.find((candidate) => samePath(candidate, resolved))
59
+ if (!match) {
60
+ return {
61
+ ok: false,
62
+ reason: 'not-allowed',
63
+ error: 'data_dir must be the configured ledger directory or <working directory>/.ai-prison',
64
+ dir: resolved,
65
+ allowed,
66
+ }
67
+ }
68
+ return { ok: true, dir: match, allowed }
69
+ }
70
+
34
71
  const ACTIONS = new Set(['demo', 'drill', 'reset', 'reset-demo', 'reset-drill'])
35
72
 
73
+ /** Minimum spacing between two POST /run executions (simple local throttle). */
74
+ export const RUN_MIN_INTERVAL_MS = 1000
75
+ let lastRunAt = 0
76
+ export function resetRunThrottle() {
77
+ lastRunAt = 0
78
+ }
79
+
36
80
  function jsonResponse(payload, status = 200) {
37
81
  return Response.json(payload, { status, headers: { 'cache-control': 'no-store' } })
38
82
  }
@@ -61,9 +105,13 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
61
105
  fetch: async (request) => {
62
106
  try {
63
107
  const url = new URL(request.url)
108
+ const cwd = resolveSessionCwd(ctx)
64
109
  const requested = url.searchParams.get('data_dir')
65
- const statusConfig = requested ? { ...config, dataDir: requested } : config
66
- const status = await buildStatus({ config: statusConfig, cwd: resolveSessionCwd(ctx) })
110
+ const allowed = resolveAllowedDataDir({ requested: requested === null ? undefined : requested, config, cwd })
111
+ if (!allowed.ok) {
112
+ return jsonResponse({ ok: false, error: allowed.error, reason: 'data-dir-not-allowed', allowed: allowed.allowed, dir: allowed.dir }, 403)
113
+ }
114
+ const status = await buildStatus({ config: { ...config, dataDir: allowed.dir }, cwd })
67
115
  return jsonResponse(status)
68
116
  } catch (error) {
69
117
  return jsonResponse({ ok: false, error: String((error && error.message) || error) }, 500)
@@ -89,10 +137,19 @@ export function registerApi({ ctx, config = {}, logger } = {}) {
89
137
  if (!ACTIONS.has(action)) {
90
138
  return jsonResponse({ ok: false, error: 'action must be one of demo, drill, reset, reset-demo' }, 400)
91
139
  }
140
+ const sinceLastRun = Date.now() - lastRunAt
141
+ if (sinceLastRun < RUN_MIN_INTERVAL_MS) {
142
+ return jsonResponse({ ok: false, error: 'run is rate limited', reason: 'rate-limited', retryAfterMs: RUN_MIN_INTERVAL_MS - sinceLastRun }, 429)
143
+ }
144
+ lastRunAt = Date.now()
92
145
  const resolved = resolveCli({ config })
93
146
  const cwd = resolveSessionCwd(ctx) || process.cwd()
94
147
  const requested = typeof body?.data_dir === 'string' && body.data_dir ? body.data_dir : undefined
95
- const dataDir = requested ? requested : resolveDataDir({ config, cwd })
148
+ const allowed = resolveAllowedDataDir({ requested, config, cwd })
149
+ if (!allowed.ok) {
150
+ return jsonResponse({ ok: false, action, error: allowed.error, reason: 'data-dir-not-allowed', allowed: allowed.allowed, dir: allowed.dir }, 403)
151
+ }
152
+ const dataDir = allowed.dir
96
153
 
97
154
  let removed = []
98
155
  if (action === 'reset' || action === 'reset-demo' || action === 'reset-drill') {
package/lib/boot-watch.js CHANGED
@@ -9,18 +9,20 @@ import path from 'node:path'
9
9
  * so that a later boot (or the external guard) can see the curve even when this
10
10
  * process dies. Two stricter startup thresholds raise a safe-boot plan:
11
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).
12
+ * - total heap > ~49% of the heap cap (2.0 GB on a 4 GB host, 3.0 GB on a 6 GB host).
13
13
  */
14
14
  export const BOOT_SAMPLE_MS = 500
15
15
  export const BOOT_MAX_MS = 120_000
16
16
  export const BOOT_RATE_MBPS = 150
17
+ export const BOOT_TOTAL_RATIO = 0.49
17
18
  export const RUN_KEEP = 5
18
19
 
19
20
  export function bootThresholdsFor(heapLimitBytes) {
20
21
  const limitGB = Number(heapLimitBytes) / (1024 * 1024 * 1024)
22
+ const totalMB = Math.max(500, Math.round(limitGB * 1024 * BOOT_TOTAL_RATIO))
21
23
  return {
22
24
  rateMBps: BOOT_RATE_MBPS,
23
- totalMB: limitGB >= 5.5 ? 3000 : 2000,
25
+ totalMB,
24
26
  }
25
27
  }
26
28
 
package/lib/harness.js CHANGED
@@ -15,10 +15,19 @@ export function installationAnchors({ execPath = process.execPath, env = process
15
15
  // the installation root arrives as DSH_INSTALL_DIR or as the host's second
16
16
  // argument (after the entry module).
17
17
  const argvRoot = typeof argv[2] === 'string' && argv[2].endsWith('package.json') === false ? argv[2] : undefined
18
+ // The entry module (argv[1]) often sits either directly in the runtime root
19
+ // (…/app.asar/dsh/index.js) or in a subdirectory (…/dsh/dist/index.js). Both
20
+ // are useful anchors when execPath no longer points at the installation.
21
+ const entry = typeof argv[1] === 'string' && path.isAbsolute(argv[1]) ? argv[1] : undefined
22
+ const entryDir = entry ? path.dirname(entry) : undefined
23
+ const entryParent = entryDir ? path.dirname(entryDir) : undefined
24
+ const entryLooksLikeDsh = (candidate) => Boolean(candidate) && /(^|[\\/])(app\.asar|dsh|dsh-runtime)([\\/]|$)/.test(candidate)
18
25
  return [
19
26
  env.DSH_APP_ANCHOR,
20
27
  env.DSH_INSTALL_DIR ? path.join(env.DSH_INSTALL_DIR, 'package.json') : undefined,
21
28
  argvRoot && path.basename(argvRoot) === 'dsh' ? path.join(argvRoot, 'package.json') : undefined,
29
+ entryLooksLikeDsh(entryDir) ? path.join(entryDir, 'package.json') : undefined,
30
+ entryLooksLikeDsh(entryParent) ? path.join(entryParent, 'package.json') : undefined,
22
31
  path.join(dir, 'resources', 'app.asar', 'dsh', 'package.json'),
23
32
  path.join(dir, 'resources', 'app', 'dsh', 'package.json'),
24
33
  path.join(dir, '..', 'Resources', 'app.asar', 'dsh', 'package.json'),
@@ -42,11 +42,12 @@ const REMEDIATION = {
42
42
  tamper: {
43
43
  title: '关键配置文件被非插件管理器修改',
44
44
  why: 'profile 的 package.json / cordis.patch.yml / pnpm-workspace.yaml / pnpm-lock.yaml 在插件管理器操作窗口之外发生了变化(被修改或删除)。',
45
- impact: '已把被改动内容备份到 .ai-prison-watchdog/tampered/,默认恢复原文件;归因到的最后安装/启用插件已被隔离。',
45
+ impact: '默认 observe 只记录并保存证据,不会改动文件;策略为 restore 时才会把被改动内容备份到 .ai-prison-watchdog/tampered/、恢复原文件,并隔离归因到的最后安装/启用插件。',
46
46
  steps: [
47
47
  '检查 .ai-prison-watchdog/tampered/ 下的备份,确认改动来自哪里(手工编辑、脚本、其他工具)。',
48
48
  '不要在 DSH 运行中手工改 profile 配置;确需修改时先退出 DSH。',
49
- '确认无插件行为异常后,在面板"插件监狱"点"假释"恢复该插件。',
49
+ '确认需要自动恢复时,显式把 tamperPolicy 设为 restore,并先核对备份内容。',
50
+ '确认无插件行为异常后,在面板"插件监狱"点"假释"恢复被隔离的插件。',
50
51
  ],
51
52
  release: '手动释放(面板"假释");恢复前先核对 tampered/ 备份。',
52
53
  },