@twinsearth/ai-prison-dsh-plugin 1.5.0 → 1.5.2

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,38 @@
2
2
 
3
3
  All notable changes to `@twinsearth/ai-prison-dsh-plugin` are recorded here.
4
4
 
5
+ ## [1.5.2] — 2026-11-18
6
+
7
+ ### Fixed — child RSS scan is observable and prefers the Host subprocess service
8
+
9
+ - The scan now runs through `ctx.subprocess` (collected stdout, abort signal,
10
+ grace) and falls back to a direct spawn only when that service is absent;
11
+ both paths share one parser (`lib/rss.js`).
12
+ - Failures are no longer silent: the watchdog records `rssError`, sets
13
+ `degraded`, emits one `rss-scan-failed` incident per run and stamps `rssAt`
14
+ on every attempt. The service error is kept in `rssServiceError`.
15
+ - The parser hardens matching (`node_modules\\@scope\\name` and
16
+ `node_modules/@scope/name`), skips the host/skip marker and exposes
17
+ `rssStats {lines, matched, names}`.
18
+ - Tests: `test/rss.test.mjs` covers Windows/posix paths, host exclusion and
19
+ self-pid exclusion.
20
+
21
+ ## [1.5.1] — 2026-11-18
22
+ ## [1.5.1] — 2026-11-18
23
+
24
+ ### Fixed — Top5 v2 child RSS attribution never matched
25
+
26
+ - The scanner filtered process command lines by the profile path, which matched
27
+ the host and the local subprocess runner but not plugin children, and it built
28
+ Windows needles from `@scope/name` without converting the scope separator.
29
+ - It now scans every process with a command line, skips the host itself and
30
+ `dsh-desktop-host` children, and matches
31
+ `node_modules\\@scope\\name` / `node_modules/@scope/name` for each enabled
32
+ plugin, so `xray-core`, the w2m runner and similar children are attributed.
33
+ - `rssAt` is written even when nothing matches, and `rssScan: false` disables the
34
+ scan.
35
+
36
+ ## [1.5.0] — 2026-11-18
5
37
  ## [1.5.0] — 2026-11-18
6
38
 
7
39
  ### Changed — profile tamper monitor is dry-run (observe) by default
@@ -0,0 +1,123 @@
1
+ import { spawn as defaultSpawn } from 'node:child_process'
2
+ import { RSS_QUERY_SCRIPT, parseProcessList } from './rss.js'
3
+
4
+ /**
5
+ * Child-process RSS scanner (Windows).
6
+ *
7
+ * Prefers the Host subprocess service (collected stdout + abort signal) and
8
+ * falls back to a direct spawn. Failures are recorded on the watchdog state and
9
+ * reported once per run instead of silently producing an empty Top5.
10
+ */
11
+ const INTERVAL_MS = 60_000
12
+
13
+ export function startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets, spawn = defaultSpawn }) {
14
+ if (process.platform !== 'win32') return undefined
15
+ if (watchdogState.config && watchdogState.config.rssScan === false) return undefined
16
+ if (refs.rssStarted) return undefined
17
+ refs.rssStarted = true
18
+ let scanning = false
19
+ let failureReported = false
20
+ let timer = null
21
+
22
+ function service() {
23
+ try {
24
+ return typeof ctx.get === 'function' ? ctx.get('subprocess') : null
25
+ } catch {
26
+ return null
27
+ }
28
+ }
29
+
30
+ function direct() {
31
+ return new Promise((resolve, reject) => {
32
+ const child = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', RSS_QUERY_SCRIPT], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
33
+ let stdout = ''
34
+ let stderr = ''
35
+ child.stdout.on('data', (chunk) => {
36
+ stdout += String(chunk)
37
+ })
38
+ child.stderr.on('data', (chunk) => {
39
+ stderr = (stderr + String(chunk)).slice(-500)
40
+ })
41
+ child.on('error', (error) => reject(error))
42
+ child.on('exit', (code) => {
43
+ if (code === 0) resolve({ stdout })
44
+ else reject(new Error('powershell exit ' + code + ': ' + stderr))
45
+ })
46
+ })
47
+ }
48
+
49
+ async function viaService(serviceInstance) {
50
+ const controller = new AbortController()
51
+ const abortTimer = setTimeout(() => controller.abort(), 20_000)
52
+ if (typeof abortTimer.unref === 'function') abortTimer.unref()
53
+ try {
54
+ const handle = serviceInstance.spawn({
55
+ argv: ['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', RSS_QUERY_SCRIPT],
56
+ cwd: profileDir,
57
+ stdio: { stdin: 'ignore', stdout: { maxBytes: 4 * 1024 * 1024 }, stderr: { maxBytes: 64 * 1024 } },
58
+ graceMs: 5000,
59
+ signal: controller.signal,
60
+ })
61
+ await handle.done
62
+ const stdout = handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
63
+ const stderr = handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
64
+ if (!stdout) throw new Error('subprocess service returned no stdout' + (stderr ? ': ' + stderr.slice(0, 300) : ''))
65
+ return { stdout }
66
+ } finally {
67
+ clearTimeout(abortTimer)
68
+ }
69
+ }
70
+
71
+ async function scan() {
72
+ if (scanning) return
73
+ const manager = refs.manager
74
+ if (!manager || typeof manager.listBundles !== 'function') return
75
+ scanning = true
76
+ const attemptedAt = new Date().toISOString()
77
+ watchdogState.rssAttempts = (watchdogState.rssAttempts || 0) + 1
78
+ try {
79
+ let result
80
+ const serviceInstance = service()
81
+ if (serviceInstance && typeof serviceInstance.spawn === 'function') {
82
+ try {
83
+ result = await viaService(serviceInstance)
84
+ } catch (error) {
85
+ watchdogState.rssServiceError = String((error && error.message) || error).slice(0, 300)
86
+ }
87
+ }
88
+ if (!result) result = await direct()
89
+ const rows = await manager.listBundles()
90
+ const enabled = rows.filter((row) => row.enabled && !exemptTargets.has(row.name)).map((row) => row.name)
91
+ const parsed = parseProcessList(result.stdout, enabled)
92
+ const rss = { ...(watchdogState.rss || {}) }
93
+ for (const [name, bytes] of Object.entries(parsed.rss)) rss[name] = bytes
94
+ watchdogState.rss = rss
95
+ watchdogState.rssAt = attemptedAt
96
+ watchdogState.rssError = null
97
+ watchdogState.rssStats = { lines: parsed.lines, matched: parsed.matched, names: Object.keys(parsed.rss).length }
98
+ failureReported = false
99
+ } catch (error) {
100
+ const message = String((error && error.message) || error).slice(0, 300)
101
+ watchdogState.rssAt = attemptedAt
102
+ watchdogState.rssError = message
103
+ watchdogState.degraded = 'rss scan: ' + message
104
+ if (!failureReported) {
105
+ failureReported = true
106
+ try {
107
+ appendIncident({ kind: 'rss-scan-failed', detail: '子进程 RSS 扫描失败:' + message })
108
+ } catch {
109
+ // best effort
110
+ }
111
+ }
112
+ } finally {
113
+ scanning = false
114
+ }
115
+ }
116
+
117
+ const first = setTimeout(scan, 5000)
118
+ if (typeof first.unref === 'function') first.unref()
119
+ timer = setInterval(scan, INTERVAL_MS)
120
+ if (typeof timer.unref === 'function') timer.unref()
121
+ refs.rssTimer = timer
122
+ return { scan, timer }
123
+ }
package/lib/rss.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Child-process RSS attribution shared by the watchdog and its tests.
3
+ * The query lists every process with a command line; a process belongs to a
4
+ * plugin when its command line references that plugin's package directory.
5
+ */
6
+ export const RSS_QUERY_SCRIPT = [
7
+ "$ErrorActionPreference='SilentlyContinue'",
8
+ 'Get-CimInstance Win32_Process | Where-Object { $_.CommandLine } | ForEach-Object { ($_.ProcessId.ToString() + \'|\' + [string]$_.WorkingSetSize + \'|\' + $_.CommandLine) }',
9
+ ].join('; ')
10
+
11
+ export function parseProcessList(output, pluginNames, { selfPid = process.pid, skipHostMarker = 'dsh-desktop-host' } = {}) {
12
+ const names = [...new Set((Array.isArray(pluginNames) ? pluginNames : []).filter(Boolean))]
13
+ const rss = {}
14
+ let lines = 0
15
+ let matched = 0
16
+ for (const line of String(output || '').split('\n')) {
17
+ const trimmed = line.trim()
18
+ if (!trimmed) continue
19
+ const parts = trimmed.split('|')
20
+ if (parts.length < 3) continue
21
+ lines += 1
22
+ const pid = Number(parts[0])
23
+ const bytes = Number(parts[1]) || 0
24
+ const commandLine = parts.slice(2).join('|')
25
+ if (pid === selfPid || commandLine.includes(skipHostMarker)) continue
26
+ for (const name of names) {
27
+ const winNeedle = 'node_modules' + '\\' + name.split('/').join('\\')
28
+ const posixNeedle = 'node_modules/' + name
29
+ if (commandLine.includes(winNeedle) || commandLine.includes(posixNeedle)) {
30
+ rss[name] = (rss[name] || 0) + bytes
31
+ matched += 1
32
+ break
33
+ }
34
+ }
35
+ }
36
+ return { rss, lines, matched }
37
+ }
@@ -9,6 +9,7 @@ import { probeBudget } from './budget-probe.js'
9
9
  import { createTamperMonitor } from './tamper-monitor.js'
10
10
  import { remediationFor } from './remediation.js'
11
11
  import { notify } from './notifier.js'
12
+ import { startRssScannerV2 } from './rss-scan.js'
12
13
  import {
13
14
  attributeCrash,
14
15
  classifyWaterline,
@@ -221,19 +222,14 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
221
222
  const manager = refs.manager
222
223
  if (!manager || typeof manager.listBundles !== 'function') return
223
224
  rssScanning = true
224
- const profileLiteral = String(profileDir).replace(/'/g, "''")
225
225
  const script = [
226
226
  "$ErrorActionPreference='SilentlyContinue'",
227
- "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -like '*node_modules*' -and $_.CommandLine -like '*" + profileLiteral + "*' } | ForEach-Object { ($_.ProcessId.ToString() + '|' + [string]$_.WorkingSetSize + '|' + $_.CommandLine) }",
227
+ "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine } | ForEach-Object { ($_.ProcessId.ToString() + '|' + [string]$_.WorkingSetSize + '|' + $_.CommandLine) }",
228
228
  ].join('; ')
229
229
  let output = ''
230
230
  const child = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script], { windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] })
231
- child.stdout.on('data', (chunk) => {
232
- output += String(chunk)
233
- })
234
- child.on('error', () => {
235
- rssScanning = false
236
- })
231
+ child.stdout.on('data', (chunk) => { output += String(chunk) })
232
+ child.on('error', () => { rssScanning = false })
237
233
  child.on('exit', () => {
238
234
  rssScanning = false
239
235
  void manager
@@ -244,10 +240,14 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
244
240
  for (const line of output.split('\n')) {
245
241
  const parts = line.trim().split('|')
246
242
  if (parts.length < 3) continue
243
+ const pid = Number(parts[0])
247
244
  const bytes = Number(parts[1]) || 0
248
245
  const commandLine = parts.slice(2).join('|')
246
+ if (pid === process.pid || commandLine.includes('dsh-desktop-host')) continue
249
247
  for (const name of enabled) {
250
- if (commandLine.includes('node_modules' + path.sep + name) || commandLine.includes('node_modules/' + name)) {
248
+ const winNeedle = 'node_modules' + path.sep + name.split('/').join(path.sep)
249
+ const posixNeedle = 'node_modules/' + name
250
+ if (commandLine.includes(winNeedle) || commandLine.includes(posixNeedle)) {
251
251
  totals.set(name, (totals.get(name) || 0) + bytes)
252
252
  break
253
253
  }
@@ -263,7 +263,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
263
263
  }
264
264
 
265
265
  function startRssScanner() {
266
- if (rssTimer || process.platform !== 'win32') return
266
+ if (rssTimer || process.platform !== 'win32' || watchdogState.config.rssScan === false) return
267
267
  const timer = setTimeout(scanChildRss, 5000)
268
268
  if (typeof timer.unref === 'function') timer.unref()
269
269
  rssTimer = setInterval(scanChildRss, RSS_INTERVAL_MS)
@@ -807,7 +807,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
807
807
  refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
808
808
  if (refs.manager) {
809
809
  void reapplyQuarantine()
810
- startRssScanner()
810
+ startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets: EXEMPT_TARGETS })
811
811
  const probeTimer = setTimeout(() => {
812
812
  void scheduleProbe()
813
813
  }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
@@ -1013,6 +1013,9 @@ export function watchdogSnapshot() {
1013
1013
  tamper: s.tamper || null,
1014
1014
  rss: s.rss || {},
1015
1015
  rssAt: s.rssAt || null,
1016
+ rssError: s.rssError || null,
1017
+ rssStats: s.rssStats || null,
1018
+ rssServiceError: s.rssServiceError || null,
1016
1019
  incidents: s.incidents.slice(-20),
1017
1020
  generatedAt: new Date().toISOString(),
1018
1021
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.5.0",
3
+ "version": "1.5.2",
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",