@twinsearth/ai-prison-dsh-plugin 1.5.1 → 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,23 @@
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
5
22
  ## [1.5.1] — 2026-11-18
6
23
 
7
24
  ### Fixed — Top5 v2 child RSS attribution never matched
@@ -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,
@@ -806,7 +807,7 @@ export function createWatchdog(ctx, config = {}, logger = {}) {
806
807
  refs.manager = child.pluginManager || (typeof child.get === 'function' ? child.get('pluginManager') : null)
807
808
  if (refs.manager) {
808
809
  void reapplyQuarantine()
809
- startRssScanner()
810
+ startRssScannerV2({ ctx, refs, profileDir, watchdogState, appendIncident, exemptTargets: EXEMPT_TARGETS })
810
811
  const probeTimer = setTimeout(() => {
811
812
  void scheduleProbe()
812
813
  }, Number(config.probeDelayMs) > 0 ? Number(config.probeDelayMs) : 30_000)
@@ -1012,6 +1013,9 @@ export function watchdogSnapshot() {
1012
1013
  tamper: s.tamper || null,
1013
1014
  rss: s.rss || {},
1014
1015
  rssAt: s.rssAt || null,
1016
+ rssError: s.rssError || null,
1017
+ rssStats: s.rssStats || null,
1018
+ rssServiceError: s.rssServiceError || null,
1015
1019
  incidents: s.incidents.slice(-20),
1016
1020
  generatedAt: new Date().toISOString(),
1017
1021
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@twinsearth/ai-prison-dsh-plugin",
3
- "version": "1.5.1",
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",