The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
perf(cli): keystrokes never wait behind the core's probe spawns (#1361)
0xken15d311ef5a4333
diff --git a/cli/e2e/harness/ptyRoundTrip.py b/cli/e2e/harness/ptyRoundTrip.pynew file mode 100644index 000000000..7dcd92d70--- /dev/null+++ b/cli/e2e/harness/ptyRoundTrip.py@@ -0,0 +1,32 @@+"""Raw pty round trip: the floor for a typing measurement.++Runs argv[2:] on a fresh pty, writes one key at a time to its master and times the first byte back.+Prints the round trips in ms as a JSON list. No tmux, no daemon, no socket.+"""+import json, os, pty, select, sys, time++count = int(sys.argv[1])+pid, fd = pty.fork()+if pid == 0:+ os.execvp(sys.argv[2], sys.argv[2:])++def drain(seconds):+ end = time.monotonic() + seconds+ while True:+ ready, _, _ = select.select([fd], [], [], max(0, end - time.monotonic()))+ if not ready:+ return+ os.read(fd, 65536)++drain(1.5)+out = []+for i in range(count):+ started = time.perf_counter()+ os.write(fd, b'x' if i % 2 == 0 else b'\x7f')+ ready, _, _ = select.select([fd], [], [], 5)+ out.append(round((time.perf_counter() - started) * 1000, 3))+ if ready:+ os.read(fd, 65536)+ drain(0.015 + (i % 3) * 0.005)+os.write(fd, b'\x03')+print(json.dumps(out))diff --git a/cli/e2e/harness/typingEcho.mjs b/cli/e2e/harness/typingEcho.mjsnew file mode 100644index 000000000..163e0243d--- /dev/null+++ b/cli/e2e/harness/typingEcho.mjs@@ -0,0 +1,12 @@+// The engine side of a typing measurement: every key redraws the input line, as Claude Code's composer+// does, so an echo is a real redraw and not the kernel's line discipline. Ctrl+C ends it.+process.stdin.setRawMode(true)+let line = ''+process.stdout.write('\x1b[?2004h> ready\r\n')+process.stdin.on('data', (data) => {+ for (const c of data.toString()) {+ if (c === '\x03') process.exit(0)+ line = c === '\x7f' ? line.slice(0, -1) : line + c+ }+ process.stdout.write(`\r\x1b[0J\x1b[39m❯ ${line}\x1b[0m`)+})diff --git a/cli/e2e/typingLatency.e2e.ts b/cli/e2e/typingLatency.e2e.tsnew file mode 100644index 000000000..e018d140e--- /dev/null+++ b/cli/e2e/typingLatency.e2e.ts@@ -0,0 +1,188 @@+/**+ * TYPING=1: keystroke → echo latency at each hop, idle and under load, on an isolated daemon.+ * TYPING_REPORT=<file> writes JSON; TYPING_N=<keys per path> (default 150); TYPING_SAMPLE=1 (macOS) also+ * `sample`s the core's main thread for each daemon window, beside the report.+ *+ * Why it exists: a terminal stuttered while typing on a busy machine and the median said nothing. Each+ * condition times the same composer-like TUI four ways: on a raw pty (the floor), through a tmux control+ * client of our own (tmux's share), through the daemon as the desktop types (the core's share), and the+ * core's event-loop delay meanwhile (e2e/harness/corePerf.cjs). Run alone: the host's load is the noise.+ *+ * Lessons kept from the spike (2026-10-15): the load processes are spawned directly, since `sh -c 'yes …'`+ * orphans `yes` when killed; streams get `terminal_alive` every 5 s or they expire after 30 s; never+ * `--cpu-prof`, which profiles the fake engines too and slows everything it measures.+ */+import { execFile, spawn, type ChildProcess } from 'node:child_process'+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { cpus, loadavg } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { promisify } from 'node:util'+import { it } from 'vitest'+import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'++const exec = promisify(execFile)+const N = Number(process.env.TYPING_N ?? 150)+const HARNESS = join(CLI_ROOT, 'e2e', 'harness')+const sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms))+const gap = (i: number) => 15 + (i % 3) * 5+const key = (i: number) => (i % 2 === 0 ? 'x' : '\x7f')+type Stats = { n: number; p50: number; p90: number; p99: number; max: number }++function stats(values: number[]): Stats {+ const sorted = [...values].sort((a, b) => a - b)+ const at = (p: number) => +sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))].toFixed(2)+ return { n: sorted.length, p50: at(0.5), p90: at(0.9), p99: at(0.99), max: +sorted[sorted.length - 1].toFixed(2) }+}++async function rawPty(): Promise<number[]> {+ const { stdout } = await exec('python3', [join(HARNESS, 'ptyRoundTrip.py'), String(N), process.execPath, join(HARNESS, 'typingEcho.mjs')], { timeout: 120_000 })+ return JSON.parse(stdout)+}++/** Our own control client on `pane`: `send-keys -H`, then the first `%output` for that pane. */+async function tmuxDirect(d: IsolatedDaemon, pane: string): Promise<number[]> {+ const child = spawn('tmux', ['-S', d.tmux.socket, '-C', 'attach-session', '-f', 'ignore-size', '-t', pane], { env: d.tmux.env, stdio: ['pipe', 'pipe', 'ignore'] })+ let waiter: (() => void) | null = null+ let tail = ''+ child.stdout!.on('data', (chunk: Buffer) => {+ tail += chunk.toString('latin1')+ const lines = tail.split('\n')+ tail = lines.pop()!+ for (const line of lines) if (line.startsWith(`%output ${pane} `) && waiter) { const wake = waiter; waiter = null; wake() }+ })+ await sleep(800)+ const out: number[] = []+ for (let i = 0; i < N; i++) {+ const echoed = new Promise<void>((done) => { waiter = done })+ const started = performance.now()+ child.stdin!.write(`send-keys -t ${pane} -H ${Buffer.from(key(i)).toString('hex')}\n`)+ await Promise.race([echoed, sleep(5_000)])+ out.push(performance.now() - started)+ await sleep(gap(i))+ }+ child.stdin!.end()+ child.kill()+ return out+}++/** The desktop's path: an input frame over the local WS, the daemon, tmux, the engine, and back. */+async function daemonPath(client: LocalClient, streamId: string, firstSeq: number): Promise<number[]> {+ const out: number[] = []+ for (let i = 0; i < N; i++) {+ const echoed = client.waitForBinary((f) => f.streamId === streamId && f.kind === TerminalBinaryKind.output, 5_000, 'echo', client.binaries.length)+ const started = performance.now()+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: firstSeq + i, compressed: false, bytes: Buffer.from(key(i)) })+ const frame = await echoed+ out.push(performance.now() - started)+ client.send('terminal_ack', { streamId, lastSeq: frame.seq })+ await sleep(gap(i))+ }+ return out+}++async function createAgent(d: IsolatedDaemon, client: LocalClient, folder: string): Promise<Record<string, any>> {+ const cwd = join(d.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ return until(`${folder} active`, async () => {+ const rows = (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents+ const row = rows.find((r) => r.id === created.agent.id)+ return row?.sessionId && row.status === 'active' ? row : null+ }, 60_000, 500)+}++async function openTerminal(client: LocalClient, agentId: string): Promise<string> {+ const requestId = `open-${Math.random().toString(36).slice(2)}`+ const ready = client.next((f) => f.type === 'terminal_ready' && f.payload?.requestId === requestId, 30_000, 'terminal_ready')+ client.send('terminal_open', { requestId, protocolVersion: 3, agentId, cols: 120, rows: 40 })+ return (await ready).payload!.streamId as string+}++it.runIf(process.env.TYPING === '1')('typing latency by hop, idle and under load', async () => {+ const report = resolve(process.env.TYPING_REPORT ?? join(CLI_ROOT, '.typing-latency.json'))+ const perfDir = join(dirname(report), `typing-core-${Date.now()}`)+ mkdirSync(perfDir, { recursive: true })+ const token = `typing-${process.pid}-${Date.now()}`+ const d = await IsolatedDaemon.create({ env: {+ NODE_OPTIONS: `--require=${join(HARNESS, 'corePerf.cjs')}`, HARNESS_E2E_PERF_DIR: perfDir, HARNESS_E2E_PERF_TOKEN: token,+ } })+ const burners: ChildProcess[] = []+ const timers: NodeJS.Timeout[] = []+ try {+ await d.start()+ const corePid = await until('core pid', () => d.corePid() ?? null, 30_000, 200)+ const endpoint = await until('core probe', () => {+ try { return JSON.parse(readFileSync(join(perfDir, `core-${corePid}.json`), 'utf8')) as { port: number } } catch { return null }+ }, 30_000, 200)+ const probe = async (op: 'start' | 'end', label: string) => (await (await fetch(`http://127.0.0.1:${endpoint.port}/${op}`, {+ method: 'POST', headers: { 'x-harness-perf-token': token }, body: JSON.stringify({ label }),+ })).json()) as Record<string, any>++ const client = await LocalClient.connect(d)+ const target = await createAgent(d, client, 'target')+ const others = await Promise.all([1, 2, 3, 4].map((i) => createAgent(d, client, `other${i}`)))+ const streamId = await openTerminal(client, target.id)+ const otherStreams = await Promise.all(others.map((a) => openTerminal(client, a.id)))+ // A window acks what it drew every ~16 ms. Frames are dropped once acked: a flood would otherwise+ // pile up in this process's memory.+ timers.push(setInterval(() => {+ const last = new Map<string, number>()+ for (const f of client.binaries) last.set(f.streamId, f.seq)+ for (const s of otherStreams) if (last.has(s)) client.send('terminal_ack', { streamId: s, lastSeq: last.get(s)! })+ client.binaries.length = 0+ }, 16))+ timers.push(setInterval(() => { for (const s of [streamId, ...otherStreams]) client.send('terminal_alive', { streamId: s }) }, 5_000))+ await d.tmux.run('new-session', '-d', '-s', 'echo', '-x', '120', '-y', '40', `${process.execPath} ${join(HARNESS, 'typingEcho.mjs')}`)+ const echoPane = await d.tmux.run('display-message', '-p', '-t', 'echo', '#{pane_id}')++ const conditions: Record<string, Record<string, unknown>> = {}+ let seq = 0+ const measure = async (label: string) => {+ const loadBefore = loadavg()[0]+ const raw = stats(await rawPty())+ const tmux = stats(await tmuxDirect(d, echoPane))+ await probe('start', label)+ const sampled = process.env.TYPING_SAMPLE === '1' && process.platform === 'darwin'+ ? exec('sample', [String(corePid), '8', '-file', join(dirname(report), `typing-sample-${label}.txt`)], { timeout: 60_000 }).catch(() => null)+ : null+ const daemon = stats(await daemonPath(client, streamId, seq))+ seq += N+ await sampled+ const core = await probe('end', label)+ const flooding = !(await d.tmux.run('capture-pane', '-p', '-t', others[0].tmuxPane)).includes('flooded')+ conditions[label] = {+ rawPty: raw, tmuxDirect: tmux, daemon, loadAverage: [loadBefore, loadavg()[0]], flooding,+ core: { cpuPercent: core.cpu.percent, loopDelayP99Ms: core.eventLoop.p99Ms, loopDelayMaxMs: core.eventLoop.maxMs },+ }+ }+ const burn = () => { for (let i = 0; i < cpus().length; i++) burners.push(spawn('yes', [], { stdio: 'ignore' })) }+ const unburn = () => { for (const b of burners.splice(0)) b.kill() }++ await measure('idle')+ burn(); await sleep(1_000); await measure('cpu'); unburn(); await sleep(1_000)+ for (const a of others) client.send('message', { agentId: a.id, content: '!flood 409600' })+ await sleep(3_000)+ await measure('flood')+ burn(); await sleep(1_000); await measure('cpu-flood'); unburn()+ // The same floods with no window holding their panes: what showing no output for a hidden pane could+ // save at most (the floods go on in tmux, read by no control client of the daemon's).+ for (const s of otherStreams) client.send('terminal_close', { streamId: s })+ await sleep(1_500)+ await measure('flood-closed')+ burn(); await sleep(1_000); await measure('cpu-flood-closed'); unburn()++ writeFileSync(report, `${JSON.stringify({+ schema: 1, at: new Date().toISOString(), keysPerPath: N,+ machine: { cpus: cpus().length, model: cpus()[0]?.model, platform: process.platform },+ conditions,+ }, null, 2)}\n`)+ console.log(`typing latency report: ${report}`)+ client.close()+ } finally {+ for (const t of timers) clearInterval(t)+ for (const b of burners) b.kill()+ await d.close()+ }+}, 900_000)diff --git a/cli/src/core/agents/heldLaunches.spec.ts b/cli/src/core/agents/heldLaunches.spec.tsindex 1f923fd03..28c823cc8 100644--- a/cli/src/core/agents/heldLaunches.spec.ts+++ b/cli/src/core/agents/heldLaunches.spec.ts@@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process'import { afterEach, describe, expect, it, vi } from 'vitest'import type { AgentLaunch, RegisteredSession } from '../../lib/registry.js'import { heldLaunch, type RestoreSummary } from '../../lib/restoreAgents.js'-import { createHeldLaunches, heldFor, heldPaneArgv } from './heldLaunches.js'+import { createHeldLaunches, heldFor, heldPaneArgv, heldRetryMs } from './heldLaunches.js'const running: ReturnType<typeof createHeldLaunches>[] = []afterEach(() => { for (const held of running.splice(0)) held.close() })@@ -293,3 +293,63 @@ it('retries a held sibling while another agent’s observation has not settled',await pass} finally { vi.useRealTimers() }})++it('waits longer after each timer pass that launched nothing, up to half a minute', () => {+ expect([0, 1, 2, 3, 4, 5, 40].map(heldRetryMs)).toEqual([2_000, 4_000, 8_000, 16_000, 30_000, 30_000, 30_000])+})++it('backs off a hold nothing else wakes, and climbs again from the start once something changes', async () => {+ vi.useFakeTimers()+ try {+ const h = setup([row('a', heldLaunch('native'))], () => summary({ held: ['a'] }))+ await h.held.boot(async () => {})+ await h.held.restoreHeld()+ const passesAfter = async (ms: number) => { await vi.advanceTimersByTimeAsync(ms); return h.restore.mock.calls.length }+ // 2 s, 4 s, 8 s, 16 s, then every 30 s: a day of it is about 2,900 passes, not 43,000.+ expect(await passesAfter(1_999)).toBe(1)+ expect(await passesAfter(1)).toBe(2)+ expect(await passesAfter(4_000)).toBe(3)+ expect(await passesAfter(8_000)).toBe(4)+ expect(await passesAfter(16_000)).toBe(5)+ expect(await passesAfter(29_999)).toBe(5)+ expect(await passesAfter(1)).toBe(6)+ expect(await passesAfter(30_000)).toBe(7)+ // A service connecting is news: it is asked at once, the waiting pass keeps its time, and the one after+ // that is 4 s later again rather than 30.+ await h.held.restoreHeld('native')+ expect(h.restore).toHaveBeenCalledTimes(8)+ expect(await passesAfter(30_000)).toBe(9)+ expect(await passesAfter(3_999)).toBe(9)+ expect(await passesAfter(1)).toBe(10)+ } finally { vi.useRealTimers() }+})++it('climbs again from the start once a pass launches an agent, and when a person restarts a held one', async () => {+ vi.useFakeTimers()+ try {+ let launch = false+ const h = setup([row('a', heldLaunch('native')), row('b', heldLaunch('native'))],+ only => only.has('b') && launch ? summary({ restored: ['b'] }) : summary({ held: [...only] }))+ await h.held.boot(async () => {})+ await h.held.restoreHeld()+ await vi.advanceTimersByTimeAsync(2_000 + 4_000 + 8_000 + 16_000 + 30_000)+ const nextPass = async () => {+ const before = h.restore.mock.calls.length+ for (let ms = 1; ms <= 30_000; ms++) {+ await vi.advanceTimersByTimeAsync(1)+ if (h.restore.mock.calls.length > before) return ms+ }+ return null+ }+ launch = true+ expect(await nextPass()).toBe(30_000)+ expect(h.registry.get('b')?.launch?.state).toBe('starting')+ // The pass after the one that launched waits 4 s, not 30.+ expect(await nextPass()).not.toBeNull()+ expect(await nextPass()).toBe(4_000)+ await vi.advanceTimersByTimeAsync(8_000 + 16_000 + 30_000)+ expect(await h.held.restartHeld('a')).toMatchObject({ ok: false, error: 'SERVICE_UNAVAILABLE' })+ expect(await nextPass()).not.toBeNull()+ expect(await nextPass()).toBe(4_000)+ } finally { vi.useRealTimers() }+})diff --git a/cli/src/core/agents/heldLaunches.ts b/cli/src/core/agents/heldLaunches.tsindex 8c88c044a..0049c6107 100644--- a/cli/src/core/agents/heldLaunches.ts+++ b/cli/src/core/agents/heldLaunches.ts@@ -18,6 +18,12 @@ import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'import type { RestoreSummary } from '../../lib/restoreAgents.js'+/** How long a hold waits before the next timer pass: 2 s, doubling with each pass that launched nothing, at most+ * 30 s. An engine that becomes available is still picked up within half a minute without anyone asking. */+export function heldRetryMs(quietPasses: number): number {+ return Math.min(2_000 * 2 ** quietPasses, 30_000)+}+/** The service a row is held for, or null. */export function heldFor(row: Pick<RegisteredSession, 'launch'> | undefined): string | null {return row?.launch?.state === 'held' ? row.launch.service : null@@ -41,18 +47,25 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)// Closing revokes preparations already waiting on hooks or a service, too.const current = () => !closedlet retryTimer: ReturnType<typeof setTimeout> | undefined+ // Timer passes in a row that launched nothing. A hold nothing else wakes (native: an engine's search path that+ // cannot be confirmed) was retried every 2 s for good: measured 2026-10-15, one held Codex had been tried 27,491+ // times in a day, each pass running about four login shells (`zsh -lic`, the launch environment) from the core,+ // whose synchronous spawns held the event loop the terminals' keystrokes wait on.+ let quietPasses = 0const active = new Map<string, Promise<RestoreSummary>>()let nextAgent = 0const empty = (): RestoreSummary => ({ restored: [], skipped: [], failed: [], held: [], unsurveyed: [] })const retryContention = (summary: RestoreSummary): void => {+ if (summary.restored.length) quietPasses = 0if (closed || retryTimer || (!summary.retry && !summary.held.length)) returnretryTimer = setTimeout(() => {retryTimer = undefined+ if (!summary.retry) quietPasses++void restoreHeld(undefined, false).catch(error => {log(`[restore] core contention retry failed: ${String(error)}`)retryContention({ ...empty(), retry: true })})- }, summary.retry ? 500 : 2_000)+ }, summary.retry ? 500 : heldRetryMs(quietPasses))retryTimer.unref?.()}// One flight per agent, four across the core. A stalled native home or service@@ -82,6 +95,8 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)const restoreHeld = async (service?: string, joinRunning = true): Promise<RestoreSummary | null> => {await readyif (closed) return null+ // Asked from outside the timer (a service connected, the core became ready): something changed, so wait less.+ if (joinRunning) quietPasses = 0const held = registry.list().filter(row => {const holder = heldFor(row)return holder !== null && (service === undefined || holder === service) && (joinRunning || !active.has(row.agentId))@@ -115,6 +130,7 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)const before = registry.byAgent(agentId)if (!before || closed) return { ok: false, error: 'AGENT_NOT_FOUND' }if (!heldFor(before)) return { ok: true, session: before, resumed: !!before.sessionId }+ quietPasses = 0const summary = await restoreOne(agentId)retryContention(summary)const now = registry.byAgent(agentId)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 8e76bee02..839a999e3 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -44,6 +44,7 @@ import { isLocalOnly, withoutUpdate } from '../lib/cardUpdate.js'import { elapsedSecondsOf } from '../lib/footerTimer.js'import { sqlitePreflightMessage } from '../lib/sqliteAvailability.js'import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'+import { enableOffThreadExec } from '../lib/offThreadExec.js'import type { AppSwarms } from '../cable/cableSession.js'import type { UnreadNotification } from '../lib/notificationRead.js'import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from '../lib/registry.js'@@ -441,6 +442,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// move (it tears down two dozen subsystems declared further down). Until it is ready, a staged update is// applied by `bootHandoff`, which hands the machine over without finishing start-up.coreLink.onUpdate((version) => { void daemonBoot.applyStagedUpdate(version) })+ // The core's probes spawn from a worker, so a terminal's keystrokes never wait behind one (lib/offThreadExec.ts).+ enableOffThreadExec()// What the master told this core, read from here: runCore took it out of process.env before anything// could hand it to a child (lib/harnessdEnv.ts).const harnessd = harnessdEnv()diff --git a/cli/src/engines/kit/launchEnvironment.spec.ts b/cli/src/engines/kit/launchEnvironment.spec.tsindex 804bcce12..143403459 100644--- a/cli/src/engines/kit/launchEnvironment.spec.ts+++ b/cli/src/engines/kit/launchEnvironment.spec.ts@@ -1,6 +1,6 @@import { afterEach, expect, it, vi } from 'vitest'import { execFile } from 'node:child_process'-import { launchEnvironment } from './launchExecutable.js'+import { clearLaunchEnvironmentCache, launchEnvironment } from './launchExecutable.js'vi.mock('../../lib/engineLaunch.js', () => ({interactiveEngineShell: () => ({ path: '/fixture/login-shell', args: ['-ic'], label: 'fixture shell' }),@@ -13,7 +13,7 @@ vi.mock('node:child_process', () => ({ execFile: vi.fn((_file, _args, _options,})))return { stdin: { end: vi.fn() } }}) }))-afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks() })+afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); vi.useRealTimers(); clearLaunchEnvironmentCache() })it('captures the actual launch shell for an isolated daemon running with NODE_ENV=test', async () => {vi.stubEnv('NODE_ENV', 'test')@@ -22,3 +22,27 @@ it('captures the actual launch shell for an isolated daemon running with NODE_ENexpect(execFile).toHaveBeenCalledWith('/fixture/login-shell', expect.any(Array),expect.objectContaining({ timeout: 5_000, maxBuffer: 64 * 1024 }), expect.any(Function))})++it('answers a capture again for a few seconds, and joins one still running, instead of starting another login shell', async () => {+ vi.useFakeTimers()+ const [first, joined] = await Promise.all([launchEnvironment(), launchEnvironment()])+ expect(joined).toEqual(first)+ expect(execFile).toHaveBeenCalledOnce()+ // A caller's copy is its own: changing it never changes what the next caller is told.+ first!.PATH = '/changed'+ expect((await launchEnvironment())!.PATH).toBe('/fixture/bin')+ expect(execFile).toHaveBeenCalledOnce()+ vi.advanceTimersByTime(10_000)+ await launchEnvironment()+ expect(execFile).toHaveBeenCalledTimes(2)+})++it('never answers a failed capture again: the next ask runs the shell', async () => {+ vi.mocked(execFile).mockImplementationOnce(((_file: string, _args: string[], _options: unknown, done: (error: Error | null, output: string) => void) => {+ queueMicrotask(() => done(new Error('rc file failed'), ''))+ return { stdin: { end: vi.fn() } }+ }) as never)+ expect(await launchEnvironment()).toBeNull()+ expect(await launchEnvironment()).toMatchObject({ HOME: '/fixture/home' })+ expect(execFile).toHaveBeenCalledTimes(2)+})diff --git a/cli/src/engines/kit/launchExecutable.ts b/cli/src/engines/kit/launchExecutable.tsindex f33dccf5e..57c040d2a 100644--- a/cli/src/engines/kit/launchExecutable.ts+++ b/cli/src/engines/kit/launchExecutable.ts@@ -6,6 +6,7 @@ import { engineBin, enginePathOverride } from '../../lib/engineBin.js'import { engineInstallPaths, engineInstallRecipe, type EngineInstallRecipe } from '../../lib/engineInstall.js'import { engineShellArgv, interactiveEngineShell } from '../../lib/engineLaunch.js'import { managedNodePath } from '../../lib/nodeRuntime.js'+import { probeExecFile } from '../../lib/offThreadExec.js'import { shellSingleQuote } from '../../lib/shellQuote.js'import { LAUNCH_LOCATION_VARIABLES } from './nativeLocations.js'import type { AgentEngine } from '../types.js'@@ -25,19 +26,48 @@ const pickLocations = (environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv => Obj)let probing = 0const MAX_PROBES = 8+/** How long a captured launch environment answers again. Each capture is a login shell (rc files, then Node),+ * spawned synchronously from the core: a held launch's pass asked about four times, every pass (measured+ * 2026-10-15). A few seconds joins those; an rc file edited since is read on the next launch after it. */+const ENVIRONMENT_TTL_MS = 10_000+const captured = new Map<string, { at: number; environment: NodeJS.ProcessEnv }>()+const capturing = new Map<string, Promise<NodeJS.ProcessEnv | null>>()++/** Test seam. */+export function clearLaunchEnvironmentCache(): void {+ captured.clear()+ capturing.clear()+}/** No unavailable or negative shell answer is cached. A slot belongs to the- * actual child until its callback, including timeout/oversized-output kills. */+ * actual child until its callback, including timeout/oversized-output kills.+ * A capture still running is joined; one taken in the last ENVIRONMENT_TTL_MS is answered again. */export async function launchEnvironment(shell?: string): Promise<NodeJS.ProcessEnv | null> {const interactive = interactiveEngineShell(shell)if (!interactive) return pickLocations(process.env)+ // Keyed by the shell, not its argv: a shell that is not POSIX gets a one-time script file in its argv.+ const key = JSON.stringify([interactive.path, interactive.args, managedNodePath()])+ const hit = captured.get(key)+ if (hit && Date.now() - hit.at < ENVIRONMENT_TTL_MS) return { ...hit.environment }+ const running = capturing.get(key)+ if (running) return running.then(environment => environment && { ...environment })if (probing >= MAX_PROBES) return nullconst code = `process.stdout.write(${JSON.stringify(ENV_MARKER)}+JSON.stringify(Object.fromEntries(${JSON.stringify(LAUNCH_LOCATION_VARIABLES)}.filter(k=>process.env[k]!==undefined).map(k=>[k,process.env[k]]))))`const argv = engineShellArgv(interactive, [`exec ${shellSingleQuote(managedNodePath())} -e ${shellSingleQuote(code)}`, 'harness-launch-environment'])+ const capture = captureEnvironment(argv).then(environment => {+ capturing.delete(key)+ if (environment) captured.set(key, { at: Date.now(), environment })+ return environment+ })+ capturing.set(key, capture)+ return capture.then(environment => environment && { ...environment })+}++function captureEnvironment(argv: string[]): Promise<NodeJS.ProcessEnv | null> {probing++return new Promise(done => {try {- const child = execFile(argv[0], argv.slice(1), { encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }, (error, output) => {+ const child = probeExecFile(execFile)(argv[0], argv.slice(1), { timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }, (error, output) => {probing--if (error) { done(null); return }try {@@ -49,7 +79,7 @@ export async function launchEnvironment(shell?: string): Promise<NodeJS.ProcessEdone(pickLocations(value as NodeJS.ProcessEnv))} catch { done(null) }})- child.stdin?.end()+ child?.stdin?.end()} catch { probing--; done(null) }})}diff --git a/cli/src/lib/nativeProcessImages.ts b/cli/src/lib/nativeProcessImages.tsindex 4a83ecbb9..28be913b1 100644--- a/cli/src/lib/nativeProcessImages.ts+++ b/cli/src/lib/nativeProcessImages.ts@@ -1,4 +1,5 @@import { execFile } from 'node:child_process'+import { probeExecFile } from './offThreadExec.js'import { createHash, randomUUID } from 'node:crypto'import { constants } from 'node:fs'import { link, lstat, mkdir, open, unlink } from 'node:fs/promises'@@ -191,7 +192,7 @@ export async function nativeProcessImages(const remaining = Math.floor(deadline - performance.now())if (!helper || remaining <= 0) return emptyreturn await new Promise(resolve => {- execFile(helper.path, ['--paths', ...new Set(pids).values()].map(String),+ probeExecFile(execFile)(helper.path, ['--paths', ...new Set(pids).values()].map(String),{ timeout: remaining, maxBuffer: 4 * 1024 * 1024, env: psEnv() }, (error, stdout) => {const result = parseNativeProcessImages(stdout ?? '', new Set(pids))if (error && !result.images.size) {diff --git a/cli/src/lib/offThreadExec.spec.ts b/cli/src/lib/offThreadExec.spec.tsnew file mode 100644index 000000000..a427d720c--- /dev/null+++ b/cli/src/lib/offThreadExec.spec.ts@@ -0,0 +1,160 @@+import { execFile, execFileSync, spawn } from 'node:child_process'+import { fileURLToPath } from 'node:url'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ enableOffThreadExec, execFileOffThread, offThreadExecActive, probeExecFile, resetOffThreadExec,+ stopProbeWorkerForTest, type ProbeOptions,+} from './offThreadExec.js'+import { launchEnvironment, clearLaunchEnvironmentCache } from '../engines/kit/launchExecutable.js'+import { clearProcessEnvCache, readProcessEnv } from './processEnv.js'++// The real execFile, watched: a probe the route sends to the worker must never reach it on this thread.+// The worker's own child_process is its thread's, untouched by this mock.+vi.mock('node:child_process', async (importOriginal) => {+ const actual = await importOriginal<typeof import('node:child_process')>()+ return { ...actual, execFile: vi.fn(actual.execFile) }+})++afterEach(() => { resetOffThreadExec(); vi.unstubAllEnvs() })++const call = (file: string, args: string[], options: ProbeOptions = {}) =>+ new Promise<{ error: (Error & Record<string, unknown>) | null; stdout: string; stderr: string; killed?: boolean }>((resolve) => {+ const child = execFileOffThread(file, args, options, (error, stdout, stderr) =>+ resolve({ error: error as never, stdout, stderr, killed: child.killed }))+ })++describe('probes spawned from a worker thread', () => {+ it('answers what the child printed', async () => {+ expect(await call('echo', ['still here'])).toMatchObject({ error: null, stdout: 'still here\n', stderr: '' })+ })++ it('passes an exit code through with both outputs', async () => {+ const { error, stdout, stderr } = await call('sh', ['-c', 'echo out; echo err >&2; exit 3'])+ expect(error).toMatchObject({ code: 3 })+ expect([stdout, stderr]).toEqual(['out\n', 'err\n'])+ })++ it('reports a binary that does not exist as execFile does', async () => {+ expect((await call('/no/such/binary', [])).error).toMatchObject({ code: 'ENOENT' })+ })++ it('times a child out in the worker, killed with the signal asked for', async () => {+ const { error, killed } = await call('sleep', ['5'], { timeout: 100, killSignal: 'SIGKILL' })+ expect(error).toMatchObject({ killed: true, signal: 'SIGKILL' })+ expect(killed).toBe(true)+ })++ it('kills a child from the main thread', async () => {+ const answered = new Promise<Error | null>((resolve) => {+ const child = execFileOffThread('sleep', ['5'], {}, (error) => resolve(error))+ setTimeout(() => child.kill('SIGKILL'), 50)+ })+ expect(await answered).toMatchObject({ signal: 'SIGKILL' })+ })++ it('ends the child\'s stdin, so a probe that reads it finishes', async () => {+ // The launch-environment capture is an interactive login shell, which reads stdin.+ expect(await call('sh', ['-c', 'cat; echo done'], { timeout: 5_000 })).toMatchObject({ error: null, stdout: 'done\n' })+ })++ it('stops reading at maxBuffer, as execFile does', async () => {+ const { error } = await call('sh', ['-c', 'yes | head -c 5000'], { maxBuffer: 100 })+ expect(error).toMatchObject({ code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' })+ })++ it('runs the child in the environment the caller has now, not the one the worker started with', async () => {+ // The core prepends tmux's folder to PATH after it starts (tmuxOnPath.ts): a worker's own copy of+ // process.env, made at its start, would find another tmux.+ vi.stubEnv('HARNESS_PROBE_ENV', 'before')+ expect((await call('sh', ['-c', 'printf %s "$HARNESS_PROBE_ENV"'])).stdout).toBe('before')+ vi.stubEnv('HARNESS_PROBE_ENV', 'after')+ expect((await call('sh', ['-c', 'printf %s "$HARNESS_PROBE_ENV"'])).stdout).toBe('after')+ expect((await call('sh', ['-c', 'printf %s "$HARNESS_PROBE_ENV"'], { env: { HARNESS_PROBE_ENV: 'given' } })).stdout).toBe('given')+ })++ it('fails the calls in flight when the worker dies, and starts a new one for the next', async () => {+ const inFlight = call('sleep', ['5'])+ await new Promise((resolve) => setTimeout(resolve, 50))+ await stopProbeWorkerForTest()+ expect((await inFlight).error).toMatchObject({ code: 'EWORKER' })+ expect(await call('echo', ['again'])).toMatchObject({ error: null, stdout: 'again\n' })+ })++ it('keeps a process alive while a probe is in flight, as a child of its own would', () => {+ // Found by CI: a signed-out `harness start` awaited a probe with nothing else holding its loop yet, and+ // exited 0 mid-start, because the worker was unref'd even while it owed an answer.+ const module = fileURLToPath(new URL('./offThreadExec.ts', import.meta.url))+ const script = `import(${JSON.stringify(module)}).then(m => m.execFileOffThread('sh', ['-c', 'sleep 0.3; echo answered'], {}, (e, out) => process.stdout.write(out)))`+ expect(execFileSync(process.execPath, ['--import', 'tsx', '-e', script], { timeout: 10_000, encoding: 'utf8' })).toBe('answered\n')+ })++ it('lets a script that used it exit: the worker never keeps a process alive', () => {+ const module = fileURLToPath(new URL('./offThreadExec.ts', import.meta.url))+ const script = `import(${JSON.stringify(module)}).then(m => m.execFileOffThread('echo', ['x'], {}, () => {}))`+ // Throws if the process is still running after 10 s.+ execFileSync(process.execPath, ['--import', 'tsx', '-e', script], { timeout: 10_000 })+ })+})++describe('the route the core turns on', () => {+ it('is off until the core enables it, and probeExecFile calls the execFile it was given', () => {+ expect(offThreadExecActive()).toBe(false)+ const inThread = vi.fn((_f: string, _a: string[], _o: object, done: (...a: unknown[]) => void) => { done(null, 'mocked', ''); return { kill: () => true } })+ const done = vi.fn()+ probeExecFile(inThread)('ps', ['-ax'], { timeout: 10 }, done)+ expect(inThread).toHaveBeenCalledWith('ps', ['-ax'], { timeout: 10 }, done)+ expect(done).toHaveBeenCalledWith(null, 'mocked', '')+ })++ it('sends probes to the worker once enabled', async () => {+ enableOffThreadExec()+ expect(offThreadExecActive()).toBe(true)+ const inThread = vi.fn()+ const stdout = await new Promise<string>((resolve) => { probeExecFile(inThread)('echo', ['worker'], {}, (_e, out) => resolve(out)) })+ expect(stdout).toBe('worker\n')+ expect(inThread).not.toHaveBeenCalled()+ })++ it('falls back to the main thread for good after the worker dies twice in a minute', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ enableOffThreadExec()+ await call('echo', ['one'])+ await stopProbeWorkerForTest()+ await call('echo', ['two'])+ await stopProbeWorkerForTest()+ expect(offThreadExecActive()).toBe(false)+ expect(warn).toHaveBeenCalledOnce()+ const inThread = vi.fn()+ probeExecFile(inThread)('echo', [], {}, () => {})+ expect(inThread).toHaveBeenCalledOnce()+ })+})++describe('the probes that called execFile directly', () => {+ afterEach(() => { clearProcessEnvCache(); clearLaunchEnvironmentCache() })++ it.runIf(process.platform === 'darwin')('reads a process environment through the worker', async () => {+ enableOffThreadExec()+ // A Node child with a mark of its own: `ps eww` shows a process's environment as it started, and Apple's+ // platform binaries (sleep, sh) refuse to show theirs at all.+ const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 10_000)'], { env: { ...process.env, HARNESS_PROBE_MARK: 'marked' }, stdio: 'ignore' })+ try {+ const env = await readProcessEnv({ pid: child.pid!, startMarker: 'x', executable: process.execPath } as never)+ expect(env?.HARNESS_PROBE_MARK).toBe('marked')+ } finally { child.kill() }+ })++ it('captures the launch environment through the worker', async () => {+ enableOffThreadExec()+ const env = await launchEnvironment('/bin/sh')+ expect(env?.HOME).toBe(process.env.HOME)+ })++ it('does not spawn on this thread once the route is on', async () => {+ enableOffThreadExec()+ vi.mocked(execFile).mockClear()+ await launchEnvironment('/bin/sh')+ if (process.platform === 'darwin') await readProcessEnv({ pid: process.pid, startMarker: 'y', executable: process.execPath } as never)+ expect(execFile).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/offThreadExec.ts b/cli/src/lib/offThreadExec.tsnew file mode 100644index 000000000..3dbe8d619--- /dev/null+++ b/cli/src/lib/offThreadExec.ts@@ -0,0 +1,215 @@+/**+ * The core's short-lived probes (`ps`, `lsof`, `tmux` queries, the login-shell capture), spawned from a+ * worker thread.+ *+ * Node spawns a child synchronously on the thread that asks (`uv_spawn` → `posix_spawn`), and under CPU+ * contention one spawn takes tens of milliseconds. The core's terminals share its main thread: a keystroke+ * read from the local socket, and its echo written back, wait behind every probe spawned in between.+ * Measured 2026-10-15 on a 12-core Mac with 12 busy processes: ~60 % of the core main thread's non-idle+ * samples were inside `uv_spawn`, and a keystroke's echo took p99 62–101 ms through the daemon against+ * 12–28 ms through tmux alone (docs/plans/2026-10-15-keystrokes-off-spawn-path.md). From a worker, a+ * spawn holds only the worker.+ *+ * The child's timeout runs in the worker, as a patient deadline (see the worker's source). The main thread+ * keeps no timer, since a held loop fires a timer late, before it reads the answer waiting in the port+ * (patientExec.ts). The environment travels with every call: a worker's process.env is a copy made at its+ * start, and the core changes PATH after that (tmuxOnPath.ts).+ *+ * Only the core turns this on (`enableOffThreadExec`, core/main.ts). Everything else, and every unit test,+ * calls `execFile` on its own thread as before, so a test's mock of `node:child_process` still applies.+ */+import type { ExecFileException } from 'node:child_process'+import { Worker } from 'node:worker_threads'+import { HELD_MS, MAX_WINDOWS } from './patientExec.js'++export interface ProbeOptions {+ timeout?: number+ killSignal?: NodeJS.Signals+ maxBuffer?: number+ env?: NodeJS.ProcessEnv+ cwd?: string+}+/** `timedOut`: the worker killed the child for its timeout. Only the worker path reports it. */+export type ProbeDone = (error: ExecFileException | null, stdout: string, stderr: string, outcome?: { timedOut: boolean }) => void+export interface ProbeChild {+ kill(signal?: NodeJS.Signals): boolean+ readonly killed?: boolean+ stdin?: { end(): void } | null+}++interface Reply {+ id: number+ stdout: string+ stderr: string+ error: { message: string; code?: unknown; killed?: boolean; signal?: unknown; cmd?: string } | null+ timedOut: boolean+ killed: boolean+}++// CommonJS, evaluated in the worker: the lean bundle carries it as a string, with no file of its own.+// Nothing writes to a probe's stdin, so it is ended at once: an interactive shell that reads it then sees+// end-of-file, as the in-thread capture arranged with `child.stdin.end()`.+//+// The timeout is the worker's own patient deadline (patientExec.ts `patientDeadline`, the same rules), never+// Node's: the worker is held too, by its own synchronous spawns, and under a burst of probes Node's timer ran+// before the child's exit was read and reported an answered child as success with nothing in it (found in+// review, 2026-10-15). A late timer gets its window again; one on time kills from the check phase, after+// an answer that landed in the same instant has been read.+// Built when the worker starts, not at load: patientExec.ts imports this module, so its constants are not+// initialised yet while this one loads.+const workerSource = (): string => `+const { parentPort } = require('node:worker_threads')+const { execFile } = require('node:child_process')+const HELD_MS = ${HELD_MS}, MAX_WINDOWS = ${MAX_WINDOWS}+const deadline = (ms, expire) => {+ let cancelled = false, windows = 0, timer+ const arm = () => {+ windows+++ const due = performance.now() + ms+ timer = setTimeout(() => {+ if (performance.now() - due > HELD_MS && windows < MAX_WINDOWS) { arm(); return }+ setImmediate(() => { if (!cancelled) expire() })+ }, ms)+ }+ arm()+ return () => { cancelled = true; clearTimeout(timer) }+}+const children = new Map()+parentPort.on('message', (m) => {+ if (m.kill !== undefined) { const child = children.get(m.kill); if (child) child.kill(m.signal); return }+ const { timeout = 0, killSignal = 'SIGTERM', ...options } = m.options+ let child, timedOut = false, cancel = () => {}+ const reply = (error, stdout, stderr) => {+ cancel()+ children.delete(m.id)+ parentPort.postMessage({ id: m.id, stdout: String(stdout ?? ''), stderr: String(stderr ?? ''), timedOut,+ killed: Boolean(child && child.killed), error: error+ ? { message: error.message, code: error.code, killed: error.killed, signal: error.signal, cmd: error.cmd } : null })+ }+ try {+ child = execFile(m.file, m.args, options, reply)+ if (child.stdin) child.stdin.end()+ children.set(m.id, child)+ if (timeout > 0) cancel = deadline(timeout, () => { timedOut = true; child.kill(killSignal) })+ } catch (error) { reply(error, '', '') }+})+`++/** Two deaths this close together turn the route off for the rest of the process. */+const DEATH_WINDOW_MS = 60_000++let enabled = false+let fallen = false+let worker: Worker | null = null+let nextId = 0+type Pending = (error: ExecFileException | null, stdout: string, stderr: string, outcome: { timedOut: boolean; killed: boolean }) => void+const pending = new Map<number, Pending>()+const deaths: number[] = []++export function enableOffThreadExec(): void {+ enabled = true+}++export function offThreadExecActive(): boolean {+ return enabled && !fallen+}++/** Test seam: the route off, the worker gone, no death counted. */+export function resetOffThreadExec(): void {+ enabled = false+ fallen = false+ deaths.length = 0+ const stopping = worker+ worker = null+ failAll('the probe worker was reset')+ void stopping?.terminate()+}++/** Test seam: the worker ends as a crash would end it. */+export async function stopProbeWorkerForTest(): Promise<void> {+ const stopping = worker+ if (!stopping) return+ const exited = new Promise<void>((resolve) => stopping.once('exit', () => resolve()))+ await stopping.terminate()+ await exited+}++/**+ * The worker holds the process open exactly while it owes an answer. Found by CI (2026-10-15): unref'd+ * throughout, a signed-out `harness start` awaited a probe while nothing else held its loop yet and exited 0+ * in the middle of starting.+ */+function settle(): void {+ if (pending.size === 0) worker?.unref()+ else worker?.ref()+}++function failAll(reason: string): void {+ for (const [id, done] of [...pending]) {+ pending.delete(id)+ done(Object.assign(new Error(reason), { code: 'EWORKER' }) as ExecFileException, '', '', { timedOut: false, killed: false })+ }+}++function start(): Worker {+ const started = new Worker(workerSource(), { eval: true })+ started.on('message', (reply: Reply) => {+ const done = pending.get(reply.id)+ if (!done) return+ pending.delete(reply.id)+ settle()+ const error = reply.error ? Object.assign(new Error(reply.error.message), reply.error) as ExecFileException : null+ done(error, reply.stdout, reply.stderr, { timedOut: reply.timedOut, killed: reply.killed })+ })+ // An uncaught error in the worker ends it; `exit` follows and does the accounting.+ started.on('error', () => {})+ started.once('exit', () => {+ if (worker !== started) return+ worker = null+ failAll('the probe worker exited')+ const now = Date.now()+ deaths.push(now)+ while (deaths.length && now - deaths[0] > DEATH_WINDOW_MS) deaths.shift()+ if (deaths.length >= 2 && !fallen) {+ fallen = true+ console.warn('[probes] the probe worker exited twice within a minute; probes run on the main thread from now on')+ }+ })+ // Idle, the worker never keeps the process alive; a probe in flight does (`settle`), as a child spawned on+ // this thread would. After the listeners, since adding a 'message' listener refs the worker again+ // (measured on Node 23).+ started.unref()+ return started+}++export function execFileOffThread(file: string, args: readonly string[], options: ProbeOptions, done: ProbeDone): ProbeChild {+ const id = nextId+++ let killed = false+ pending.set(id, (error, stdout, stderr, outcome) => {+ // As ChildProcess.killed: true once the child was sent a signal, whoever sent it.+ killed = outcome.killed+ done(error, stdout, stderr, { timedOut: outcome.timedOut })+ })+ const target = worker ?? (worker = start())+ settle()+ target.postMessage({ id, file, args: [...args], options: { ...options, env: { ...(options.env ?? process.env) }, encoding: 'utf8' } })+ return {+ get killed() { return killed },+ kill(signal: NodeJS.Signals = 'SIGTERM') {+ if (!pending.has(id) || !worker) return false+ worker.postMessage({ kill: id, signal })+ return true+ },+ }+}++/**+ * `execFile` for a probe: the worker's when the core has turned it on, else `inThread` (the caller's own+ * `execFile`, passed in so a test's mock of `node:child_process` applies) with the same arguments.+ */+export function probeExecFile(inThread: (...args: any[]) => unknown) {+ return (file: string, args: readonly string[], options: ProbeOptions, done: ProbeDone): ProbeChild | undefined =>+ offThreadExecActive()+ ? execFileOffThread(file, args, options, done)+ : inThread(file, args, options, done) as ProbeChild | undefined+}diff --git a/cli/src/lib/patientExec.spec.ts b/cli/src/lib/patientExec.spec.tsindex e8d814fa4..2e2055e8f 100644--- a/cli/src/lib/patientExec.spec.ts+++ b/cli/src/lib/patientExec.spec.ts@@ -1,6 +1,7 @@import { execFile } from 'node:child_process'import { afterEach, describe, expect, it, vi } from 'vitest'import { HELD_MS, MAX_WINDOWS, patientDeadline, patientExec } from './patientExec.js'+import { enableOffThreadExec, resetOffThreadExec } from './offThreadExec.js'const hold = (ms: number) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }const run = patientExec(execFile)@@ -111,3 +112,51 @@ describe('a deadline that counts only running time', () => {expect(expire).toHaveBeenCalledTimes(1)})})++describe('the same contract, with the core\'s probes in their worker', () => {+ afterEach(() => { resetOffThreadExec() })++ it('reads an answer that arrived while this loop was held, and never runs the in-thread execFile', async () => {+ enableOffThreadExec()+ const inThread = vi.fn()+ const kept = new Promise<{ error: Error | null; stdout: string }>((resolve) => {+ patientExec(inThread)('echo', ['still here'], { timeout: 100 }, (error, stdout) => resolve({ error, stdout }))+ })+ setImmediate(() => hold(400))+ expect(await kept).toEqual({ error: null, stdout: 'still here\n' })+ expect(inThread).not.toHaveBeenCalled()+ })++ it('reports a timeout exactly as the in-thread path does', async () => {+ enableOffThreadExec()+ const error = await new Promise<Error | null>((resolve) => {+ patientExec(execFile)('sleep', ['5'], { timeout: 100 }, (e) => resolve(e))+ })+ expect(error).toMatchObject({ killed: true, code: 'ETIMEDOUT', signal: 'SIGTERM' })+ expect(error!.message).toBe('sleep did not answer within 100 ms')+ })++ it('never turns an answer into an empty success while the worker is busy spawning', async () => {+ // Found in review: with Node's own timeout in the worker, a burst of probes held the worker spawning+ // past a short probe's deadline; the timer then ran before the exit was read, and Node reported the+ // answered child as success with nothing in it: "no panes", the failure stall.e2e.ts exists for.+ enableOffThreadExec()+ await new Promise((resolve) => { patientExec(execFile)('true', [], {}, resolve) })+ for (let round = 0; round < 3; round++) {+ const answer = new Promise<{ error: (Error & { code?: unknown }) | null; stdout: string }>((resolve) => {+ patientExec(execFile)('sh', ['-c', 'echo answer'], { timeout: 100 }, (error, stdout) => resolve({ error, stdout }))+ })+ const burst = Array.from({ length: 150 }, () => new Promise((resolve) => { patientExec(execFile)('true', [], { timeout: 10_000 }, resolve) }))+ const { error, stdout } = await answer+ await Promise.all(burst)+ if (error) expect(error).toMatchObject({ code: 'ETIMEDOUT' })+ else expect(stdout).toBe('answer\n')+ }+ }, 30_000)++ it('passes a failure through as it is', async () => {+ enableOffThreadExec()+ const error = await new Promise<Error | null>((resolve) => { patientExec(execFile)('false', [], { timeout: 1_000 }, (e) => resolve(e)) })+ expect(error).toMatchObject({ code: 1 })+ })+})diff --git a/cli/src/lib/patientExec.ts b/cli/src/lib/patientExec.tsindex 994f72b95..891d60b3c 100644--- a/cli/src/lib/patientExec.ts+++ b/cli/src/lib/patientExec.ts@@ -16,6 +16,7 @@* timed out, as Node's does (`killed`, `signal`).*/import type { ExecFileException } from 'node:child_process'+import { execFileOffThread, offThreadExecActive } from './offThreadExec.js'/** A timer this much later than its due time was held up: the loop did not run meanwhile. */export const HELD_MS = 250@@ -55,6 +56,13 @@ export function patientDeadline(ms: number, expire: () => void, clock: () => num}}+/** The error a timed-out child is reported with, on either path: `tmuxBackend.ts` reads its shape. */+function timedOut(file: string, args: readonly string[], timeout: number, killSignal: NodeJS.Signals): ExecFileException {+ return Object.assign(new Error(`${file} did not answer within ${timeout} ms`), {+ killed: true, signal: killSignal, code: 'ETIMEDOUT', cmd: [file, ...args].join(' '),+ }) as ExecFileException+}+/*** Wrap a module's own `execFile` (passed in, so a test's mock of `child_process` still applies) as one* that takes the same arguments and calls back the same way, with the timeout above.@@ -62,25 +70,33 @@ export function patientDeadline(ms: number, expire: () => void, clock: () => numexport function patientExec(execFile: (...args: any[]) => unknown) {return (file: string, args: readonly string[], options: PatientExecOptions, done: ExecDone): void => {const { timeout = 0, killSignal = 'SIGTERM', ...rest } = options+ if (offThreadExecActive()) {+ // The worker's loop is not held when this one is: its own timeout is a real one, and an answer+ // waits in the port until this loop reads it (offThreadExec.ts). No deadline is armed here.+ execFileOffThread(file, args, { ...rest, timeout, killSignal }, (error, stdout, stderr, outcome) => {+ // As below: exit 0 is an answer even when the kill raced it.+ if (error && outcome?.timedOut) { done(timedOut(file, args, timeout, killSignal), stdout, stderr); return }+ done(error, stdout, stderr)+ })+ return+ }let finished = false- let timedOut = false+ let timedOutHere = falselet cancel = (): void => {}const child = execFile(file, [...args], { ...rest, encoding: 'utf8' }, (error: ExecFileException | null, stdout: string, stderr: string) => {finished = truecancel()// Exit 0 is an answer even when the kill raced it: unlike Node's own timeout, this one never// throws the output away.- if (error && timedOut) {- done(Object.assign(new Error(`${file} did not answer within ${timeout} ms`), {- killed: true, signal: killSignal, code: 'ETIMEDOUT', cmd: [file, ...args].join(' '),- }), stdout ?? '', stderr ?? '')+ if (error && timedOutHere) {+ done(timedOut(file, args, timeout, killSignal), stdout ?? '', stderr ?? '')return}done(error, stdout ?? '', stderr ?? '')}) as { kill?: (signal: NodeJS.Signals) => boolean } | undefinedif (timeout > 0 && !finished) {cancel = patientDeadline(timeout, () => {- timedOut = true+ timedOutHere = truechild?.kill?.(killSignal)})}diff --git a/cli/src/lib/processEnv.ts b/cli/src/lib/processEnv.tsindex 4b6be3ae1..2231b29e9 100644--- a/cli/src/lib/processEnv.ts+++ b/cli/src/lib/processEnv.ts@@ -12,6 +12,7 @@*/import { execFile } from 'node:child_process'+import { probeExecFile } from './offThreadExec.js'import { readFile } from 'node:fs/promises'import type { ProcessIdentity } from './registry.js'@@ -51,7 +52,7 @@ function read(pid: number): Promise<Record<string, string> | null> {return readFile(`/proc/${pid}/environ`, 'utf8').then(parseEnviron).catch(() => null)}return new Promise((resolve) => {- execFile('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {+ probeExecFile(execFile)('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {if (err && !stdout) { resolve(null); return }const env = parsePsEnviron(stdout)// NO variables at all is macOS refusing to show them, not a process that has none.diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.tsindex 66ca3b159..34d1c6769 100644--- a/cli/src/lib/tmux.ts+++ b/cli/src/lib/tmux.ts@@ -22,6 +22,7 @@ import { processStartTicks } from './processLiveness.js'import { nativeProcessImages } from './nativeProcessImages.js'import { neutralizePasteControls } from './pasteText.js'import { patientDeadline, patientExec } from './patientExec.js'+import { probeExecFile } from './offThreadExec.js'import { inTmuxRoom } from './tmuxControlGate.js'import { tmuxFeatures, type TmuxFeatures } from './tmuxVersion.js'import { processIdentityOf, sameProcessIdentity } from './terminalRuntime.js'@@ -382,7 +383,7 @@ function execText(command: string, args: string[], timeout: number): Promise<str// timeout, for a deadline shared across calls: `killed` without an error is that timeout throwing// away an answer that had arrived (patientExec.ts), so it is no answer, not an empty one.let child: { killed?: boolean } | undefined- child = execFile(command, args, { timeout }, (err, stdout) => resolve((err && !stdout) || child?.killed ? null : stdout))+ child = probeExecFile(execFile)(command, args, { timeout }, (err, stdout) => resolve((err && !stdout) || child?.killed ? null : stdout))})}diff --git a/docs/plans/2026-10-15-keystrokes-off-spawn-path-implementation.md b/docs/plans/2026-10-15-keystrokes-off-spawn-path-implementation.mdnew file mode 100644index 000000000..73b32c7c9--- /dev/null+++ b/docs/plans/2026-10-15-keystrokes-off-spawn-path-implementation.md@@ -0,0 +1,1200 @@+# Keystrokes Off the Spawn Path Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** The core's short-lived probe children (`ps`, `lsof`, `tmux` queries, the login-shell capture)+are spawned from a worker thread, so a terminal keystroke is never queued behind a synchronous+`posix_spawn` on the core's main thread.++**Architecture:**+- One `worker_threads` worker (inline source, `eval: true`) owns `child_process.execFile` for probes. It+ is started lazily and `unref()`ed.+- The main thread posts `{ id, file, args, options }` and gets back `{ id, error, stdout, stderr }`.+- `patientExec` and four direct `execFile` probes route through it when the core has turned the route on+ (`enableOffThreadExec()` in `runForeground`). Everywhere else (services, CLI commands, unit tests) the+ route stays off and behaviour is byte-for-byte today's.++**Tech Stack:** Node 22 (`node:worker_threads`, `node:child_process`), TypeScript, vitest; the cli e2e+harness (`cli/e2e/harness/*`).++**Spec:** `docs/plans/2026-10-15-keystrokes-off-spawn-path.md` (problem, measurements, options, design,+phases). Read it first.++## Global Constraints++- Do not commit, push or open a PR. Leave every change in the working tree; the owner commits. The+ "Checkpoint" steps below replace commits.+- Work in `cli/`. Run commands from `cli/` unless a step says otherwise.+- Comments say why, in plain sentences, naming the measurement or incident (cli/AGENTS.md rule 7).+- `src/core/**` and `src/services/**` stay at 100 % per-file coverage (`npm run test:core`).+ `src/core/main.ts` is exempt (wiring).+- Tests never touch the developer's real daemon (port 18473), real tmux server or real `~/.claude` /+ `~/.codex` (cli/AGENTS.md rule 6).+- The route is turned on only by the core's composition root. Unit tests must not turn it on except in+ `offThreadExec.spec.ts` and `patientExec.spec.ts`, which reset it in `afterEach`.+- Pre-existing failures on this machine are not this change's: compare any red against a clean worktree+ at the same base before investigating (17 known reds in `src/engines/**` and `src/services/searchProcess.spec.ts`+ on 2026-10-15).++## Review Focus++1. **`process.env.PATH` changed after the worker started** (the core prepends tmux's directory at start,+ `src/lib/tmuxOnPath.ts`). Expected: the child finds the same binary the main thread would. Pinned by+ Task 2's "env is the caller's, read per call" test.+2. **The core's loop held for seconds while a probe is in flight** (`e2e/stall.e2e.ts`). Expected: the+ answer that arrived is read, never reported as a timeout or an empty answer. Pinned by Task 3's+ held-loop test with the route on.+3. **The worker dies mid-call.** Expected: in-flight calls fail with `code: 'EWORKER'` (callers treat it+ like any failed probe: "could not ask"), the next call starts a new worker, and two deaths within 60 s+ fall back to in-thread for good. Pinned by Task 2.+4. **A probe that reads stdin** (the interactive login shell of the launch-environment capture).+ Expected: it sees end-of-file and finishes, as it does today with `child.stdin.end()`. Pinned by+ Task 2's stdin test.+5. **A timeout in `patientExec` with the route on.** Expected: the same error shape as today+ (`code: 'ETIMEDOUT'`, `killed: true`, `signal`, message `<file> did not answer within <n> ms`), since+ `tmuxBackend.ts` reads it. Pinned by Task 3.++---++## File Structure++| File | Responsibility |+|---|---|+| `cli/e2e/typingLatency.e2e.ts` (create) | Opt-in measurement: keystroke→echo latency by hop, idle and under load; JSON report |+| `cli/e2e/harness/typingEcho.mjs` (create) | A composer-like TUI that redraws its input line on every key |+| `cli/e2e/harness/ptyRoundTrip.py` (create) | Raw pty round trip for the same TUI, the floor every other path is compared to |+| `cli/src/lib/offThreadExec.ts` (create) | The probe worker, `execFileOffThread`, `probeExecFile`, enable/active/reset |+| `cli/src/lib/offThreadExec.spec.ts` (create) | Real-children tests of the worker route |+| `cli/src/lib/patientExec.ts` (modify) | Route to the worker when active; shared timeout error |+| `cli/src/lib/patientExec.spec.ts` (modify) | The same contract with the route on |+| `cli/src/lib/processEnv.ts` (modify) | `ps eww` through `probeExecFile` |+| `cli/src/lib/tmux.ts` (modify, `execText` ~378) | `lsof` through `probeExecFile` |+| `cli/src/lib/nativeProcessImages.ts` (modify, ~194) | The image helper through `probeExecFile` |+| `cli/src/engines/kit/launchExecutable.ts` (modify, `captureEnvironment`) | The login-shell capture through `probeExecFile` |+| `cli/src/core/main.ts` (modify, `runForeground` ~406) | `enableOffThreadExec()` |+| `docs/plans/2026-10-15-keystrokes-off-spawn-path.md` (modify) | The spawn inventory (Task 6) and results (Task 7) |++---++### Task 1: The typing-latency measurement (Phase 0)++**Files:**+- Create: `cli/e2e/harness/typingEcho.mjs`+- Create: `cli/e2e/harness/ptyRoundTrip.py`+- Create: `cli/e2e/typingLatency.e2e.ts`++**Interfaces:**+- Consumes: `IsolatedDaemon`, `until`, `CLI_ROOT` (`e2e/harness/daemon.ts`); `LocalClient` (`e2e/harness/client.ts`);+ `TerminalBinaryKind` (`src/lib/terminalBinary.ts`); the probe preload `e2e/harness/corePerf.cjs`+ (POST `/start` `{label}` and `/end` on the port it writes to `core-<pid>.json`).+- Produces: `TYPING=1 TYPING_REPORT=<file> npx vitest run --config vitest.e2e.config.ts e2e/typingLatency.e2e.ts`+ writing `{ machine, conditions: { [label]: { rawPty, tmuxDirect, daemon, core } } }`, each path+ `{ n, p50, p90, p99, max }` in ms. Task 7 compares two of these files.++- [ ] **Step 1: Write the composer-like TUI**++`cli/e2e/harness/typingEcho.mjs`:++```js+// The engine side of a typing measurement: every key redraws the input line, as Claude Code's composer+// does, so an echo is a real redraw and not the kernel's line discipline. Ctrl+C ends it.+process.stdin.setRawMode(true)+let line = ''+process.stdout.write('\x1b[?2004h> ready\r\n')+process.stdin.on('data', (data) => {+ for (const c of data.toString()) {+ if (c === '\x03') process.exit(0)+ line = c === '\x7f' ? line.slice(0, -1) : line + c+ }+ process.stdout.write(`\r\x1b[0J\x1b[39m❯ ${line}\x1b[0m`)+})+```++- [ ] **Step 2: Write the raw pty round trip**++`cli/e2e/harness/ptyRoundTrip.py`:++```python+"""Raw pty round trip: the floor for a typing measurement.++Runs argv[2:] on a fresh pty, writes one key at a time to its master and times the first byte back.+Prints the round trips in ms as a JSON list. No tmux, no daemon, no socket.+"""+import json, os, pty, select, sys, time++count = int(sys.argv[1])+pid, fd = pty.fork()+if pid == 0:+ os.execvp(sys.argv[2], sys.argv[2:])++def drain(seconds):+ end = time.monotonic() + seconds+ while True:+ ready, _, _ = select.select([fd], [], [], max(0, end - time.monotonic()))+ if not ready:+ return+ os.read(fd, 65536)++drain(1.5)+out = []+for i in range(count):+ started = time.perf_counter()+ os.write(fd, b'x' if i % 2 == 0 else b'\x7f')+ ready, _, _ = select.select([fd], [], [], 5)+ out.append(round((time.perf_counter() - started) * 1000, 3))+ if ready:+ os.read(fd, 65536)+ drain(0.015 + (i % 3) * 0.005)+os.write(fd, b'\x03')+print(json.dumps(out))+```++- [ ] **Step 3: Write the e2e**++`cli/e2e/typingLatency.e2e.ts`:++```ts+/**+ * TYPING=1: keystroke → echo latency at each hop, idle and under load, on an isolated daemon.+ * TYPING_REPORT=<file> writes JSON; TYPING_N=<keys per path> (default 150); TYPING_SAMPLE=1 (macOS) also+ * `sample`s the core's main thread for each daemon window, beside the report.+ *+ * Why it exists: a terminal stuttered while typing on a busy machine and the median said nothing. Each+ * condition times the same composer-like TUI four ways: on a raw pty (the floor), through a tmux control+ * client of our own (tmux's share), through the daemon as the desktop types (the core's share), and the+ * core's event-loop delay meanwhile (e2e/harness/corePerf.cjs). Run alone: the host's load is the noise.+ *+ * Lessons kept from the spike (2026-10-15): the load processes are spawned directly, since `sh -c 'yes …'`+ * orphans `yes` when killed; streams get `terminal_alive` every 5 s or they expire after 30 s; never+ * `--cpu-prof`, which profiles the fake engines too and slows everything it measures.+ */+import { execFile, spawn, type ChildProcess } from 'node:child_process'+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { cpus, loadavg } from 'node:os'+import { dirname, join, resolve } from 'node:path'+import { promisify } from 'node:util'+import { it } from 'vitest'+import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'++const exec = promisify(execFile)+const N = Number(process.env.TYPING_N ?? 150)+const HARNESS = join(CLI_ROOT, 'e2e', 'harness')+const sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms))+const gap = (i: number) => 15 + (i % 3) * 5+const key = (i: number) => (i % 2 === 0 ? 'x' : '\x7f')+type Stats = { n: number; p50: number; p90: number; p99: number; max: number }++function stats(values: number[]): Stats {+ const sorted = [...values].sort((a, b) => a - b)+ const at = (p: number) => +sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))].toFixed(2)+ return { n: sorted.length, p50: at(0.5), p90: at(0.9), p99: at(0.99), max: +sorted[sorted.length - 1].toFixed(2) }+}++async function rawPty(): Promise<number[]> {+ const { stdout } = await exec('python3', [join(HARNESS, 'ptyRoundTrip.py'), String(N), process.execPath, join(HARNESS, 'typingEcho.mjs')], { timeout: 120_000 })+ return JSON.parse(stdout)+}++/** Our own control client on `pane`: `send-keys -H`, then the first `%output` for that pane. */+async function tmuxDirect(d: IsolatedDaemon, pane: string): Promise<number[]> {+ const child = spawn('tmux', ['-S', d.tmux.socket, '-C', 'attach-session', '-f', 'ignore-size', '-t', pane], { env: d.tmux.env, stdio: ['pipe', 'pipe', 'ignore'] })+ let waiter: (() => void) | null = null+ let tail = ''+ child.stdout!.on('data', (chunk: Buffer) => {+ tail += chunk.toString('latin1')+ const lines = tail.split('\n')+ tail = lines.pop()!+ for (const line of lines) if (line.startsWith(`%output ${pane} `) && waiter) { const wake = waiter; waiter = null; wake() }+ })+ await sleep(800)+ const out: number[] = []+ for (let i = 0; i < N; i++) {+ const echoed = new Promise<void>((done) => { waiter = done })+ const started = performance.now()+ child.stdin!.write(`send-keys -t ${pane} -H ${Buffer.from(key(i)).toString('hex')}\n`)+ await Promise.race([echoed, sleep(5_000)])+ out.push(performance.now() - started)+ await sleep(gap(i))+ }+ child.stdin!.end()+ child.kill()+ return out+}++/** The desktop's path: an input frame over the local WS, the daemon, tmux, the engine, and back. */+async function daemonPath(client: LocalClient, streamId: string, firstSeq: number): Promise<number[]> {+ const out: number[] = []+ for (let i = 0; i < N; i++) {+ const echoed = client.waitForBinary((f) => f.streamId === streamId && f.kind === TerminalBinaryKind.output, 5_000, 'echo', client.binaries.length)+ const started = performance.now()+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: firstSeq + i, compressed: false, bytes: Buffer.from(key(i)) })+ const frame = await echoed+ out.push(performance.now() - started)+ client.send('terminal_ack', { streamId, lastSeq: frame.seq })+ await sleep(gap(i))+ }+ return out+}++async function createAgent(d: IsolatedDaemon, client: LocalClient, folder: string): Promise<Record<string, any>> {+ const cwd = join(d.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ return until(`${folder} active`, async () => {+ const rows = (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents+ const row = rows.find((r) => r.id === created.agent.id)+ return row?.sessionId && row.status === 'active' ? row : null+ }, 60_000, 500)+}++async function openTerminal(client: LocalClient, agentId: string): Promise<string> {+ const requestId = `open-${Math.random().toString(36).slice(2)}`+ const ready = client.next((f) => f.type === 'terminal_ready' && f.payload?.requestId === requestId, 30_000, 'terminal_ready')+ client.send('terminal_open', { requestId, protocolVersion: 3, agentId, cols: 120, rows: 40 })+ return (await ready).payload!.streamId as string+}++it.runIf(process.env.TYPING === '1')('typing latency by hop, idle and under load', async () => {+ const report = resolve(process.env.TYPING_REPORT ?? join(CLI_ROOT, '.typing-latency.json'))+ const perfDir = join(dirname(report), `typing-core-${Date.now()}`)+ mkdirSync(perfDir, { recursive: true })+ const token = `typing-${process.pid}-${Date.now()}`+ const d = await IsolatedDaemon.create({ env: {+ NODE_OPTIONS: `--require=${join(HARNESS, 'corePerf.cjs')}`, HARNESS_E2E_PERF_DIR: perfDir, HARNESS_E2E_PERF_TOKEN: token,+ } })+ const burners: ChildProcess[] = []+ const timers: NodeJS.Timeout[] = []+ try {+ await d.start()+ const corePid = await until('core pid', () => d.corePid() ?? null, 30_000, 200)+ const endpoint = await until('core probe', () => {+ try { return JSON.parse(readFileSync(join(perfDir, `core-${corePid}.json`), 'utf8')) as { port: number } } catch { return null }+ }, 30_000, 200)+ const probe = async (op: 'start' | 'end', label: string) => (await (await fetch(`http://127.0.0.1:${endpoint.port}/${op}`, {+ method: 'POST', headers: { 'x-harness-perf-token': token }, body: JSON.stringify({ label }),+ })).json()) as Record<string, any>++ const client = await LocalClient.connect(d)+ const target = await createAgent(d, client, 'target')+ const others = await Promise.all([1, 2, 3, 4].map((i) => createAgent(d, client, `other${i}`)))+ const streamId = await openTerminal(client, target.id)+ const otherStreams = await Promise.all(others.map((a) => openTerminal(client, a.id)))+ // A window acks what it drew every ~16 ms. Frames are dropped once acked: a flood would otherwise+ // pile up in this process's memory.+ timers.push(setInterval(() => {+ const last = new Map<string, number>()+ for (const f of client.binaries) last.set(f.streamId, f.seq)+ for (const s of otherStreams) if (last.has(s)) client.send('terminal_ack', { streamId: s, lastSeq: last.get(s)! })+ client.binaries.length = 0+ }, 16))+ timers.push(setInterval(() => { for (const s of [streamId, ...otherStreams]) client.send('terminal_alive', { streamId: s }) }, 5_000))+ await d.tmux.run('new-session', '-d', '-s', 'echo', '-x', '120', '-y', '40', `${process.execPath} ${join(HARNESS, 'typingEcho.mjs')}`)+ const echoPane = await d.tmux.run('display-message', '-p', '-t', 'echo', '#{pane_id}')++ const conditions: Record<string, Record<string, unknown>> = {}+ let seq = 0+ const measure = async (label: string) => {+ const loadBefore = loadavg()[0]+ const raw = stats(await rawPty())+ const tmux = stats(await tmuxDirect(d, echoPane))+ await probe('start', label)+ const sampled = process.env.TYPING_SAMPLE === '1' && process.platform === 'darwin'+ ? exec('sample', [String(corePid), '8', '-file', join(dirname(report), `typing-sample-${label}.txt`)], { timeout: 60_000 }).catch(() => null)+ : null+ const daemon = stats(await daemonPath(client, streamId, seq))+ seq += N+ await sampled+ const core = await probe('end', label)+ conditions[label] = {+ rawPty: raw, tmuxDirect: tmux, daemon, loadAverage: [loadBefore, loadavg()[0]],+ core: { cpuPercent: core.cpu.percent, loopDelayP99Ms: core.eventLoop.p99Ms, loopDelayMaxMs: core.eventLoop.maxMs },+ }+ }+ const burn = () => { for (let i = 0; i < cpus().length; i++) burners.push(spawn('yes', [], { stdio: 'ignore' })) }+ const unburn = () => { for (const b of burners.splice(0)) b.kill() }++ await measure('idle')+ burn(); await sleep(1_000); await measure('cpu'); unburn(); await sleep(1_000)+ for (const a of others) client.send('message', { agentId: a.id, content: '!flood 409600' })+ await sleep(3_000)+ await measure('flood')+ burn(); await sleep(1_000); await measure('cpu-flood'); unburn()++ writeFileSync(report, `${JSON.stringify({+ schema: 1, at: new Date().toISOString(), keysPerPath: N,+ machine: { cpus: cpus().length, model: cpus()[0]?.model, platform: process.platform },+ conditions,+ }, null, 2)}\n`)+ console.log(`typing latency report: ${report}`)+ client.close()+ } finally {+ for (const t of timers) clearInterval(t)+ for (const b of burners) b.kill()+ await d.close()+ }+}, 900_000)+```++- [ ] **Step 4: Run it and check its output is sane**++Run (from `cli/`):+`TYPING=1 TYPING_REPORT=/tmp/typing-base-1.json npx vitest run --config vitest.e2e.config.ts e2e/typingLatency.e2e.ts`++Expected:+- The run passes in about 2–3 minutes.+- `/tmp/typing-base-1.json` has 4 conditions. Each has `rawPty`, `tmuxDirect` and `daemon` with `n: 150`.+- `idle.daemon.p50` is under 2 ms. `cpu.daemon.p99` is well above `cpu.tmuxDirect.p99` (on the reference+ Mac: 62–101 ms against 12–28 ms).+- Afterwards, `ps -Ao command | awk '$1=="yes"' | wc -l` prints `0`.++- [ ] **Step 5: Confirm the default suite skips it**++Run: `npx vitest run --config vitest.e2e.config.ts e2e/typingLatency.e2e.ts`+Expected: 1 skipped, no daemon started.++- [ ] **Step 6: Record the baseline**++Before any other task touches the code, run Step 4 three times with+`TYPING_SAMPLE=1 TYPING_REPORT=/tmp/typing-base-{1,2,3}.json`. Keep the files; Task 7 compares against them.++- [ ] **Step 7: Checkpoint**++Run: `git status --short` (from the repo root)+Expected: the three new files, nothing else from this task.++---++### Task 2: The off-thread exec++**Files:**+- Create: `cli/src/lib/offThreadExec.ts`+- Test: `cli/src/lib/offThreadExec.spec.ts`++**Interfaces:**+- Consumes: nothing from other tasks.+- Produces (exact exports):+ - `interface ProbeOptions { timeout?: number; killSignal?: NodeJS.Signals; maxBuffer?: number; env?: NodeJS.ProcessEnv; cwd?: string }`+ - `type ProbeDone = (error: ExecFileException | null, stdout: string, stderr: string) => void`+ - `interface ProbeChild { kill(signal?: NodeJS.Signals): boolean; readonly killed?: boolean; stdin?: { end(): void } | null }`+ - `function execFileOffThread(file: string, args: readonly string[], options: ProbeOptions, done: ProbeDone): ProbeChild`+ - `function probeExecFile(inThread: (...args: any[]) => unknown): (file: string, args: readonly string[], options: ProbeOptions, done: ProbeDone) => ProbeChild | undefined`+ - `function enableOffThreadExec(): void`+ - `function offThreadExecActive(): boolean`+ - `function resetOffThreadExec(): void`: test seam; turns the route off and drops the worker without counting a death.+ - `function stopProbeWorkerForTest(): Promise<void>`: test seam; terminates the worker as a death would.++- [ ] **Step 1: Write the failing tests**++`cli/src/lib/offThreadExec.spec.ts`:++```ts+import { execFileSync } from 'node:child_process'+import { fileURLToPath } from 'node:url'+import { afterEach, describe, expect, it, vi } from 'vitest'+import {+ enableOffThreadExec, execFileOffThread, offThreadExecActive, probeExecFile, resetOffThreadExec,+ stopProbeWorkerForTest, type ProbeOptions,+} from './offThreadExec.js'++afterEach(() => { resetOffThreadExec(); vi.unstubAllEnvs() })++const call = (file: string, args: string[], options: ProbeOptions = {}) =>+ new Promise<{ error: (Error & Record<string, unknown>) | null; stdout: string; stderr: string; killed?: boolean }>((resolve) => {+ const child = execFileOffThread(file, args, options, (error, stdout, stderr) =>+ resolve({ error: error as never, stdout, stderr, killed: child.killed }))+ })++describe('probes spawned from a worker thread', () => {+ it('answers what the child printed', async () => {+ expect(await call('echo', ['still here'])).toMatchObject({ error: null, stdout: 'still here\n', stderr: '' })+ })++ it('passes an exit code through with both outputs', async () => {+ const { error, stdout, stderr } = await call('sh', ['-c', 'echo out; echo err >&2; exit 3'])+ expect(error).toMatchObject({ code: 3 })+ expect([stdout, stderr]).toEqual(['out\n', 'err\n'])+ })++ it('reports a binary that does not exist as execFile does', async () => {+ expect((await call('/no/such/binary', [])).error).toMatchObject({ code: 'ENOENT' })+ })++ it('times a child out in the worker, killed with the signal asked for', async () => {+ const { error, killed } = await call('sleep', ['5'], { timeout: 100, killSignal: 'SIGKILL' })+ expect(error).toMatchObject({ killed: true, signal: 'SIGKILL' })+ expect(killed).toBe(true)+ })++ it('kills a child from the main thread', async () => {+ const answered = new Promise<Error | null>((resolve) => {+ const child = execFileOffThread('sleep', ['5'], {}, (error) => resolve(error))+ setTimeout(() => child.kill('SIGKILL'), 50)+ })+ expect(await answered).toMatchObject({ signal: 'SIGKILL' })+ })++ it('ends the child\'s stdin, so a probe that reads it finishes', async () => {+ // The launch-environment capture is an interactive login shell, which reads stdin.+ expect(await call('sh', ['-c', 'cat; echo done'], { timeout: 5_000 })).toMatchObject({ error: null, stdout: 'done\n' })+ })++ it('stops reading at maxBuffer, as execFile does', async () => {+ const { error } = await call('sh', ['-c', 'yes | head -c 5000'], { maxBuffer: 100 })+ expect(error).toMatchObject({ code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' })+ })++ it('runs the child in the environment the caller has now, not the one the worker started with', async () => {+ // The core prepends tmux's folder to PATH after it starts (tmuxOnPath.ts): a worker's own copy of+ // process.env, made at its start, would find another tmux.+ vi.stubEnv('HARNESS_PROBE_ENV', 'before')+ expect((await call('sh', ['-c', 'printf %s "$HARNESS_PROBE_ENV"'])).stdout).toBe('before')+ vi.stubEnv('HARNESS_PROBE_ENV', 'after')+ expect((await call('sh', ['-c', 'printf %s "$HARNESS_PROBE_ENV"'])).stdout).toBe('after')+ expect((await call('sh', ['-c', 'printf %s "$HARNESS_PROBE_ENV"'], { env: { HARNESS_PROBE_ENV: 'given' } })).stdout).toBe('given')+ })++ it('fails the calls in flight when the worker dies, and starts a new one for the next', async () => {+ const inFlight = call('sleep', ['5'])+ await new Promise((resolve) => setTimeout(resolve, 50))+ await stopProbeWorkerForTest()+ expect((await inFlight).error).toMatchObject({ code: 'EWORKER' })+ expect(await call('echo', ['again'])).toMatchObject({ error: null, stdout: 'again\n' })+ })++ it('lets a script that used it exit: the worker never keeps a process alive', () => {+ const module = fileURLToPath(new URL('./offThreadExec.ts', import.meta.url))+ const script = `import(${JSON.stringify(module)}).then(m => m.execFileOffThread('echo', ['x'], {}, () => {}))`+ // Throws if the process is still running after 10 s.+ execFileSync(process.execPath, ['--import', 'tsx', '-e', script], { timeout: 10_000 })+ })+})++describe('the route the core turns on', () => {+ it('is off until the core enables it, and probeExecFile calls the execFile it was given', () => {+ expect(offThreadExecActive()).toBe(false)+ const inThread = vi.fn((_f: string, _a: string[], _o: object, done: (...a: unknown[]) => void) => { done(null, 'mocked', ''); return { kill: () => true } })+ const done = vi.fn()+ probeExecFile(inThread)('ps', ['-ax'], { timeout: 10 }, done)+ expect(inThread).toHaveBeenCalledWith('ps', ['-ax'], { timeout: 10 }, done)+ expect(done).toHaveBeenCalledWith(null, 'mocked', '')+ })++ it('sends probes to the worker once enabled', async () => {+ enableOffThreadExec()+ expect(offThreadExecActive()).toBe(true)+ const inThread = vi.fn()+ const stdout = await new Promise<string>((resolve) => { probeExecFile(inThread)('echo', ['worker'], {}, (_e, out) => resolve(out)) })+ expect(stdout).toBe('worker\n')+ expect(inThread).not.toHaveBeenCalled()+ })++ it('falls back to the main thread for good after the worker dies twice in a minute', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ enableOffThreadExec()+ await call('echo', ['one'])+ await stopProbeWorkerForTest()+ await call('echo', ['two'])+ await stopProbeWorkerForTest()+ expect(offThreadExecActive()).toBe(false)+ expect(warn).toHaveBeenCalledOnce()+ const inThread = vi.fn()+ probeExecFile(inThread)('echo', [], {}, () => {})+ expect(inThread).toHaveBeenCalledOnce()+ })+})+```++- [ ] **Step 2: Run them to see them fail**++Run: `npx vitest run src/lib/offThreadExec.spec.ts`+Expected: FAIL. The module `./offThreadExec.js` does not exist.++- [ ] **Step 3: Write the module**++`cli/src/lib/offThreadExec.ts`:++```ts+/**+ * The core's short-lived probes (`ps`, `lsof`, `tmux` queries, the login-shell capture), spawned from a+ * worker thread.+ *+ * Node spawns a child synchronously on the thread that asks (`uv_spawn` → `posix_spawn`), and under CPU+ * contention one spawn takes tens of milliseconds. The core's terminals share its main thread: a keystroke+ * read from the local socket, and its echo written back, wait behind every probe spawned in between.+ * Measured 2026-10-15 on a 12-core Mac with 12 busy processes: ~60 % of the core main thread's non-idle+ * samples were inside `uv_spawn`, and a keystroke's echo took p99 62–101 ms through the daemon against+ * 12–28 ms through tmux alone (docs/plans/2026-10-15-keystrokes-off-spawn-path.md). From a worker, a+ * spawn holds only the worker.+ *+ * The child's timeout runs in the worker. Its loop is not held when the core's is, so a timeout there is+ * real; the main thread keeps no timer, since a held loop fires a timer late, before it reads the answer+ * waiting in the port (patientExec.ts). The environment travels with every call: a worker's process.env+ * is a copy made at its start, and the core changes PATH after that (tmuxOnPath.ts).+ *+ * Only the core turns this on (`enableOffThreadExec`, core/main.ts). Everything else, and every unit test,+ * calls `execFile` on its own thread as before, so a test's mock of `node:child_process` still applies.+ */+import type { ExecFileException } from 'node:child_process'+import { Worker } from 'node:worker_threads'++export interface ProbeOptions {+ timeout?: number+ killSignal?: NodeJS.Signals+ maxBuffer?: number+ env?: NodeJS.ProcessEnv+ cwd?: string+}+export type ProbeDone = (error: ExecFileException | null, stdout: string, stderr: string) => void+export interface ProbeChild {+ kill(signal?: NodeJS.Signals): boolean+ readonly killed?: boolean+ stdin?: { end(): void } | null+}++interface Reply {+ id: number+ stdout: string+ stderr: string+ error: { message: string; code?: unknown; killed?: boolean; signal?: unknown; cmd?: string } | null+}++// CommonJS, evaluated in the worker: the lean bundle carries it as a string, with no file of its own.+// Nothing writes to a probe's stdin, so it is ended at once: an interactive shell that reads it then sees+// end-of-file, as the in-thread capture arranged with `child.stdin.end()`.+const WORKER_SOURCE = `+const { parentPort } = require('node:worker_threads')+const { execFile } = require('node:child_process')+const children = new Map()+parentPort.on('message', (m) => {+ if (m.kill !== undefined) { const child = children.get(m.kill); if (child) child.kill(m.signal); return }+ const reply = (error, stdout, stderr) => {+ children.delete(m.id)+ parentPort.postMessage({ id: m.id, stdout: String(stdout ?? ''), stderr: String(stderr ?? ''), error: error+ ? { message: error.message, code: error.code, killed: error.killed, signal: error.signal, cmd: error.cmd } : null })+ }+ try {+ const child = execFile(m.file, m.args, m.options, reply)+ if (child.stdin) child.stdin.end()+ children.set(m.id, child)+ } catch (error) { reply(error, '', '') }+})+`++/** Two deaths this close together turn the route off for the rest of the process. */+const DEATH_WINDOW_MS = 60_000++let enabled = false+let fallen = false+let worker: Worker | null = null+let nextId = 0+const pending = new Map<number, ProbeDone>()+const deaths: number[] = []++export function enableOffThreadExec(): void {+ enabled = true+}++export function offThreadExecActive(): boolean {+ return enabled && !fallen+}++/** Test seam: the route off, the worker gone, no death counted. */+export function resetOffThreadExec(): void {+ enabled = false+ fallen = false+ deaths.length = 0+ const stopping = worker+ worker = null+ failAll('the probe worker was reset')+ void stopping?.terminate()+}++/** Test seam: the worker ends as a crash would end it. */+export async function stopProbeWorkerForTest(): Promise<void> {+ const stopping = worker+ if (!stopping) return+ const exited = new Promise<void>((resolve) => stopping.once('exit', () => resolve()))+ await stopping.terminate()+ await exited+}++function failAll(reason: string): void {+ for (const [id, done] of [...pending]) {+ pending.delete(id)+ done(Object.assign(new Error(reason), { code: 'EWORKER' }) as ExecFileException, '', '')+ }+}++function start(): Worker {+ const started = new Worker(WORKER_SOURCE, { eval: true })+ // A probe in flight never keeps the process alive: the core has its sockets for that.+ started.unref()+ started.on('message', (reply: Reply) => {+ const done = pending.get(reply.id)+ if (!done) return+ pending.delete(reply.id)+ const error = reply.error ? Object.assign(new Error(reply.error.message), reply.error) as ExecFileException : null+ done(error, reply.stdout, reply.stderr)+ })+ // An uncaught error in the worker ends it; `exit` follows and does the accounting.+ started.on('error', () => {})+ started.once('exit', () => {+ if (worker !== started) return+ worker = null+ failAll('the probe worker exited')+ const now = Date.now()+ deaths.push(now)+ while (deaths.length && now - deaths[0] > DEATH_WINDOW_MS) deaths.shift()+ if (deaths.length >= 2 && !fallen) {+ fallen = true+ console.warn('[probes] the probe worker exited twice within a minute; probes run on the main thread from now on')+ }+ })+ return started+}++export function execFileOffThread(file: string, args: readonly string[], options: ProbeOptions, done: ProbeDone): ProbeChild {+ const id = nextId+++ let killed = false+ pending.set(id, (error, stdout, stderr) => {+ if (error?.killed) killed = true+ done(error, stdout, stderr)+ })+ const target = worker ?? (worker = start())+ target.postMessage({ id, file, args: [...args], options: { ...options, env: { ...(options.env ?? process.env) }, encoding: 'utf8' } })+ return {+ get killed() { return killed },+ kill(signal: NodeJS.Signals = 'SIGTERM') {+ if (!pending.has(id) || !worker) return false+ worker.postMessage({ kill: id, signal })+ return true+ },+ }+}++/**+ * `execFile` for a probe: the worker's when the core has turned it on, else `inThread` (the caller's own+ * `execFile`, passed in so a test's mock of `node:child_process` applies) with the same arguments.+ */+export function probeExecFile(inThread: (...args: any[]) => unknown) {+ return (file: string, args: readonly string[], options: ProbeOptions, done: ProbeDone): ProbeChild | undefined =>+ offThreadExecActive()+ ? execFileOffThread(file, args, options, done)+ : inThread(file, args, options, done) as ProbeChild | undefined+}+```++- [ ] **Step 4: Run the tests**++Run: `npx vitest run src/lib/offThreadExec.spec.ts`+Expected: PASS, 13 tests.++If `probeExecFile ... toHaveBeenCalledWith('ps', ['-ax'], ...)` fails on array identity, that is fine:+`toHaveBeenCalledWith` compares deeply. Do not copy `args` in the in-thread branch; today's callers pass+their own arrays straight to `execFile`.++- [ ] **Step 5: Typecheck**++Run: `npm run typecheck`+Expected: exit 0.++- [ ] **Step 6: Checkpoint**++Run: `git diff --stat; git status --short`+Expected: the two new files.++---++### Task 3: `patientExec` through the worker++**Files:**+- Modify: `cli/src/lib/patientExec.ts` (the `patientExec` function, ~line 62)+- Test: `cli/src/lib/patientExec.spec.ts`++**Interfaces:**+- Consumes: `offThreadExecActive`, `execFileOffThread` (Task 2).+- Produces: unchanged signature `patientExec(execFile)(file, args, options, done)`. With the route on, the+ child runs in the worker and a timeout is reported with today's error shape.++- [ ] **Step 1: Write the failing tests**++In `cli/src/lib/patientExec.spec.ts`, add this import with the existing ones at the top:++```ts+import { enableOffThreadExec, resetOffThreadExec } from './offThreadExec.js'+```++and append this block at the end of the file (it uses the file's existing `hold` helper and `execFile` import):++```ts+describe('the same contract, with the core\'s probes in their worker', () => {+ afterEach(() => { resetOffThreadExec() })++ it('reads an answer that arrived while this loop was held, and never runs the in-thread execFile', async () => {+ enableOffThreadExec()+ const inThread = vi.fn()+ const kept = new Promise<{ error: Error | null; stdout: string }>((resolve) => {+ patientExec(inThread)('echo', ['still here'], { timeout: 100 }, (error, stdout) => resolve({ error, stdout }))+ })+ setImmediate(() => hold(400))+ expect(await kept).toEqual({ error: null, stdout: 'still here\n' })+ expect(inThread).not.toHaveBeenCalled()+ })++ it('reports a timeout exactly as the in-thread path does', async () => {+ enableOffThreadExec()+ const error = await new Promise<Error | null>((resolve) => {+ patientExec(execFile)('sleep', ['5'], { timeout: 100 }, (e) => resolve(e))+ })+ expect(error).toMatchObject({ killed: true, code: 'ETIMEDOUT', signal: 'SIGTERM' })+ expect(error!.message).toBe('sleep did not answer within 100 ms')+ })++ it('passes a failure through as it is', async () => {+ enableOffThreadExec()+ const error = await new Promise<Error | null>((resolve) => { patientExec(execFile)('false', [], { timeout: 1_000 }, (e) => resolve(e)) })+ expect(error).toMatchObject({ code: 1 })+ })+})+```++- [ ] **Step 2: Run them to see them fail**++Run: `npx vitest run src/lib/patientExec.spec.ts`+Expected: FAIL. The first test times out after vitest's 5 s: the in-thread path calls `inThread`,+a `vi.fn()` that never calls back. The timeout test passes already (the in-thread path behaves the same).++- [ ] **Step 3: Implement the route**++In `cli/src/lib/patientExec.ts`, add the import under the existing `import type { ExecFileException } ...`:++```ts+import { execFileOffThread, offThreadExecActive } from './offThreadExec.js'+```++Replace the whole `patientExec` function with:++```ts+/** The error a timed-out child is reported with, on either path: `tmuxBackend.ts` reads its shape. */+function timedOut(file: string, args: readonly string[], timeout: number, killSignal: NodeJS.Signals): ExecFileException {+ return Object.assign(new Error(`${file} did not answer within ${timeout} ms`), {+ killed: true, signal: killSignal, code: 'ETIMEDOUT', cmd: [file, ...args].join(' '),+ }) as ExecFileException+}++export function patientExec(execFile: (...args: any[]) => unknown) {+ return (file: string, args: readonly string[], options: PatientExecOptions, done: ExecDone): void => {+ const { timeout = 0, killSignal = 'SIGTERM', ...rest } = options+ if (offThreadExecActive()) {+ // The worker's loop is not held when this one is: its own timeout is a real one, and an answer+ // waits in the port until this loop reads it (offThreadExec.ts). No deadline is armed here.+ execFileOffThread(file, args, { ...rest, timeout, killSignal }, (error, stdout, stderr) => {+ if (error && timeout > 0 && error.killed && error.signal === killSignal) { done(timedOut(file, args, timeout, killSignal), stdout, stderr); return }+ done(error, stdout, stderr)+ })+ return+ }+ let finished = false+ let timedOutHere = false+ let cancel = (): void => {}+ const child = execFile(file, [...args], { ...rest, encoding: 'utf8' }, (error: ExecFileException | null, stdout: string, stderr: string) => {+ finished = true+ cancel()+ // Exit 0 is an answer even when the kill raced it: unlike Node's own timeout, this one never+ // throws the output away.+ if (error && timedOutHere) {+ done(timedOut(file, args, timeout, killSignal), stdout ?? '', stderr ?? '')+ return+ }+ done(error, stdout ?? '', stderr ?? '')+ }) as { kill?: (signal: NodeJS.Signals) => boolean } | undefined+ if (timeout > 0 && !finished) {+ cancel = patientDeadline(timeout, () => {+ timedOutHere = true+ child?.kill?.(killSignal)+ })+ }+ }+}+```++The in-thread branch is today's code with the error built by `timedOut` and the flag renamed+`timedOutHere` (it would shadow the helper otherwise). The message, `killed`, `signal`, `code` and `cmd`+are unchanged.++- [ ] **Step 4: Run every patientExec test, old and new**++Run: `npx vitest run src/lib/patientExec.spec.ts`+Expected: PASS. The existing tests are unchanged and still pass with the route off.++- [ ] **Step 5: Run the users of patientExec**++Run: `npx vitest run src/lib/tmux src/lib/tmuxCapture src/lib/tmuxAgentDiscovery src/lib/tmuxBackend src/lib/tmuxVersion`+Expected: same result as on the base commit (route off in all of them).++- [ ] **Step 6: Checkpoint**++Run: `git diff --stat`+Expected: `patientExec.ts`, `patientExec.spec.ts`, plus Task 2's files.++---++### Task 4: The direct probes++**Files:**+- Modify: `cli/src/lib/processEnv.ts` (`read`, ~line 54)+- Modify: `cli/src/lib/tmux.ts` (`execText`, ~line 378; import line 3)+- Modify: `cli/src/lib/nativeProcessImages.ts` (~line 194)+- Modify: `cli/src/engines/kit/launchExecutable.ts` (`captureEnvironment`)+- Test: `cli/src/lib/offThreadExec.spec.ts` (one routing test per caller)++**Interfaces:**+- Consumes: `probeExecFile` (Task 2).+- Produces: nothing new. Each caller keeps its signature and behaviour; with the route on, its child+ runs in the worker.++- [ ] **Step 1: Write the failing tests**++Append to `cli/src/lib/offThreadExec.spec.ts`:++```ts+import { launchEnvironment, clearLaunchEnvironmentCache } from '../engines/kit/launchExecutable.js'+import { clearProcessEnvCache, readProcessEnv } from './processEnv.js'++describe('the probes that called execFile directly', () => {+ afterEach(() => { clearProcessEnvCache(); clearLaunchEnvironmentCache() })++ it.runIf(process.platform === 'darwin')('reads a process environment through the worker', async () => {+ enableOffThreadExec()+ const { pid } = process+ // `ps eww` of this test's own Node: not an Apple platform binary, so its environment is shown.+ const env = await readProcessEnv({ pid, startMarker: 'x', executable: process.execPath } as never)+ expect(env?.HOME).toBe(process.env.HOME)+ })++ it('captures the launch environment through the worker', async () => {+ enableOffThreadExec()+ const env = await launchEnvironment('/bin/sh')+ expect(env?.HOME).toBe(process.env.HOME)+ })+})+```++`tmux.ts` `execText` and `nativeProcessImages` are covered end to end in Task 5: on macOS discovery runs+both every few seconds, and `paneLifecycle.e2e.ts` fails if discovery cannot read the process table.++- [ ] **Step 2: Run them**++Run: `npx vitest run src/lib/offThreadExec.spec.ts`+Expected: PASS even before the change (the in-thread path gives the same answers).++That is the point: these tests pin behaviour, not the route. The route itself is checked in Step 4 by+making the in-thread path unavailable.++- [ ] **Step 3: Route the four callers**++`cli/src/lib/processEnv.ts`: add `import { probeExecFile } from './offThreadExec.js'` beside the+`execFile` import, then in `read` replace++```ts+ execFile('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {+```++with++```ts+ probeExecFile(execFile)('ps', ['eww', '-p', String(pid), '-o', 'command='], { timeout: 2_000, maxBuffer: 4 << 20 }, (err, stdout) => {+```++`cli/src/lib/tmux.ts`: add `import { probeExecFile } from './offThreadExec.js'` with the other `./`+imports, then in `execText` replace++```ts+ let child: { killed?: boolean } | undefined+ child = execFile(command, args, { timeout }, (err, stdout) => resolve((err && !stdout) || child?.killed ? null : stdout))+```++with++```ts+ let child: { killed?: boolean } | undefined+ child = probeExecFile(execFile)(command, args, { timeout }, (err, stdout) => resolve((err && !stdout) || child?.killed ? null : stdout))+```++`cli/src/lib/nativeProcessImages.ts`: add `import { probeExecFile } from './offThreadExec.js'`, then replace++```ts+ execFile(helper.path, ['--paths', ...new Set(pids).values()].map(String),+```++with++```ts+ probeExecFile(execFile)(helper.path, ['--paths', ...new Set(pids).values()].map(String),+```++`cli/src/engines/kit/launchExecutable.ts`: add `import { probeExecFile } from '../../lib/offThreadExec.js'`,+then in `captureEnvironment` replace++```ts+ const child = execFile(argv[0], argv.slice(1), { encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }, (error, output) => {+```++with++```ts+ const child = probeExecFile(execFile)(argv[0], argv.slice(1), { timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }, (error, output) => {+```++Change the `child.stdin?.end()` line after it to `child?.stdin?.end()`. `probeExecFile` may return+`undefined` (a test's stand-in), the in-thread child still needs its stdin ended, and the worker ends+stdin itself.++The `encoding: 'utf8'` option is dropped because `ProbeOptions` has no `encoding`. The worker always+uses utf8, and `execFile` defaults to utf8 in-thread, so `output` is still a string. If the typecheck+complains about the callback's parameter types at any of the four sites, annotate them as+`(err: ExecFileException | null, stdout: string)`. Do not cast the call.++- [ ] **Step 4: Prove the route is taken**++Add to the `describe('the probes that called execFile directly')` block:++```ts+ it('does not spawn on this thread once the route is on', async () => {+ enableOffThreadExec()+ const childProcess = await import('node:child_process')+ const spy = vi.spyOn(childProcess, 'execFile')+ await launchEnvironment('/bin/sh')+ expect(spy).not.toHaveBeenCalled()+ spy.mockRestore()+ })+```++Run: `npx vitest run src/lib/offThreadExec.spec.ts`+Expected: PASS.++If `vi.spyOn` cannot redefine the ESM namespace export, drop this test and rely on Task 5's `sample`+check instead (`uv_spawn` must disappear from the core's main thread). Do not mock the worker.++- [ ] **Step 5: Run the callers' own specs and the typecheck**++Run: `npm run typecheck && npx vitest run src/lib/processEnv src/lib/tmux src/lib/nativeProcessImages src/engines/kit/launchEnvironment src/engines/kit/launchExecutable src/engines/nativeLaunch`+Expected: typecheck exit 0. Specs give the same result as on the base commit: they mock `node:child_process`+and the route is off in them.++- [ ] **Step 6: Checkpoint**++Run: `git diff --stat`+Expected: the four callers modified, plus earlier tasks' files.++---++### Task 5: The core turns it on++**Files:**+- Modify: `cli/src/core/main.ts` (`runForeground`, line ~406)++**Interfaces:**+- Consumes: `enableOffThreadExec` (Task 2).+- Produces: the route on in the core process, and only there.++- [ ] **Step 1: Enable it first thing in the core**++In `cli/src/core/main.ts`, add `import { enableOffThreadExec } from '../lib/offThreadExec.js'` with the+other `../lib/` imports, and in `runForeground` right after `installTimestampedConsole()`:++```ts+ // The core's probes spawn from a worker, so a terminal's keystrokes never wait behind one (lib/offThreadExec.ts).+ enableOffThreadExec()+```++- [ ] **Step 2: Typecheck and the core's coverage gate**++Run: `npm run typecheck && npm run test:core`+Expected:+- typecheck exits 0;+- `test:core` gives the same failures as on the base commit (2026-10-15: 3 in+ `src/services/searchProcess.spec.ts`).++The only core file touched is `src/core/main.ts`, which the gate exempts, so no per-file coverage check+is needed here.++- [ ] **Step 3: The bundle carries and loads the worker**++Run: `npm run bundle && node scripts/check-lean-bundle.mjs dist/cli.js`+Expected: both exit 0.++- [ ] **Step 4: The e2e that exercise probes and terminals**++Run: `npx vitest run --config vitest.e2e.config.ts e2e/stall.e2e.ts e2e/terminal.e2e.ts e2e/paneLifecycle.e2e.ts e2e/robustness.e2e.ts`+Expected: PASS, or exactly the base commit's result for these files (run them on a clean worktree of the+base to compare if anything is red).++`stall.e2e.ts` is the one that matters most: it holds the core's loop and checks no live pane is taken+for gone.++- [ ] **Step 5: Spawns are off the main thread**++On macOS, run Task 1's e2e once with `TYPING_SAMPLE=1 TYPING_REPORT=/tmp/typing-route-1.json`, then:++```bash+for f in /tmp/typing-sample-cpu.txt /tmp/typing-sample-cpu-flood.txt; do+ printf '%s ' "$f"+ awk '/Call graph:/{f=1} /Total number in stack/{f=0} f' "$f" \+ | awk '/^ [0-9]+ Thread_/{t=$0} {print t "\t" $0}' | grep main-thread | awk -F'\t' '{print $2}' \+ | sed -E 's/^[ +!:|]*//' \+ | awk '$2 ~ /^Thread_/ {tot=$1} $2=="uv_spawn"{s+=$1} $2=="kevent"{k+=$1} END{printf "busy=%d uv_spawn=%d (%.1f%%)\n", tot-k, s, 100*s/(tot-k)}'+done+```++Expected: `uv_spawn` under 5 % of the main thread's busy samples in both (it was ~60 % before).++- [ ] **Step 6: Checkpoint**++Run: `git diff --stat`++---++### Task 6: Inventory the remaining spawns++**Files:**+- Modify: `docs/plans/2026-10-15-keystrokes-off-spawn-path.md` (append a "Spawn inventory" section)++**Interfaces:**+- Consumes: Tasks 2–5 merged in the working tree.+- Produces: a table of every `child_process` call reachable from the core, marked routed, stays (with+ the reason), or follow-up.++- [ ] **Step 1: List the call sites**++Run (from `cli/`):++```bash+rg -n "\b(execFile|execFileSync|spawn|spawnSync|exec|execSync)\(" src/lib src/core src/engines \+ -g '!*.spec.ts' -g '!*.golden.spec.ts' | rg -v "probeExecFile|offThreadExec"+```++- [ ] **Step 2: Find which run on a timer in the core**++From the `sample` files of Task 5, list any remaining JS frames under `uv_spawn`. `sample` shows native+frames only, so use the earlier e2e CPU-profile method on a throwaway run. Run Task 1's e2e with+`NODE_OPTIONS` extended by `--cpu-prof --cpu-prof-dir=/tmp/typing-prof` for the core only. Set it in+`IsolatedDaemon.create({ env })` for this one run; do not commit that change.++Then attribute `ChildProcess.spawn` and `spawnSync` self time to callers. Write this script to /tmp+(do not put it in the repo):++```python+import json, sys, collections+p = json.load(open(sys.argv[1])); target = sys.argv[2]+nodes = {n['id']: n for n in p['nodes']}+parent = {c: n['id'] for n in p['nodes'] for c in n.get('children', [])}+dt = collections.Counter()+for sid, d in zip(p['samples'], p['timeDeltas']): dt[sid] += d+def name(n):+ cf = n['callFrame']; u = cf['url']+ return f"{cf['functionName'] or '(anon)'} {u.split('/src/')[-1]}:{cf['lineNumber']+1}"+agg = collections.Counter()+for nid, t in dt.items():+ if not name(nodes[nid]).startswith(target): continue+ chain, cur = [], parent.get(nid)+ while cur is not None and len(chain) < 40: chain.append(name(nodes[cur])); cur = parent.get(cur)+ agg[' <- '.join([c for c in chain if '.ts:' in c][:4])] += t+for k, t in agg.most_common(15): print(f"{t/1000:8.1f}ms {k}")+```++Run it as `python3 /tmp/attr.py <core>.cpuprofile ChildProcess.spawn`, and again with `spawnSync`.++- [ ] **Step 3: Write the table**++Append to the spec:++```markdown+## Spawn inventory (after Phase 2)++| Call site | Runs | Thread | Why |+|---|---|---|---|+| `lib/patientExec.ts` users (tmux.ts run, tmuxCapture, tmuxAgentDiscovery, tmuxBackend, tmuxVersion) | timers, requests | worker | Phase 1 |+| `lib/processEnv.ts` read | discovery, gateway runtime, DSH | worker | Phase 2 |+| … one row per remaining site from Step 1, with what Step 2 measured … |+```++Fill every row from Steps 1–2; a site with no measured time on a timer is "stays: on demand". If Step 2+shows a periodic site still on the main thread, add it to Task 4's pattern and rerun Task 4 Step 5.++- [ ] **Step 4: Checkpoint**++Run: `git diff --stat`++---++### Task 7: Measure and decide (Phase 3)++**Files:**+- Modify: `docs/plans/2026-10-15-keystrokes-off-spawn-path.md` (append "Results")++**Interfaces:**+- Consumes: Task 1's baseline `/tmp/typing-base-{1,2,3}.json`; everything above.+- Produces: the numbers and the decision: done, or design option 2.++- [ ] **Step 1: Three runs with the change**++Run Task 1's e2e three times with `TYPING_SAMPLE=1 TYPING_REPORT=/tmp/typing-route-{1,2,3}.json`.++- [ ] **Step 2: Compare against the gate**++Write `/tmp/compare.py` (not in the repo):++```python+import json, statistics, sys+def load(prefix): return [json.load(open(f'{prefix}-{i}.json'))['conditions'] for i in (1, 2, 3)]+base, route = load(sys.argv[1]), load(sys.argv[2])+def med(runs, cond, path, stat): return statistics.median(r[cond][path][stat] for r in runs)+for cond in ('idle', 'cpu', 'flood', 'cpu-flood'):+ for stat in ('p50', 'p99', 'max'):+ print(f"{cond:10} daemon {stat}: {med(base, cond, 'daemon', stat):8.2f} -> {med(route, cond, 'daemon', stat):8.2f}"+ f" (tmux {med(route, cond, 'tmuxDirect', stat):.2f})")+```++Run: `python3 /tmp/compare.py /tmp/typing-base /tmp/typing-route`++The gate, from the spec:+- `cpu`: daemon p99 ≤ 2× tmux p99, and max < 100 ms.+- `cpu-flood`: daemon p99 < 60 ms.+- `idle`: p50 ≤ 1 ms and p99 ≤ 5 ms.++- [ ] **Step 3: CPU and memory did not grow**++Run `PERF=1 E2E_BUNDLE=1 npx vitest run --config vitest.e2e.config.ts e2e/perf.e2e.ts` on the base and on+the change, with the same `PERF_REPORT` naming. Compare the core's CPU % and RSS.++Expected: within 5 %. The worker costs one isolate, roughly 5–10 MB RSS.++- [ ] **Step 4: The real Mac (owner's machine, with their go)**++Do this only with the owner's go: installing restarts their daemon.+- Install with `bash cli/scripts/install-cli.sh` from a worktree of the current release tag plus this+ diff, as was done for fix A (2026-10-15).+- Record children per minute and the core's `uv_spawn` share, before and after. Use `sample <core pid> 60`+ and the main-thread `awk` from Task 5 Step 5.+- Tell the owner the machine is now on a `-dev.` build that never self-updates; `harness update --force`+ returns it to releases.++- [ ] **Step 5: Write the results and the decision**++Append to the spec a "Results" section with three things:+- the medians table from Step 2;+- the perf comparison from Step 3;+- the real-Mac numbers from Step 4.++Then one of:+- **Gate met:** done. List any `execFileSync`/`spawnSync` still on a timer (Task 6) as follow-ups.+- **Gate missed:** quote what `sample` shows the main thread doing instead, and state that option 2 (the+ terminal data plane in its own worker) needs its own design document before any code.++- [ ] **Step 6: Checkpoint**++Run: `git status --short`+Expected: Tasks 1–7's files, uncommitted, for the owner to review and commit.diff --git a/docs/plans/2026-10-15-keystrokes-off-spawn-path.md b/docs/plans/2026-10-15-keystrokes-off-spawn-path.mdnew file mode 100644index 000000000..a488ea89f--- /dev/null+++ b/docs/plans/2026-10-15-keystrokes-off-spawn-path.md@@ -0,0 +1,268 @@+# Keystrokes off the core's spawn path++Status: proposed, 2026-10-15. Follows the typing-latency spike of the same day and fix A (held-launch+backoff and the cached launch environment), which removed the worst spawner but not the mechanism.++## Problem++A local terminal stutters while typing when the machine is busy. The echo's median is fine; its tail is not.++Measured with the e2e harness (isolated daemon, private tmux, fake Claude Code, 150–250 keystrokes per+condition, a keystroke's echo timed from the client). Load = 12 busy `yes` processes on a 12-core Mac;+flood = 4 other agents printing as fast as tmux reads, their streams open and acked every 16 ms.++| Condition (ms) | raw pty p50 / p99 | tmux control client p50 / p99 | daemon over local WS p50 / p99 / max |+|---|---|---|---|+| idle | 0.1 / 0.6 | 0.4 / 1 | 0.7 / 5 / 7 |+| CPU load | 0.3 / 5–20 | 1.2 / 12–28 | 2–4 / 62–101 / 300+ |+| CPU load + flood | 0.2 / 12 | 2.5 / 24–28 | 4.5 / 126–224 / 350 |++- The core hop adds 4–5× the tail tmux does. Flutter is not the cause: a typing echo parses and paints in+ ~0.2 ms; a full 30-row redraw costs ~0.8 ms per pane with real fonts (debug build).+- Under load the core's event-loop delay reached p99 ~65 ms and max 200–300 ms while the core used ~5 % CPU:+ it was blocked, not busy.+- `sample` of the core's main thread under load (no profiler attached): **~60 % of its non-idle samples+ were inside `uv_spawn` → `posix_spawn`**. Node's `child_process` spawns synchronously on the calling+ thread; under CPU contention one spawn takes tens of milliseconds.+- The spawns are the core's own probes, each a `ps`, `lsof` or `tmux` child: `readProcessEnv` (`ps eww`, per+ process, for discovery, the gateway runtime and DSH), `readProcessRows` (`ps -axo`), `darwinProcessImages`+ (`lsof`), `panePidLookup` and `tmuxCapture` (`tmux display-message` / `capture-pane`), `listPaneTitles`.+- A keystroke arrives on the same thread (`localWsServer.ts` → `TerminalStreamManager.handleBinary` →+ `TmuxControlStream.writeRaw`), and so does its echo (`%output` → `onOutput` → `flushOutput` → `ws.send`).+ Every spawn in between is time the keystroke waits.++On the real Mac after fix A, the core still spawns ~45 children a minute (`ps`, `lsof`, `tmux`); `uv_spawn`+is 4–7 % of the main thread's busy time on a lightly loaded machine, and climbs with load as above.++## Goal++A keystroke never waits behind a probe's spawn.++Success, on the same e2e workload and machine as the baseline:++- CPU load: daemon p99 ≤ 2× the tmux control client's p99 (today 3–5×), max < 100 ms.+- CPU load + flood: daemon p99 < 60 ms (today 126–224 ms).+- Idle: no regression (p50 ≤ 1 ms, p99 ≤ 5 ms).+- Core main thread: `uv_spawn` < 5 % of non-idle samples under load.+- Core CPU and RSS within 5 % of baseline on `e2e/perf.e2e.ts`.++## Options++1. **Run the probes' children from a worker thread (chosen).** One `worker_threads` worker in the core+ owns `child_process` for short-lived probes. The main thread posts `{file, args, options}` and receives+ `{error, stdout, stderr}`. `posix_spawn` then blocks only the worker. Small and targeted: almost every+ hot probe already goes through one wrapper, `patientExec` (tmux.ts, tmuxCapture.ts, tmuxAgentDiscovery.ts,+ tmuxBackend.ts, tmuxVersion.ts); the rest are four direct `execFile` calls. No protocol or process change.+2. **Move the terminal data plane to a worker** (Orca's shape: a pty host whose loop does nothing else).+ The worker would own the tmux control clients and a socket of its own for terminal frames, since a+ keystroke read by the main thread is already behind whatever holds it. Isolates keystrokes from+ everything (GC, synchronous fs, JSON, other frames), but changes the desktop's protocol (a second local+ socket), splits the control lease and stream state across threads, and is several times the work.+3. **Move the probes to a service process.** Discovery and reconciliation are core by design ("must never+ go down"); moving them is an architecture change for a scheduling problem.++Option 1 removes the measured cause at a fraction of the cost. Option 2 stays on the table if Phase 3's+numbers show the tail is still the core's (see "Decision after measurement").++## Design (option 1)++`src/lib/offThreadExec.ts`++- `execFileOffThread(file, args, options, done)`: the same callback contract as `execFile`+ (`error | null, stdout, stderr`), returns a handle with `kill(signal)`.+- The worker is a few lines of inline code (`new Worker(code, { eval: true })`) using only `node:child_process`,+ so the lean bundle needs no extra file. Started lazily on first use, `unref()`ed so it never keeps the+ process alive.+- **The child's timeout runs in the worker.** The worker's loop is not held when the core's is, so a+ timeout there is a real one. The main thread keeps no timer of its own: a main-thread timer is exactly+ what a held loop fires late, before the reply waiting in the port is read. A worker that dies fails+ its calls from its `exit` event. This also removes the case `patientExec` exists for (a held loop+ firing a timeout on an answer that already arrived), for these calls.+- **The environment is sent with every call**: `options.env ?? process.env`, captured when called. A+ worker's `process.env` is a copy made at its start, and the core changes `PATH` after start+ (`tmuxOnPath.ts`); a stale copy would find another `tmux`.+- `maxBuffer`, `killSignal`, `cwd` and `encoding: 'utf8'` are passed through. Output arrives as strings+ (structured clone); the largest regular one is `ps -axo` (tens to hundreds of KB every few seconds).+- One worker serves every call; children run concurrently, as they do now. Requests are numbered; a+ reply for a cancelled request is dropped.+- **Failure**: if the worker cannot start, or exits, every call in flight gets an error (`EWORKER`) and the+ next call starts a new worker. Two worker deaths in 60 s turn the route off and fall back to in-thread+ `execFile` for the rest of the process, logged once.+- **Opt-in by the core only.** `enableOffThreadExec()` is called from `runForeground` (core/main.ts) and nowhere+ else: services, the CLI and unit tests keep calling `execFile` in-thread, and a test's `vi.mock` of+ `node:child_process` still applies to every call it makes.++Routing++- `patientExec(execFile)`: when the route is on, calls go to `execFileOffThread` instead of the `execFile`+ passed in, and without its own deadline (the worker's is enough). When it is off, unchanged.+- Direct `execFile` probes routed the same way, through one helper `probeExecFile` exported beside it:+ `processEnv.read` (`ps eww`), `tmux.ts` `execText` (`lsof`), `nativeProcessImages` (the helper binary),+ `launchExecutable.captureEnvironment` (the login shell).+- Not routed: long-lived children (`tmux -C` control clients, engine panes, services), synchronous calls+ (`execFileSync`/`spawnSync`, which need their own fix), and anything outside the core process.++## Phases++Each phase ends green on its own and can ship alone.++### Phase 0: the measurement, in the repo++- Turn the spike into an opt-in e2e, `e2e/typingLatency.e2e.ts` (`TYPING=1`, like `PERF=1`). It times+ keystroke echo in four paths: raw pty, a tmux control client, the daemon over the local WS, and the+ core probe's event-loop delay. It runs idle, CPU load, flood, and load with flood, and writes JSON+ (`TYPING_REPORT=<file>`).+- Lessons from the spike that the test must keep:+ - Spawn the load processes directly; `sh -c 'yes …'` leaves orphans.+ - Send `terminal_alive` every 5 s or the streams expire after 30 s.+ - Never use `--cpu-prof`: it profiles the fake engines too and skews everything.+ - Use `sample <pid>` for main-thread attribution.+- Record the baseline on main: 3 runs of each condition, with the machine's load average reported beside+ them, since the host's own load is noise.+- Out: a reproducible baseline JSON and the command to rerun it.++### Phase 1: the off-thread exec++- `src/lib/offThreadExec.ts` and its spec, using real children (`/bin/echo`, `/bin/sh -c 'sleep …'`, a+ command that exits 3, one that prints more than `maxBuffer`):+ - an answer;+ - an exit code;+ - a timeout killed in the worker;+ - `kill()` from the main thread;+ - the env passed through after `process.env.PATH` changes;+ - a worker that exits mid-call (its calls fail, the next one restarts it);+ - two deaths turning the route off;+ - `unref` (a script using it exits).+- `patientExec` routing, with specs for on and off. Off must stay byte-for-byte the current behaviour; its+ existing specs keep passing untouched.+- `enableOffThreadExec()` called from `runForeground`.+- Validation:+ - `npm run typecheck`;+ - the new and affected specs;+ - `npm run test:core` (the core's files stay at 100 %);+ - e2e: `stall.e2e.ts` (a held loop must still not turn a timeout into "no panes"), `terminal.e2e.ts`,+ `paneLifecycle.e2e.ts`, `robustness.e2e.ts`;+ - `scripts/check-lean-bundle.mjs dist/cli.js` (the worker's inline code loads from the lean bundle).++### Phase 2: the direct probes++- Route `processEnv.read`, `tmux.ts` `execText`, `nativeProcessImages` and the launch environment's capture+ through `probeExecFile`.+- Inventory the remaining `execFile`/`spawn` calls reachable from the core's timers (`rg` over+ `child_process` imports under `src/lib`, `src/core` and `src/engines`, about 58 files). Route the periodic+ ones; list the on-demand ones in this plan with why they stay.+- Validation: their specs (they mock `node:child_process`, which still applies since the route is off in+ unit tests), `test:core`, and the e2e set from Phase 1.++### Phase 3: measure, then decide++- Rerun Phase 0's e2e on the same machine, three runs each, against the recorded baseline.+- Check the core with `sample` under load: `uv_spawn`'s share of non-idle samples.+- Run `e2e/perf.e2e.ts` (CPU, RSS, event-loop delay of the core) against main's numbers.+- On the real Mac, install the build and check two things before and after: children per minute and+ `uv_spawn`'s share in the core.+- Record the numbers in the PR. The typing-latency targets are the gate, not a feeling.++### Decision after measurement++- Targets met: done. Sync spawns (`execFileSync`/`spawnSync`), if any remain on a timer, become a follow-up.+- Targets missed and `sample` shows the main thread busy with something else (GC, synchronous fs, frames):+ write option 2's design as its own document before any code.++## Risks++- **A stale environment in the worker**: handled by sending `env` with every call. A spec pins it.+- **Ordering**: no caller relies on two separate children finishing in order (each is its own process+ today too). tmux commands that must be ordered already share one `tmux` invocation or the control+ client, which stays on the main thread.+- **Memory**: one worker is a V8 isolate, about 5–10 MB RSS. Phase 3 measures it.+- **Lost children if the worker dies**: a probe's child outlives a dead worker until its own exit. They are+ short-lived (`ps`, `lsof`, `tmux` queries), and their timeouts are seconds.+- **Tests**: unit tests never turn the route on, so mocks behave as before; e2e runs it for real.++## Out of scope++- The terminal-specific improvements from the spike:+ - pane-hidden streams;+ - input frames bypassing the per-connection `chain` in `localWsServer.ts`;+ - an output-batch bypass right after a keystroke.++ They are smaller effects by the same measurements; revisit after Phase 3.+- GPU text rendering in the desktop's terminal (glyph atlas): paint is not the typing bottleneck.+- The search-path hold (`captureLaunchExecutable` holding forever on a dangling alias earlier in PATH,+ while the shell runs a valid engine later in it): a separate fix.++## Spawn inventory (after Phase 2)++| Call site | Runs | Thread | Why |+|---|---|---|---|+| `lib/patientExec.ts` users: `tmux.ts` (`run`), `tmuxCapture.ts`, `tmuxAgentDiscovery.ts`, `tmuxBackend.ts`, `tmuxVersion.ts` | timers (discovery, reconciler, titles, captures) and requests | worker | Phase 1 |+| `lib/processEnv.ts` `read` (`ps eww`) | discovery, gateway runtime, DSH | worker | Phase 2 |+| `lib/tmux.ts` `execText` (`lsof`) | process images, every discovery pass | worker | Phase 2 |+| `lib/nativeProcessImages.ts` (image helper) | every discovery pass | worker | Phase 2 |+| `engines/kit/launchExecutable.ts` `captureEnvironment` (login shell) | launches, held-launch passes | worker | Phase 2 |+| `lib/tmuxStream.ts` (`tmux -C attach`) | once per terminal stream | main | long-lived child: its stdin/stdout are the terminal |+| `lib/loginShellEnv.ts`, `lib/tmuxOnPath.ts` (login shells) | once at start | main | start-up only |+| engine panes, services, one-shots (`lib/oneshot.ts`), git, grid, installers | on a person's request | main | on demand, not periodic |++Measured on the e2e workload (`e2e/typingLatency.e2e.ts`, `TYPING_SAMPLE=1`): with the route on, `uv_spawn` is 0.0 % of+the core main thread's non-idle samples under CPU load and under load with flood, in all three runs (70–81 % and+29–31 % before). A `uv_spawn` frame covers `spawnSync` as well, so no periodic synchronous spawn remains on the main+thread for this workload either.++## Results (2026-10-15)++`e2e/typingLatency.e2e.ts`, three runs before (HEAD 65f648ac6) and three after, same 12-core Mac. Median of+the three runs; the host's own load average was 7–41 during them.++| Condition | Daemon p50 (ms) | Daemon p99 (ms) | Daemon max (ms) | Core loop delay p99 (ms) | tmux p99 for reference |+|---|---|---|---|---|---|+| idle | 0.60 → 0.57 | 3.9 → 7.8 | 10.7 → 12.5 | 14.0 → 11.9 | 1.7 → 0.9 |+| CPU load | 1.40 → 1.26 | 23.5 → 28.0 | 37.2 → 32.5 | 35.1 → 17.5 | 6.8 → 18.8 |+| flood | 1.12 → 1.11 | 49.4 → 41.3 | 56.5 → 58.4 | 23.9 → 18.6 | 1.6 → 4.4 |+| CPU load + flood | 4.14 → 4.22 | **222 → 122** | **344 → 135** | **74 → 33** | 18.9 → 23.0 |++- `uv_spawn` on the core's main thread, share of non-idle samples:+ - under CPU load: **70–81 % → 0 %**;+ - under load with flood: **29–31 % → 0 %**.+- On the owner's Mac (real agents, light load), 60 s `sample` of the core:+ - before (fix A only): 32 % of busy samples, 2,043 busy samples;+ - after: **2 %**, 1,156 busy samples. The rest is `tmux -C attach` at stream open.+- `e2e/perf.e2e.ts`, core process, one run per build:++ | | empty | populated, idle | active |+ |---|---|---|---|+ | CPU, base | 0.92 % | 2.87 % | 23.1 % |+ | CPU, change (2 runs) | 0.76, 0.81 % | 3.26, 3.06 % | 22.9, 25.0 % |+ | RSS, base | 72.0 MB | 88.1 MB | 103.4 MB |+ | RSS, change (2 runs) | 75.7, 77.8 MB | 104.4, 100.0 MB | 129.3, 116.1 MB |++ - CPU is within run-to-run noise.+ - RSS is up by 4–26 MB. The second run had the worker's heap capped with `resourceLimits`, but review+ showed the cap has no effect under the core's process-wide heap flags (`--max-old-space-size`), so the+ cap was removed. The two runs differ by run-to-run noise alone.+ - One base run is not enough to size the cost: it needs repeated runs before it is accepted or reduced.++Against the goal:++| Target | Met? | Result |+|---|---|---|+| CPU load: p99 ≤ 2× tmux, max < 100 ms | met | 28.0 ≤ 37.6; 32.5 |+| CPU load + flood: p99 < 60 ms | **missed** | 122 ms, halved |+| Idle: p50 ≤ 1 ms, p99 ≤ 5 ms | p50 met, p99 not | p99 sits between 3.6 and 8.8 in individual runs both before and after; the target was set from one quiet run |+| `uv_spawn` < 5 % | met | 0 % e2e, 2 % on the real Mac |+| CPU and RSS within 5 % | **RSS missed** | CPU met; RSS +4–26 MB, single runs |++**Decision.** Spawning is gone from the keystroke's thread, and the worst tail halved, but under load with+flood the core's main thread is still busy with other work. In the `sample`s that work is the flooding+panes' stream I/O (`uv__stream_io`), GC (incremental marking), and a JS `flatMap`. A keystroke still+queues behind that.++What remains is option 2 territory: either+- the terminal data plane in its own worker, or+- the cheaper items listed under "Out of scope": no output for hidden panes, and input frames off the+ per-connection chain.++Both need measurement first. Option 2 needs its own design document before any code. The RSS cost+(+4–26 MB in single runs) is the price of the worker. Measure it with repeated runs before the owner+decides whether it stands.