Skip to content

The agent that grows with you

test(desktop-e2e): the core lane's process census and tool paths work off Linux

Tekniumf12e19697a3f
diff --git a/apps/desktop/e2e/core/boot-lifecycle.spec.ts b/apps/desktop/e2e/core/boot-lifecycle.spec.ts
index 33f22c5cb8e..cd78aa578bc 100644
--- a/apps/desktop/e2e/core/boot-lifecycle.spec.ts
+++ b/apps/desktop/e2e/core/boot-lifecycle.spec.ts
@@ -21,8 +21,6 @@
* persisted by the first launch cold-hydrates exactly once every time.
*/
-import * as fs from 'node:fs'
-
import { expect, test } from '@playwright/test'
import {
@@ -31,7 +29,6 @@ import {
createCoreSandbox,
currentSessionId,
launchCoreApp,
- type ProcInfo,
recordWebSockets,
sandboxProcesses,
send,
@@ -40,6 +37,7 @@ import {
writeProviderHome
} from './harness'
import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
+import { processesTagged } from './process-census'
import { gate, startScriptedProvider } from './provider'
const nonce = Math.random()
@@ -52,30 +50,6 @@ const U = (n: number) => `U${n}-${nonce}`
const A = (n: number) => `A${n}-${nonce}`
const TOOL_TAG = `core-orphan-${nonce}`
-/** Every live process whose command line carries `tag` (tool children may scrub HERMES_HOME). */
-function taggedProcesses(tag: string): ProcInfo[] {
- const out: ProcInfo[] = []
-
- for (const entry of fs.readdirSync('/proc')) {
- const pid = Number(entry)
-
- if (!Number.isInteger(pid) || pid === process.pid) {
- continue
- }
-
- try {
- const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim()
-
- if (cmdline.includes(tag)) {
- out.push({ pid, ppid: 0, cmdline })
- }
- } catch {
- /* exited mid-scan */
- }
- }
-
- return out
-}
test('boot handshake, supervised respawn, and zero orphans on quit', async () => {
const provider = await startScriptedProvider()
@@ -173,7 +147,7 @@ test('boot handshake, supervised respawn, and zero orphans on quit', async () =>
])
await send(page, `${U(3)} long tool`, 'Enter', ws)
await expect
- .poll(() => taggedProcesses(TOOL_TAG).length, { timeout: 120_000, message: 'tool child running' })
+ .poll(() => processesTagged(TOOL_TAG).length, { timeout: 120_000, message: 'tool child running' })
.toBeGreaterThan(0)
const [gateway] = backendProcesses(sandbox)
expect(gateway).toBeTruthy()
@@ -201,7 +175,7 @@ test('boot handshake, supervised respawn, and zero orphans on quit', async () =>
await expect
.poll(
() =>
- [...sandboxProcesses(sandbox), ...taggedProcesses(TOOL_TAG)].map(
+ [...sandboxProcesses(sandbox), ...processesTagged(TOOL_TAG)].map(
p => `${p.pid} ${p.cmdline.slice(0, 120)}`
),
{ timeout: 60_000, message: 'no sandbox process (gateway, tool child) survives hermes gateway stop' }
@@ -217,7 +191,7 @@ test('boot handshake, supervised respawn, and zero orphans on quit', async () =>
}
// Never leave a test-made process behind even on failure (only our own tag / sandbox).
- for (const proc of [...sandboxProcesses(sandbox), ...taggedProcesses(TOOL_TAG)]) {
+ for (const proc of [...sandboxProcesses(sandbox), ...processesTagged(TOOL_TAG)]) {
try {
process.kill(proc.pid, 'SIGKILL')
} catch {
diff --git a/apps/desktop/e2e/core/harness.ts b/apps/desktop/e2e/core/harness.ts
index d3890673cbc..f6cf1e2e4f1 100644
--- a/apps/desktop/e2e/core/harness.ts
+++ b/apps/desktop/e2e/core/harness.ts
@@ -19,6 +19,10 @@ import { _electron, type ElectronApplication, expect, type Page } from '@playwri
import { resolveElectronBinary } from '../electron-binary'
+import { isSandboxProcess, procfsCensus, type ProcInfo, readProc, sandboxProcessesOf } from './process-census'
+
+export type { ProcInfo } from './process-census'
+
export const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..', '..')
export const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')
@@ -86,7 +90,11 @@ function sleepSync(ms: number): void {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
}
-function processHomeUnder(pid: number, root: string): boolean {
+function processHomeUnder(pid: number, root: string, hermesHome: string): boolean {
+ if (!procfsCensus) {
+ return isSandboxProcess(pid, hermesHome)
+ }
+
const info = readProc(pid)
return Boolean(info?.cmdline) && info!.environ.split('\0').some(entry => entry.startsWith(`HERMES_HOME=${root}`))
@@ -112,7 +120,7 @@ function stopSandboxGatewayDaemons(root: string, hermesHome: string): void {
try {
const pid = Number(JSON.parse(fs.readFileSync(path.join(home, 'gateway.lock'), 'utf8'))?.pid)
- if (Number.isInteger(pid) && pid > 0 && processHomeUnder(pid, root)) {
+ if (Number.isInteger(pid) && pid > 0 && processHomeUnder(pid, root, hermesHome)) {
pids.add(pid)
}
} catch {
@@ -136,7 +144,7 @@ function stopSandboxGatewayDaemons(root: string, hermesHome: string): void {
sleepSync(100)
for (const pid of [...pids]) {
- if (!processHomeUnder(pid, root)) {
+ if (!processHomeUnder(pid, root, hermesHome)) {
pids.delete(pid)
}
}
@@ -261,53 +269,9 @@ export function appLogTail(app: ElectronApplication, n = 60): string {
// ─── Process census ─────────────────────────────────────────────────────
-export interface ProcInfo {
- pid: number
- ppid: number
- cmdline: string
-}
-
-function readProc(pid: number): null | { environ: string; cmdline: string; ppid: number } {
- try {
- const environ = fs.readFileSync(`/proc/${pid}/environ`, 'utf8')
- const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim()
- const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')
- // Field 4 (ppid) follows the parenthesised comm, which may contain spaces.
- const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1])
-
- return { environ, cmdline, ppid }
- } catch {
- return null
- }
-}
-
-/** Every live process whose environment carries this sandbox's HERMES_HOME (orphans included). */
+/** Every live process carrying this sandbox's HERMES_HOME (orphans included); see process-census.ts. */
export function sandboxProcesses(sandbox: CoreSandbox): ProcInfo[] {
- const needle = `HERMES_HOME=${sandbox.hermesHome}\0`
- const out: ProcInfo[] = []
-
- for (const entry of fs.readdirSync('/proc')) {
- const pid = Number(entry)
-
- if (!Number.isInteger(pid) || pid === process.pid) {
- continue
- }
-
- const info = readProc(pid)
-
- if (!info || !(info.environ + '\0').includes(needle)) {
- continue
- }
-
- // Zombies have an empty cmdline and are already dead for our purposes.
- if (!info.cmdline) {
- continue
- }
-
- out.push({ pid, ppid: info.ppid, cmdline: info.cmdline })
- }
-
- return out
+ return sandboxProcessesOf(sandbox.hermesHome)
}
/**
@@ -342,7 +306,8 @@ export function backendProcesses(sandbox: CoreSandbox): ProcInfo[] {
*/
export function stopSandboxGateway(sandbox: CoreSandbox): { code: number | null; output: string } {
const [backend] = backendProcesses(sandbox)
- const python = backend?.cmdline.split(' ')[0] || 'python3'
+ // argv[0], unquoted (a Windows command line quotes a path with spaces).
+ const python = /^"([^"]+)"|^(\S+)/.exec(backend?.cmdline ?? '')?.slice(1).find(Boolean) || 'python3'
const result = spawnSync(python, ['-m', 'hermes_cli.main', 'gateway', 'stop'], {
cwd: REPO_ROOT,
diff --git a/apps/desktop/e2e/core/interactive-prompts.spec.ts b/apps/desktop/e2e/core/interactive-prompts.spec.ts
index f963260570e..daa95f4b363 100644
--- a/apps/desktop/e2e/core/interactive-prompts.spec.ts
+++ b/apps/desktop/e2e/core/interactive-prompts.spec.ts
@@ -30,6 +30,7 @@ import {
writeProviderHome
} from './harness'
import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
+import { shellQuote } from './process-census'
import { type RecordedCompletion, startScriptedProvider } from './provider'
const nonce = Math.random()
@@ -121,7 +122,7 @@ test('clarify and approval prompts round-trip exactly once', async () => {
provider.script(U(2), [
{
text: [`${AI(2)} `, 'needs ', 'approval'],
- toolCalls: [{ name: 'terminal', args: { command: `rm -rf ${victim}` } }]
+ toolCalls: [{ name: 'terminal', args: { command: `rm -rf ${shellQuote(victim)}` } }]
},
{ text: [`${A(2)} `, 'deleted ', 'it'] }
])
@@ -143,7 +144,7 @@ test('clarify and approval prompts round-trip exactly once', async () => {
provider.script(U(3), [
{
text: [`${AI(3)} `, 'needs ', 'approval'],
- toolCalls: [{ name: 'terminal', args: { command: `rm -rf ${victim}` } }]
+ toolCalls: [{ name: 'terminal', args: { command: `rm -rf ${shellQuote(victim)}` } }]
},
{ text: [`${A(3)} `, 'left ', 'it ', 'alone'] }
])
diff --git a/apps/desktop/e2e/core/process-census.ts b/apps/desktop/e2e/core/process-census.ts
new file mode 100644
index 00000000000..2611c49385e
--- /dev/null
+++ b/apps/desktop/e2e/core/process-census.ts
@@ -0,0 +1,150 @@
+/**
+ * Process census for the core lane, per platform.
+ *
+ * Linux reads /proc: a process belongs to a sandbox when its environment names the sandbox
+ * HERMES_HOME (orphans reparented to init included). Other platforms have no readable foreign
+ * environment, so membership is the process tree rooted at every gateway pid a sandbox
+ * `gateway.lock` has ever recorded (remembered per sandbox, so the census still sees a stopped
+ * gateway's orphans after its lock is gone). Windows keeps a dead parent's id in
+ * ParentProcessId, so the tree walk still reaches orphans there.
+ *
+ * `HERMES_E2E_PROC_CENSUS=ps` forces the tree census on Linux (how the non-/proc path is tested).
+ */
+
+import { spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+export interface ProcInfo {
+ pid: number
+ ppid: number
+ cmdline: string
+}
+
+export const procfsCensus = process.env.HERMES_E2E_PROC_CENSUS !== 'ps' && fs.existsSync('/proc/self/environ')
+
+export function readProc(pid: number): null | { environ: string; cmdline: string; ppid: number } {
+ try {
+ const environ = fs.readFileSync(`/proc/${pid}/environ`, 'utf8')
+ const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim()
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8')
+ // Field 4 (ppid) follows the parenthesised comm, which may contain spaces.
+ const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1])
+
+ return { environ, cmdline, ppid }
+ } catch {
+ return null
+ }
+}
+
+/** Every live process (pid, ppid, command line); zombies/unreadable entries skipped. */
+export function listProcesses(): ProcInfo[] {
+ if (procfsCensus) {
+ return fs.readdirSync('/proc').flatMap(entry => {
+ const pid = Number(entry)
+ const info = Number.isInteger(pid) ? readProc(pid) : null
+
+ return info?.cmdline ? [{ pid, ppid: info.ppid, cmdline: info.cmdline }] : []
+ })
+ }
+
+ const listing =
+ process.platform === 'win32'
+ ? spawnSync(
+ 'powershell.exe',
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.CommandLine)" }'
+ ],
+ { encoding: 'utf8', timeout: 60_000, windowsHide: true }
+ ).stdout
+ : spawnSync('ps', ['-axww', '-o', 'pid=,ppid=,args='], { encoding: 'utf8', timeout: 30_000 }).stdout
+
+ return String(listing ?? '')
+ .split(/\r?\n/)
+ .flatMap(line => {
+ const match = process.platform === 'win32' ? /^(\d+)\t(\d+)\t(.*)$/.exec(line) : /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)
+
+ return match && match[3].trim() ? [{ pid: Number(match[1]), ppid: Number(match[2]), cmdline: match[3].trim() }] : []
+ })
+}
+
+const recordedRoots = new Map<string, Set<number>>()
+
+/** Gateway pids recorded in the sandbox's `gateway.lock` files (launch home + each profile home). */
+function lockedGatewayPids(hermesHome: string): number[] {
+ const profilesDir = path.join(hermesHome, 'profiles')
+ const homes = [hermesHome, ...(fs.existsSync(profilesDir) ? fs.readdirSync(profilesDir).map(name => path.join(profilesDir, name)) : [])]
+
+ return homes.flatMap(home => {
+ try {
+ const pid = Number(JSON.parse(fs.readFileSync(path.join(home, 'gateway.lock'), 'utf8'))?.pid)
+
+ return Number.isInteger(pid) && pid > 0 ? [pid] : []
+ } catch {
+ return []
+ }
+ })
+}
+
+/** Every live process belonging to the sandbox whose HERMES_HOME is `hermesHome` (orphans included). */
+export function sandboxProcessesOf(hermesHome: string, exclude = process.pid): ProcInfo[] {
+ if (procfsCensus) {
+ const needle = `HERMES_HOME=${hermesHome}\0`
+
+ return fs.readdirSync('/proc').flatMap(entry => {
+ const pid = Number(entry)
+ const info = Number.isInteger(pid) && pid !== exclude ? readProc(pid) : null
+
+ // Zombies have an empty cmdline and are already dead for our purposes.
+ return info?.cmdline && (info.environ + '\0').includes(needle) ? [{ pid, ppid: info.ppid, cmdline: info.cmdline }] : []
+ })
+ }
+
+ const roots = recordedRoots.get(hermesHome) ?? new Set<number>()
+ recordedRoots.set(hermesHome, roots)
+ const all = listProcesses()
+ const live = new Set(all.map(proc => proc.pid))
+
+ for (const pid of lockedGatewayPids(hermesHome)) {
+ if (live.has(pid)) {
+ roots.add(pid)
+ }
+ }
+
+ const members = new Set([...roots].filter(pid => live.has(pid)))
+ const parents = new Set(roots)
+
+ for (let grew = true; grew; ) {
+ grew = false
+
+ for (const proc of all) {
+ if (!parents.has(proc.pid) && parents.has(proc.ppid)) {
+ parents.add(proc.pid)
+ members.add(proc.pid)
+ grew = true
+ }
+ }
+ }
+
+ return all.filter(proc => members.has(proc.pid) && proc.pid !== exclude)
+}
+
+/** True while `pid` is still a live member of the sandbox (a recycled pid never matches). */
+export function isSandboxProcess(pid: number, hermesHome: string): boolean {
+ return sandboxProcessesOf(hermesHome).some(proc => proc.pid === pid)
+}
+
+/** Every live process whose command line carries `tag`. */
+export function processesTagged(tag: string): ProcInfo[] {
+ return listProcesses().filter(proc => proc.pid !== process.pid && proc.cmdline.includes(tag))
+}
+
+/** `value` single-quoted for the POSIX shell the terminal tool runs (Git Bash on Windows). */
+export function shellQuote(value: string): string {
+ const posix = process.platform === 'win32' ? value.replace(/^([A-Za-z]):[\\/]/, (_, d: string) => `/${d.toLowerCase()}/`).replace(/\\/g, '/') : value
+
+ return `'${posix.replace(/'/g, `'\\''`)}'`
+}
diff --git a/apps/desktop/e2e/core/process-census.unit.test.ts b/apps/desktop/e2e/core/process-census.unit.test.ts
new file mode 100644
index 00000000000..59a4fc2aaa2
--- /dev/null
+++ b/apps/desktop/e2e/core/process-census.unit.test.ts
@@ -0,0 +1,66 @@
+import { spawn, spawnSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import * as os from 'node:os'
+import * as path from 'node:path'
+
+import { afterEach, expect, test, vi } from 'vitest'
+
+afterEach(() => {
+ vi.unstubAllEnvs()
+ vi.resetModules()
+})
+
+// The terminal tool runs commands through a POSIX shell (bash; Git Bash on Windows).
+test.skipIf(process.platform === 'win32')('shellQuote keeps a path with spaces and quotes one argument', async () => {
+ const { shellQuote } = await import('./process-census')
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "core census o'k "))
+ const victim = path.join(dir, 'victim run')
+ fs.mkdirSync(victim)
+ const bystander = path.join(dir, 'victim')
+ fs.mkdirSync(bystander)
+
+ try {
+ expect(spawnSync('sh', ['-c', `rm -rf ${shellQuote(victim)}`]).status).toBe(0)
+ expect(fs.existsSync(victim)).toBe(false)
+ expect(fs.existsSync(bystander), 'an unquoted path split at the space would hit this').toBe(true)
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+})
+
+// Exercises the non-/proc census (Windows/macOS shape) through `ps`, on the same real processes.
+test.skipIf(process.platform === 'win32').each(['procfs', 'ps'])(
+ 'sandbox census finds the recorded gateway and its children, and drops them once gone (%s)',
+ async mode => {
+ if (mode === 'procfs' && !fs.existsSync('/proc/self/environ')) {
+ return
+ }
+
+ vi.stubEnv('HERMES_E2E_PROC_CENSUS', mode === 'ps' ? 'ps' : '')
+ const { sandboxProcessesOf, processesTagged } = await import('./process-census')
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'core census home '))
+ const tag = `core-census-${process.pid}-${mode}`
+ // A stand-in gateway whose child is tagged; the child's environment carries the home too.
+ const gateway = spawn('bash', ['-c', '(exec -a "$CORE_TAG" sleep 60) & wait'], {
+ env: { ...process.env, HERMES_HOME: home, CORE_TAG: tag },
+ stdio: 'ignore'
+ })
+ fs.writeFileSync(path.join(home, 'gateway.lock'), JSON.stringify({ pid: gateway.pid }))
+
+ try {
+ await expect.poll(() => processesTagged(tag).length).toBe(1)
+ const census = sandboxProcessesOf(home).map(proc => proc.pid)
+ expect(census).toContain(gateway.pid)
+ expect(census).toContain(processesTagged(tag)[0].pid)
+ expect(sandboxProcessesOf(path.join(home, 'other')).map(proc => proc.pid)).not.toContain(gateway.pid)
+ } finally {
+ for (const proc of processesTagged(tag)) {
+ process.kill(proc.pid, 'SIGKILL')
+ }
+
+ gateway.kill('SIGKILL')
+ await expect.poll(() => sandboxProcessesOf(home).length).toBe(0)
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+ }
+)
diff --git a/apps/desktop/e2e/core/reply-settle-paths.spec.ts b/apps/desktop/e2e/core/reply-settle-paths.spec.ts
index a03e364cd73..6ee236779fe 100644
--- a/apps/desktop/e2e/core/reply-settle-paths.spec.ts
+++ b/apps/desktop/e2e/core/reply-settle-paths.spec.ts
@@ -37,6 +37,7 @@ import {
type WsRecorder
} from './harness'
import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
+import { shellQuote } from './process-census'
import { gate, type ScriptedProvider, startScriptedProvider } from './provider'
// Review after every turn, so a review fork is in flight during the next one.
@@ -308,7 +309,7 @@ test('a steer at every point of a tool turn, then reload and switch back', async
toolCalls: [
{
name: 'terminal',
- args: { command: `touch ${ready}; while [ ! -e ${release} ]; do sleep 0.05; done; echo core-ran` }
+ args: { command: `touch ${shellQuote(ready)}; while [ ! -e ${shellQuote(release)} ]; do sleep 0.05; done; echo core-ran` }
}
]
},
diff --git a/apps/desktop/e2e/update/harness.ts b/apps/desktop/e2e/update/harness.ts
index 5537f810c2a..fbf64939feb 100644
--- a/apps/desktop/e2e/update/harness.ts
+++ b/apps/desktop/e2e/update/harness.ts
@@ -498,7 +498,8 @@ export function isAlive(pid: number): boolean {
try {
process.kill(pid, 0)
- return !/^\S+ \(.*\) Z /.test(readText(`/proc/${pid}/stat`))
+ // Zombie check needs procfs; elsewhere a signalable pid is alive.
+ return !fs.existsSync(`/proc/${pid}/stat`) || !/^\S+ \(.*\) Z /.test(readText(`/proc/${pid}/stat`))
} catch {
return false
}