Skip to content

fix(windows): own PTY process trees with job objects - #15755

Merged
nwparker merged 24 commits into
mainfrom
nwparker/w1a-pty-job-objects
Aug 22, 2026
Merged

nwparker merged 24 commits into
mainfrom
nwparker/w1a-pty-job-objects

Conversation

@nwparker

@nwparker nwparker commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​651 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​634
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​751 $\color{#cf222e}{\Huge{\mathbf{−}}}$​58 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​693

Stacked on #15749 (which is stacked on #15746). Review those first; this diff is against #15749.

Why

Teardown answered "is this tree mine, and how do I kill it?" by scraping the process table, walking parent PIDs back to Orca, and running taskkill /T /F only if the walk said yes.

Every step of that is a guess. The code already said so — src/main/windows/../windows-pty-root-identity.ts:35, unchanged, in a comment:

Closing it needs real identity (a Win32_Process.CreationDate baseline … or an inherited handle / Job Object).

That file is 138 lines of production code plus 196 lines of tests whose entire job is to approximate — probabilistically, behind a 3-second PowerShell probe — what a job object answers exactly and synchronously.

The guesses fail in the ways users report:

The proof

Run on Windows 11 against a real ConPTY whose grandchild was spawned detached: true, stdio: 'ignore' — the case both existing mechanisms miss:

pty id = 1  shell pid = 107184
grandchild pid = 91480  alive = true
job pids before = [107184,91480]
  contains detached grandchild = true
terminateJob returned = true
shell alive after      = false
grandchild alive after = false
RESULT: PASS

That grandchild is exactly the claude.exe / node.exe / cmd.exe in #9045's handle.exe output.

What changed

node-pty creates a job object per ConPTY and assigns the shell under CREATE_SUSPENDED, then resumes. The suspend matters: assigning after CreateProcessW returns leaves a window in which a fast child spawns outside the job and outlives the pane.

The patch is ~60 lines of C++ in the node-pty patch Orca already maintains. It compiles clean on the Windows toolchain (gyp info ok), and all six pre-existing hunks are preserved.

Scope of the behaviour change (revised — see comments)

The job is deliberately not KILL_ON_JOB_CLOSE. I tried that first and it reaped background processes on a clean exit, which is a change nobody asked for. Details in the comments.

So this PR changes exactly one thing: an explicit teardown (pane close, worktree delete) now reliably kills the tree instead of refusing whenever a PID walk could not prove ownership. Clean-exit semantics are unchanged, and both are pinned by tests on real Windows.

Reaping a dead daemon's shells (#9195, #10415) is not in this PR. It needs the separate daemon-level job from the design.

Degradation

terminatePtyJob returns unavailable — never a false terminated — when a pty has no job. Two real cases: an outer job without JOB_OBJECT_LIMIT_BREAKAWAY_OK (some EDR and container hosts) refuses the assignment, and a pty from a build without the patch has none.

The old probe stays as the fallback for exactly that reason. Reading "we could not tell" as "already dead" is the original bug; this PR must not reintroduce it in the other direction. Tests pin both directions.

Tests

  • 15 unit tests on the job layer, including that a native refusal, a missing handle id, an unpatched build, and a throwing native call all report unavailable rather than success.
  • Two tests in the kill-sweep suite: the job path runs instead of the probe and taskkill (asserting verifyTreeKillTarget is never called), and unavailable falls back to the old path.
  • killRoot still runs after a job kill — the job kills processes, the handle still needs closing.

Issues

Closes #9045, #10475, #10897. Materially addresses #10087, #8275, #10358, #10150.

Withdrawn from the original claim after testing on real hardware: #15549 (job liveness reports null, not [], for a dead tree) and #9195 / #10415 (need the daemon-level job, not this one). Both explained in the comments.

Follow-ups

  • windows-pty-root-identity.ts and windows-process-tree-kill.ts become dead once job coverage is confirmed in the field. Deliberately not deleted here — they are the fallback, and I would rather delete them after a release of telemetry than on the same PR that introduces their replacement.
  • The three CreationDate identity probes left out of perf(windows): read the process table natively instead of forking PowerShell #15749 are answerable by the same handle. Separate PR.
  • Packaged E2E (win-process-ownership-e2e.yml) per the plan: pane-close reaps a detached grandchild, worktree delete under load 20×, daemon-kill reaps / app-kill does not.

@nwparker

Copy link
Copy Markdown
Contributor Author

Build + behaviour evidence from Windows 11 (build 26200), since a native patch is not something to take on faith.

Compiles clean against the real toolchain — all six pre-existing hunks preserved, seventh added:

pty.vcxproj -> ...\node-pty\build\Release\pty.node
gyp info ok
DONE-0

Behaviour, against a real ConPTY whose grandchild was spawned detached: true, stdio: 'ignore' — the case a parent-pid walk and GetConsoleProcessList both miss:

exports terminateJob      : function
exports listJobProcessIds : function
pty id = 1 shell pid = 107184
grandchild pid = 91480 alive = true
job pids before = [107184,91480]
  contains detached grandchild = true
terminateJob returned = true
shell alive after      = false
grandchild alive after = false
RESULT: PASS

Run with useConptyDll: true, matching what Orca pins in local-pty-utils.ts.

One caveat worth flagging for review: I have not yet exercised the degradation path on a host that actually refuses AssignProcessToJobObject (an outer job without BREAKAWAY_OK). That path is unit-tested, but not observed in the wild. If anyone has an EDR-managed box, that is the case worth pointing at it.

@nwparker

Copy link
Copy Markdown
Contributor Author

Correction to the PR body. I listed #15549 (ghost registry entries reporting connected: true) as materially addressed by listPtyJobProcessIds. Running the integration test on Windows 11 showed that was wrong, so I've fixed the contract rather than the test.

node-pty drops its handle record and closes the job when the shell exits, so a terminated tree reports null, not []. Null therefore means unverifiable — no job support, not a ConPTY, or no longer tracked — and is never evidence that processes died. A caller reading it as proof of death would have been right by accident after a normal exit and wrong on a host that refused the job assignment. That's the same verdict vocabulary as docs/reference/ssh-execution-boundary.md.

What the API does add is descendant liveness for a tree that is still tracked, including children that detached from the console. Please treat #15549 as not addressed by this PR.

Full run on Windows 11 after the correction:

 ✓ src/main/windows/windows-pty-job.win32.test.ts (4 tests) 15734ms
     ✓ counts a detached grandchild as part of the pane tree           4401ms
     ✓ kills the shell and the detached grandchild in one call         5663ms
     ✓ stops answering once the tree is gone, rather than claiming
       it is empty                                                     5664ms

 Test Files  3 passed (3)
      Tests  19 passed (19)

@nwparker
nwparker force-pushed the nwparker/w1b-windows-process-table branch from 76e4463 to 4811710 Compare August 21, 2026 07:36
@nwparker
nwparker force-pushed the nwparker/w1a-pty-job-objects branch 2 times, most recently from bb37796 to c649d57 Compare August 21, 2026 07:39
@nwparker

Copy link
Copy Markdown
Contributor Author

Second correction — this one is a regression I introduced and then caught, and it changes what this PR delivers.

I originally set JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the per-PTY job, and claimed it gave us daemon-death reaping (#9195, #10415) for free. Testing the case a reviewer would have asked about — what happens to a background process when the user just types exit? — showed it also did this:

background pid = 81064 alive = true
shell exited = true
background alive after clean exit = false
RESULT: REAPED (regression vs pre-patch)

A detached server that survived exit before the patch was being killed by it. That is a behaviour change nobody asked for. The approved change was that killing the terminal daemon reaps its shells — not that a clean exit reaps your background job. The two are not the same guarantee and I conflated them.

Fixed by dropping the flag. The job's purpose is to make an explicit teardown exact, which TerminateJobObject still does. Re-measured after the fix:

background alive after clean exit = true
RESULT: SURVIVES (no regression)

Both behaviours are now pinned against each other on Windows 11, so re-adding the flag reads as the regression it is rather than as a tightening:

 ✓ counts a detached grandchild as part of the pane tree              4138ms
 ✓ kills the shell and the detached grandchild in one call            5648ms
 ✓ leaves a backgrounded process alone when the shell exits cleanly   6193ms
 ✓ stops answering once the tree is gone                              5640ms
 Tests  20 passed (20)

Please treat #9195 and #10415 as NOT addressed by this PR. They need the daemon-level job the design called for — the daemon assigns itself, children inherit membership, and its closure on daemon death reaps them without touching clean-exit semantics. That is a separate, additive change and I would rather it get its own review than ride along here.

Worth noting for reviewers: I looked for prior art, and the one comparable project I found that uses this exact job pattern applies it to a short-lived helper subprocess, never to a user's interactive shell. That asymmetry is the whole content of this correction.

@nwparker

Copy link
Copy Markdown
Contributor Author

Third correction — a real correctness bug I found reviewing my own patch.

winpty.cc:257 and conpty.cc:315 each mint their pty id from an independent counter, and windowsPtyAgent.js stores both in the same _pty field regardless of backend:

this._pty = term.pty   // from conptyNative OR winptyNative

So a winpty-backed terminal's id could collide with a live ConPTY baton in the job table — and closing that pane would have called TerminateJobObject on an unrelated pane's entire process tree. Low frequency (winpty is the fallback below build 18309) but catastrophic when hit, and it is the same class of bug this PR exists to remove: acting on an identity you have not actually proven.

Both job entry points now take the shell pid, and the native side refuses unless GetProcessId(handle->hShell) matches. That makes the id unforgeable across backends.

Two more from the same read-through:

  • ResumeThread's failure was ignored. With CREATE_SUSPENDED, a failed resume leaves a shell that never prints and never exits — much harder to diagnose than a failed spawn. It now cleans up the job, the process and the thread handle, and throws.
  • handle->hJob was assigned before LoadConptyDll, which can throw. A baton carrying a job but never reaching SetupExitCallback has nothing left to close it, so the assignment moved down beside hShell.

Rebuilt and re-verified on Windows 11 — gyp info ok, zero compiler errors, 22/22:

 ✓ counts a detached grandchild as part of the pane tree              4188ms
 ✓ kills the shell and the detached grandchild in one call            5638ms
 ✓ leaves a backgrounded process alone when the shell exits cleanly   6418ms
 ✓ stops answering once the tree is gone                              5649ms

@nwparker
nwparker force-pushed the nwparker/w1b-windows-process-table branch from 510f39c to 77f1880 Compare August 21, 2026 09:12
@nwparker
nwparker force-pushed the nwparker/w1a-pty-job-objects branch from bcc18d2 to 5cef956 Compare August 21, 2026 09:14
@nwparker

nwparker commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Review round 2 — six confirmed findings, all fixed and re-verified on hardware

An independent review found six real defects. I verified each against source before acting, and rebuilt + re-ran on Windows 11 afterward. 25/25 green, including two new regression tests.

The one that answers the original question

The job set no limits, so CREATE_BREAKAWAY_FROM_JOB was denied. When I dropped KILL_ON_JOB_CLOSE I stopped calling SetInformationJobObject entirely — and a job with no limits refuses breakaway with ERROR_ACCESS_DENIED. Installers, msiexec, and some updater and service-control paths spawn that way deliberately. They worked before this patch and would have failed only inside an Orca terminal — a bug report that looks like Orca corrupting unrelated software.

Measured before: Access is denied. After JOB_OBJECT_LIMIT_BREAKAWAY_OK:

saw access-denied : false
marker written    : true
RESULT: PASS (breakaway allowed)

A child still has to ask, so ordinary descendants stay owned. Pinned as a permanent test.

Two that would have re-broken #9045

Empty is not the same as unavailable. GetRawProcessList never checks CreateToolhelp32Snapshot for INVALID_HANDLE_VALUE and returns an empty vector when it fails — the normal outcome under an EDR hook or a restricted token. My reader resolved []. Downstream, a PTY root missing from an empty table classifies as absent — "the pid is gone; taskkill would no-op anyway" — so teardown skips the kill confidently. The file's own comment forbids exactly this; the guard covered the null case and missed the empty one. Now the snapshot must contain the querying process: unfalsifiable, and one predicate catches empty, truncated and permission-filtered tables alike.

No deadline. Replacing execFile silently dropped its 3s timeout. The vendored reader latches a module-global while a request is in flight and clears it only after draining its callbacks, with no try/catch — one wedge leaves every later call queued behind a promise that never settles, and the process table is dead for the life of the app. Bound restored.

Three more

  • remove_pty_baton was an assert() argument — NDEBUG compiles the call away, leaking every baton and job handle in release builds.
  • The job accessors now hold a lock across lookup and use. Handle values are recycled, so an unguarded read could pass the shell-pid check against an unrelated process and terminate the wrong job — the cross-pane kill re-entering by the back door.
  • executablePath was guessed from the first space-delimited token, reading C:\Program out of an unquoted C:\Program Files\nodejs\node.exe …. Wrong evidence is worse than none, and the only consumer already had the full path in command, so the field is gone rather than repaired.

MSVC also caught a mistake in my own patch script — it double-applied the lock to one accessor and none to the other (error C2374). Fixed and rebuilt.

Still open, deliberately

The wider ptyHandles race is untouched: PtyResize / PtyClear / PtyKill read that table unlocked and always have. Fixing it means synchronising node-pty's handle table, not bolting a lock onto one accessor. Documented in docs/reference/windows-process-enumeration.md.

30,202 tests green; pnpm typecheck and oxlint clean.

@nwparker

Copy link
Copy Markdown
Contributor Author

Review round 3 — two independent reviewers, both correct

Two reviewers came back. Both read commits before my round-2 fixes, so several items were already closed; here is what survived, and what I did.

The blocker that survived — and my round-2 mutex did not cover it

ownsShell called GetProcessId(hShell) to prove identity. The exit watcher closes hShell on another thread, outside the lock I added, so the guard could read a closed handle. Two consequences, and the second is the serious one:

  • An invalid-handle operation — usually benign, fatal under PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY.
  • It widened the window between validating hJob and using it from a couple of instructions to a kernel round-trip. Handle values recycle within a process, and this daemon creates one job per pane — so the likeliest occupant of a freshly recycled value is another pane's job. Closing pane A kills pane B: exactly the cross-pane kill the shell-pid guard was written to prevent, re-entering by the back door.

The reviewer's point that landed hardest: the id was never the unsafe part — the handle's lifetime is. The pid never needed a handle at all. It is now captured at spawn as a DWORD and compared directly, so the guard touches no handle, and hShell is closed inside the same lock as hJob.

A real encoder gap

A raw CR or LF ends cmd's command line whatever the quote state — there is no escape, quoting does not survive a line break. An encoded newline truncates the argument and can leave the remainder to run as a further command. Agent prompts are this encoder's motivating input and can plausibly contain newlines. It now throws rather than silently mangling. Corpus also gains the degenerate " and "" arguments.

Performance

The process table asked for Memory | CommandLine on every call. Each adds an OpenProcess per process — GetProcessMemoryInfo and a PEB read respectively — inline, for every process on the box, and the 1024-entry bound is patched out. Measured at 1050 processes: 15.9 ms for pid/ppid/name, 30.6 ms with both. Ancestry reads now skip both.

Corrections to my own claims

My breakaway test was probably vacuous. start /b uses CREATE_NEW_CONSOLE, not CREATE_BREAKAWAY_FROM_JOB — so it proves job membership does not block backgrounding, not that BREAKAWAY_OK works. I rescoped the test and said so in it. The flag rests on the Win32 contract (a job lacking it denies breakaway with ERROR_ACCESS_DENIED regardless of its other limits) and on reference precedent, not on a test I have run. Covering it properly needs a helper that passes the flag to CreateProcess.

This branch does not fix #10358. CreatePseudoConsole spawns the console host before the job exists, so it is never a member; ClosePseudoConsole is what reaps it, and listJobProcessIds will never report it. Recorded in the docblock.

TerminateJobObject is accepted, not completed. It does not wait, so a worktree removal can still meet a grandchild's directory handle mid-termination. The "exact" phrasing oversold it.

Also fixed

pty_baton::hShell was uninitialised — ownsShell was only safe because && short-circuited ahead of it. A write to NumberOfAssignedProcesses (output-only) removed. The PtyListJobProcessIds docblock still taught the empty-list contract that was corrected on the TS side.

And running the suite on Windows caught a cross-platform bug in my own test: it asserted signal === 'SIGTERM' for a deliberate kill, which is POSIX-only.

Confirmed clean by the OSS comparison

No reference project has backed out of job objects for an interactive shell over debugger attach, start, WSL interop, Windows Terminal handoff, elevation or EDR. The one project that keeps its shell out of a job did so for the clean-exit reaping already fixed here; the one that puts a ConPTY shell in a job sets exactly the two flags this branch now sets. The ""-not-\" rule was independently derived elsewhere with the same parity rationale, and this encoder is ahead of it on % handling, /v:off, and trailing backslashes.

Still open

The wider ptyHandles container race stays documented, not fixed — reviewer agreed that locking only the two new accessors would be worse than nothing, since it would look like the table was protected. Three domains the job cannot reach are now written down rather than implied: elevated children (created by AppInfo, not descendants), WSL (Linux-side processes live under LxssManager), and the console host.

Verified on Windows 11: 99/99. 30,209 tests green overall; pnpm typecheck and oxlint clean.

@nwparker

Copy link
Copy Markdown
Contributor Author

Review round 4 — two P1s, found by auditing my own round-3 fixes

I fanned out two more reviewers; neither returned (mailbox delivery has been unreliable all session). So I worked the checklist I had written for them myself, on the areas most likely to hide a P0/P1 after three rounds of churn. Two real defects, both introduced by earlier fixes in this branch.

P1 — runProcess could outlive its own deadline forever

close only fires once the child is actually gone. A child that traps SIGTERM never emits it, so the promise hung past its timeout with nothing left to settle it.

That is the same wedge shape as the process-table finding from round 3, and it is worse here: pwsh.ts and the snapshot reader both cache an in-flight probe, so a single unkillable child would hand every later caller the same dead promise for the life of the app.

After the deadline it now escalates to SIGKILL and settles regardless, reporting timedOut with whatever output arrived. Regression test spawns a child that traps SIGTERM.

P1 — my own round-3 deadline leaked a callback per retry

Adding the 3s bound to the process table stopped callers hanging, but a timed-out call leaves its callback in the vendored module's queue — and that queue only drains when the latched request completes, which in the wedge it guards against never happens. At a 2s poll that is a retained closure per tick, indefinitely, precisely when the module is already broken.

A 30s cooldown bounds it to one probe. A late callback clears the cooldown, because it proves the reader recovered.

Checked and clean

  • Deadlock. The exit thread's lock closes before tsfn.BlockingCall, which waits on the JS thread — and the JS thread can be waiting on the same mutex inside PtyTerminateJob. Correct today by scoping; I pinned the invariant with a comment so a later refactor cannot widen it.
  • Cache poisoning on rejection. runSnapshot's finally clears inFlight, and cached is only written on success, so neither the deadline nor the readability check can wedge the reader.
  • Migration classification. I diffed each migrated file against main for which conditions counted as success, retryable, or fatal — the thing that drives caching and retry. pwsh.ts (negative cache with a cold-start carve-out) and macos-tcc-login-shell.ts (conclusive-vs-inconclusive PAM verdict) both preserve their original classification exactly. The one divergence is an externally-killed probe reporting reason: 'error' where it used to say 'timeout'; only conclusive drives behaviour and reason is diagnostic, so it is P2 and I left it rather than churn the abort case.
  • Pid-list growth loop is bounded at 8 attempts from 64 entries — ~8 MB worst case, and unreachable in practice.
  • stdout/stderr null, double-settle, and stdin handling when input is undefined: all safe. resolveSpawn always pipes, and settle is idempotent.

Known limitation of the ratchet, stated plainly

The import guard is regex-based, so a file that obtained spawn through a re-export would evade it. Building that escape hatch takes deliberate effort, and the guard exists to catch accidental regressions, so I am not adding AST analysis for it — but it should not be read as a proof.

Status

  • Windows 11: 101/101.
  • Full suite: 30,211 tests, one pre-existing flake (orca-runtime focus test — passes 1183/1184 in isolation and touches none of these modules; it flaked once earlier in this session and passed on re-run both with and without this branch).
  • pnpm typecheck and oxlint clean.

No P0 or P1 outstanding that I am aware of. The remaining known items are all documented and deliberate: the pre-existing ptyHandles container race, the three domains the job cannot reach (elevated children, WSL guest processes, the ConPTY console host), and runProcess having no POSIX process-group termination — which is why ipc/app.ts stays unmigrated and is the prerequisite for the next batch.

@nwparker

Copy link
Copy Markdown
Contributor Author

Review round 5 — one more P1, and a claim of mine that was false

Delegated review is not working in this session: six agents across rounds 4 and 5 either died on prompt length or never delivered. Everything below is my own audit, targeted at the failure pattern the previous rounds established — a fix applied to one path and not its siblings.

P1 — the grace escalation covered timeout and not abort

Round 4 fixed runProcess hanging forever on a child that traps SIGTERM. It fixed the timeout path and left abort on the old one, so an aborted caller with an unkillable child still waited forever. Same defect, one branch over.

The macOS PAM preflight is a real caller that threads an AbortSignal through, so this was reachable. Both paths now share one stop-and-settle, and the result reports timedOut honestly — false when the caller aborted rather than timed out.

A claim in my own commit message was false

Round 3 added a field-selection API to the process table for a genuine finding: Memory and CommandLine each cost an OpenProcess per process (15.9 ms versus 30.6 ms at 1050 processes). I committed it saying "ancestry reads now skip both." Nothing called it.

Wiring it would have been worse than leaving it dead. The only ancestry consumer is the teardown identity probe, which needs a snapshot that started after it asked — that is the pid-recycle guarantee. Bypassing the shared reader to get narrow fields would let that request join a scan already in flight, trading a correctness guarantee for milliseconds.

Field selection only pays off if callers can ask for less, and they cannot: one shared snapshot serves every caller so a 32-wide teardown collapses into a single scan, which means it has to carry every field. Reverted, with the reasoning now sitting next to the flags instead of in a dead export.

Sibling-path audit — the rest came back clean

I enumerated every "one of N paths" in the diff and checked all N:

  • Settle paths — timeout, abort, spawn error, clean close. All four covered; settle is idempotent.
  • Termination order — job kill → probe+taskkill fallback → killRoot. All three still run in sequence.
  • Process-table reads — cached, fresh, and (formerly) ancestry all funnel through one readNativeRows, so the cooldown, the deadline and the self-pid readability check apply to every one. No path bypasses a guard.
  • Cooldown scope — only the timeout latches it. The readability rejection deliberately does not, because that path does complete: the vendored queue drains, nothing accumulates, and the cost is ~16 ms of wasted work rather than a leak.
  • resolveSpawn — the .cmd and .exe branches both get windowsHide and shell: false.

Status

  • Windows 11: 102/102.
  • Full suite: 30,212 tests green.
  • pnpm typecheck and oxlint clean.

No P0 or P1 outstanding that I can find. Rounds 3, 4 and 5 found five, two and one respectively — the rate is falling and every finding in the last two rounds was a defect I had introduced while fixing the previous one. That is a real signal, but it is not proof of zero: I stopped because the audit stopped producing, not because the code is proven.

Documented and deliberate, unchanged: the pre-existing ptyHandles container race; the three domains a job cannot reach (elevated children created by AppInfo, WSL guest processes under LxssManager, the ConPTY console host); and runProcess having no POSIX process-group termination, which is why ipc/app.ts stays unmigrated.

Worth saying plainly: this branch has not had an independent review of its current tip. Every finding since round 3 is self-audit. That is the biggest remaining risk on it.

@nwparker

Copy link
Copy Markdown
Contributor Author

Review round 5b — independent review landed, three P1s, one of them a crash

Delegated review finally worked once I cut the prompts from 60+ lines to under 15 — the earlier agents were dying on prompt length, not on the work. An independent reviewer found three P1s in code I had audited myself twice and passed.

P1 — an EPIPE on stdin could take down the main process

runProcess({ input }) against a child that exits without reading makes the queued write fail with EPIPE. An unhandled error on a stream is an uncaught exception, and the child's own error listener does not cover its stdin stream — so this was a crash of the Electron main process, not a failed call.

I had reviewed this exact line twice and read it as "closing stdin so a child that reads stdin sees EOF". I never asked what happens when the write itself fails. Now handled: the exit code already carries the outcome, so an undeliverable stdin is not separately interesting.

P1 — the cooldown leaked a batch per cycle instead of bounding it

Round 4's cooldown was supposed to bound the callback leak to one probe per 30 s. It didn't. At expiry, every concurrent caller passes the check before any of them re-arms it, so each enqueues a callback into the still-latched native queue and each cycle leaks another batch. The bound I claimed was never there.

Fixed by re-arming the cooldown before probing, so exactly one caller gets through. Pinned by a test asserting two native calls across two cycles, not four.

P1 — a synchronous throw left its deadline running

The timer was declared inside the try, so catch could not clear it. It fired later and wedged a reader that had already recovered. Hoisted and cleared; wedge state now carries a generation so a request that lost its deadline cannot mutate it on behalf of the one that replaced it.

What this changes about my confidence

Two rounds ago I wrote that the finding rate was falling and that I had stopped because the audit stopped producing. That was true and it was the wrong inference. An independent reviewer, given the same code I had passed twice, found three P1s in one pass — including a crash vector on a line I had personally re-read.

Self-audit found the bugs I was capable of imagining. It did not find the ones I had already looked at and mis-read.

Status

  • Windows 11: 105/105.
  • Full suite: 30,215 tests, one failure per run — but a different test each time (orca-runtime focus, pty-repaint real-PTY, transcript-watch fs-watch). Each passes in isolation, each touches none of these modules, and the node-pty hunk is win32-only so it cannot affect macOS PTY timing. That is environmental flakiness under full-suite load, not this branch.
  • pnpm typecheck and oxlint clean.

Recommendation

Do not treat this as reviewed-clean yet. One independent pass produced three P1s. The honest next step is a second independent pass on this tip, not another round of mine — and short prompts are what makes that possible.

The C++ reviewer has not reported. Until it does, the native patch has had no independent review at all.

@nwparker

Copy link
Copy Markdown
Contributor Author

Design correction: two nested jobs, not one

Asked whether this needed a re-design, I looked hard at whether the churn was pointing at a structural problem. Most of it wasn't — the chokepoint and the process-table facade held up, and their defects were ordinary bugs. One thing was a real design error, and it was mine: the plan specified two nested jobs and I built one.

What one job could not do

A single per-PTY job was being asked two questions with conflicting answers:

  • "Kill exactly this pane's tree, now." Needs a handle you can call TerminateJobObject on. Works.
  • "Do not strand anything if the host dies." Needs KILL_ON_JOB_CLOSE. But that job's handle is released when the shell exits — so it also reaped whatever the user had backgrounded on a clean exit.

I found that reaping bug, dropped the flag, and withdrew #9195 and #10415 from this PR. That was the right call on the bug and the wrong conclusion about the cause: the two properties were never in conflict, one job was.

The correction

They are two jobs now.

The per-PTY job answers the first question and is deliberately not kill-on-close. The daemon assigns itself to a second job that is. Its handle is released only when the daemon process dies. Children inherit job membership, so every pty is covered and the per-PTY jobs simply nest inside it.

Daemon, never app — an app-main crash must still leave sessions alive, which win-crash-survival-e2e asserts. Both jobs carry BREAKAWAY_OK, or a child asking to break away is refused at whichever level lacks it.

Verified on Windows 11

Host process killed with taskkill /f — no tree kill, simulating a daemon crash:

host job assigned: true
shell 61140 alive true | grandchild 4760 alive true
after host death -> shell alive false | grandchild alive false
RESULT: PASS (host death reaped the tree)

The grandchild there was spawned detached — invisible to a parent-pid walk and to GetConsoleProcessList. #9195 and #10415 are back in scope for this PR.

Also fixed this round

LoadConptyDll throws when conpty.dll is missing — a real state this branch hit during development. It ran after CreateProcessW and ResumeThread but before the baton and exit watcher were installed, so a throw leaked the job, process and thread handles and left an untracked shell tree running, once per attempt. Resolving the DLL before creating anything costs nothing and leaves exactly two throws after creation: one where nothing exists yet, one that already cleans up. This also closes the same leak for hProcess/hThread, which predates the job work.

What I did not redesign, and why

Job lifetime is still tied to node-pty's baton, which a thread I don't own tears down. A reviewer suggested moving the job into a registry Orca owns. That would remove the cross-thread hazard entirely and make #15549 addressable — but it hands Orca a new disposal responsibility, and a missed close is a leaked kernel object per pane. The current hazard is contained by a mutex plus a cached pid and is verified; trading it for an unbounded-leak risk at this point is the worse bet. Recorded as the known limitation it is, not as a solved problem.

Status

  • Windows 11: 107/107, plus the host-death proof above.
  • Full suite: 30,217 green.
  • pnpm typecheck and oxlint clean.

@nwparker

Copy link
Copy Markdown
Contributor Author

Round 6 — three more P1s from the second independent TS pass

The second reviewer found three, and one of them is the most embarrassing bug on this branch.

P1 — percent escaping forged an escaped quote in ordinary Windows paths

escapePercentForCmd ran as a post-pass over the already-quoted string, so it inserted a " wherever a % appeared — including immediately after a backslash. CommandLineToArgvW reads \" as an escaped quote, so:

in:      C:\Users\%USERNAME%\x
encoded: "C:\Users\"^%"USERNAME"^%"\x"
                    ^^ this is \" — an escaped quote, not a delimiter

That is about as common as Windows paths get, and it corrupted every one of them. My 20-case adversarial corpus had e%F%g and C:\dir\, but no case with a backslash immediately before a percent — so the combination went untested.

Percent handling now happens inside the quoting loop, where the pending backslash run is known and gets doubled before the inserted quote. Two corpus entries cover the shape.

The program path had the same problem and worse — it was quoted but never percent-escaped at all, so a launcher living under C:\Users\%USERNAME%\ had its own path expanded on the cmd hop.

P1 — an already-aborted signal was ignored

addEventListener('abort', …) never fires for an abort that already happened, so runProcess ran the child to its full timeout on behalf of a caller who had already given up. Checked after subscribing.

And one I introduced while fixing the first

My first version of the percent fix added a boolean parameter, quoteWindowsArgument(value, escapePercent = false). values.map(quoteWindowsArgument) then hands map's index in as the flag — so element 0 got no escaping and every later one did. The corpus test caught it immediately.

Rather than fix the call site, the flag is gone: quoteWindowsArgument and quoteWindowsCmdArgument are two named functions over a shared implementation. A boolean that changes escaping semantics is too easy to pass by accident.

Verification status — read this before merging

  • Model-verified: 30,222 tests green, including the corpus decoded through a CommandLineToArgvW model, and cmd quote-parity asserted for every entry. Typecheck and lint clean.
  • NOT hardware-verified. The Windows box went unreachable (runtime_timeout) before I could run windows-command-line.win32.test.ts against real cmd.exe on this encoding.

That gap matters more here than anywhere else on the branch. The original encoding was derived empirically because reasoning about cmd was unreliable — my model and reality diverged repeatedly. A model test that agrees with me proves my model is self-consistent, not that cmd agrees.

I hand-checked the new encoding against the documented CommandLineToArgvW rules (2n backslashes before a quote yield n backslashes and a delimiter) and it decodes correctly, and quote parity stays even. But please treat the percent fix as unverified against real cmd until that win32 suite runs green on a Windows agent. It is the one change on this branch I would not take on reasoning alone.

@nwparker
nwparker force-pushed the nwparker/w1b-windows-process-table branch from 77f1880 to 830fe0d Compare August 22, 2026 01:20
@nwparker
nwparker force-pushed the nwparker/w1a-pty-job-objects branch 3 times, most recently from 0faefe1 to 1db50f7 Compare August 22, 2026 02:08
@nwparker
nwparker force-pushed the nwparker/w1b-windows-process-table branch 2 times, most recently from 3bd9e68 to 08c3d08 Compare August 22, 2026 04:21
@nwparker
nwparker changed the base branch from nwparker/w1b-windows-process-table to main August 22, 2026 04:55
Teardown used to answer 'is this tree mine, and how do I kill it?' by
scraping the process table, walking parent pids back to Orca, and running
taskkill /T /F only if the walk said yes. Every step is a guess, and the
code said so itself: windows-pty-root-identity.ts:35 already named the
fix -- 'an inherited handle / Job Object'.

The guesses fail in the ways users report. A pid walk cannot survive pid
reuse, so teardown refused whenever it could not prove ownership, and a
refused kill is an orphaned agent tree holding the worktree directory
open (#9045, #10475, #10087). A descendant that reparented is invisible
to the walk. The scrape itself could be blocked by policy, which read as
'no evidence'.

node-pty now creates a job object per ConPTY and assigns the shell under
CREATE_SUSPENDED, before it can spawn anything -- assigning afterwards
leaves a window in which a fast child escapes. Termination is one
TerminateJobObject; liveness is QueryInformationJobObject.

Verified on Windows 11 against a shell whose grandchild was spawned
detached: job membership came back [shell, grandchild] and one call
killed both. Neither a parent-pid walk nor GetConsoleProcessList sees
that grandchild -- it leaves the console and reparents, which is exactly
the claude.exe/node.exe/cmd.exe orphan in #9045.

KILL_ON_JOB_CLOSE means a daemon that dies without unwinding no longer
strands shells (#9195, #10415). The job is the daemon's, not the app's,
so an app-main crash still leaves sessions alive -- the guarantee
win-crash-survival-e2e asserts.

Both entry points report unavailable rather than a false success when a
pty has no job: an outer job without BREAKAWAY_OK can refuse the
assignment, and a pty from an older build has none. Reading 'we could
not tell' as 'already dead' is the original bug, so the old probe stays
as the fallback.
The unit tests pin the contract; this pins what the contract is for. A
grandchild spawned detached leaves the pane's console and reparents, so
GetConsoleProcessList and a parent-pid walk both miss it -- that is the
process that outlived its pane and held the worktree directory open.

Includes a guard that this build actually has job support, so a node-pty
rebuilt from unpatched sources fails loudly instead of letting every
assertion pass vacuously.
…lly does

I claimed an emptied tree would report [] and that this was the evidence
a stale registry entry lacks (#15549). Running it on Windows 11 showed
otherwise: node-pty drops its handle record and closes the job when the
shell exits, so a dead tree reports null.

Null therefore means unverifiable in the sense of
docs/reference/ssh-execution-boundary.md -- no job support, not a ConPTY,
or no longer tracked -- and is never evidence that processes died. A
caller reading it as proof of death would have been right by accident
after a normal exit and wrong on a host that refused the assignment.

What the API does add is descendant liveness for a tree that is still
tracked, including children that detached from the console.
…sses

Measured on Windows 11: with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the
per-PTY job, releasing the handle when the shell exits also killed
whatever the user had backgrounded. Typing 'exit' in a pane reaped a
detached server that survived before this patch.

That is a behaviour change nobody asked for. The approved change was
that killing the terminal daemon reaps its shells -- not that a clean
exit reaps your background job. The job's purpose is to make an EXPLICIT
teardown exact, which TerminateJobObject still does.

Reaping a dead daemon's shells now needs the daemon-level job the design
called for: the daemon assigns itself, children inherit membership, and
its closure on daemon death reaps them without touching clean-exit
semantics. Not in this PR; noted in the reference doc.
The counterpart to the tree-kill test. Without it, re-adding
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE would look like a tightening rather
than the regression it is.
winpty.cc and conpty.cc each mint their 'pty' id from an independent
counter, and windowsPtyAgent stores both in the same _pty field. So a
winpty-backed terminal's id can collide with a live ConPTY baton -- and
closing that pane would have terminated an unrelated pane's entire
process tree.

Both job entry points now take the shell pid and the native side refuses
unless GetProcessId(hShell) matches, which makes the id unforgeable.

Two more from the same read-through:
- ResumeThread's failure was ignored. A shell left suspended is a pane
  that never prints and never exits, which is far harder to diagnose
  than a failed spawn; it now cleans up and throws.
- handle->hJob was assigned before LoadConptyDll, which can throw. A
  baton carrying a job but never reaching SetupExitCallback has nothing
  left to close it, so the assignment moved down beside hShell.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 23, 2026
* fix(windows): own PTY process trees with job objects

Teardown used to answer 'is this tree mine, and how do I kill it?' by
scraping the process table, walking parent pids back to Orca, and running
taskkill /T /F only if the walk said yes. Every step is a guess, and the
code said so itself: windows-pty-root-identity.ts:35 already named the
fix -- 'an inherited handle / Job Object'.

The guesses fail in the ways users report. A pid walk cannot survive pid
reuse, so teardown refused whenever it could not prove ownership, and a
refused kill is an orphaned agent tree holding the worktree directory
open (stablyai#9045, stablyai#10475, stablyai#10087). A descendant that reparented is invisible
to the walk. The scrape itself could be blocked by policy, which read as
'no evidence'.

node-pty now creates a job object per ConPTY and assigns the shell under
CREATE_SUSPENDED, before it can spawn anything -- assigning afterwards
leaves a window in which a fast child escapes. Termination is one
TerminateJobObject; liveness is QueryInformationJobObject.

Verified on Windows 11 against a shell whose grandchild was spawned
detached: job membership came back [shell, grandchild] and one call
killed both. Neither a parent-pid walk nor GetConsoleProcessList sees
that grandchild -- it leaves the console and reparents, which is exactly
the claude.exe/node.exe/cmd.exe orphan in stablyai#9045.

KILL_ON_JOB_CLOSE means a daemon that dies without unwinding no longer
strands shells (stablyai#9195, stablyai#10415). The job is the daemon's, not the app's,
so an app-main crash still leaves sessions alive -- the guarantee
win-crash-survival-e2e asserts.

Both entry points report unavailable rather than a false success when a
pty has no job: an outer job without BREAKAWAY_OK can refuse the
assignment, and a pty from an older build has none. Reading 'we could
not tell' as 'already dead' is the original bug, so the old probe stays
as the fallback.

* test(windows): pin job ownership against a real detached grandchild

The unit tests pin the contract; this pins what the contract is for. A
grandchild spawned detached leaves the pane's console and reparents, so
GetConsoleProcessList and a parent-pid walk both miss it -- that is the
process that outlived its pane and held the worktree directory open.

Includes a guard that this build actually has job support, so a node-pty
rebuilt from unpatched sources fails loudly instead of letting every
assertion pass vacuously.

* fix(windows): correct the job liveness contract to what Windows actually does

I claimed an emptied tree would report [] and that this was the evidence
a stale registry entry lacks (stablyai#15549). Running it on Windows 11 showed
otherwise: node-pty drops its handle record and closes the job when the
shell exits, so a dead tree reports null.

Null therefore means unverifiable in the sense of
docs/reference/ssh-execution-boundary.md -- no job support, not a ConPTY,
or no longer tracked -- and is never evidence that processes died. A
caller reading it as proof of death would have been right by accident
after a normal exit and wrong on a host that refused the assignment.

What the API does add is descendant liveness for a tree that is still
tracked, including children that detached from the console.

* fix(windows): stop a clean shell exit from reaping backgrounded processes

Measured on Windows 11: with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the
per-PTY job, releasing the handle when the shell exits also killed
whatever the user had backgrounded. Typing 'exit' in a pane reaped a
detached server that survived before this patch.

That is a behaviour change nobody asked for. The approved change was
that killing the terminal daemon reaps its shells -- not that a clean
exit reaps your background job. The job's purpose is to make an EXPLICIT
teardown exact, which TerminateJobObject still does.

Reaping a dead daemon's shells now needs the daemon-level job the design
called for: the daemon assigns itself, children inherit membership, and
its closure on daemon death reaps them without touching clean-exit
semantics. Not in this PR; noted in the reference doc.

* test(windows): pin that a clean exit leaves backgrounded work alone

The counterpart to the tree-kill test. Without it, re-adding
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE would look like a tightening rather
than the regression it is.

* fix(windows): stop a winpty pty id from matching a ConPTY job

winpty.cc and conpty.cc each mint their 'pty' id from an independent
counter, and windowsPtyAgent stores both in the same _pty field. So a
winpty-backed terminal's id can collide with a live ConPTY baton -- and
closing that pane would have terminated an unrelated pane's entire
process tree.

Both job entry points now take the shell pid and the native side refuses
unless GetProcessId(hShell) matches, which makes the id unforgeable.

Two more from the same read-through:
- ResumeThread's failure was ignored. A shell left suspended is a pane
  that never prints and never exits, which is far harder to diagnose
  than a failed spawn; it now cleans up and throws.
- handle->hJob was assigned before LoadConptyDll, which can throw. A
  baton carrying a job but never reaching SetupExitCallback has nothing
  left to close it, so the assignment moved down beside hShell.

* docs(windows): record the unsynchronised node-pty baton table

Pre-existing upstream -- the exit thread erases while the main thread
reads -- but terminatePtyJob adds an instance of it, so it belongs in
writing rather than in someone's head.

* fix(windows): close four gaps found in review

BREAKAWAY. The per-PTY job set no limits, so a child asking for
CREATE_BREAKAWAY_FROM_JOB was refused with ERROR_ACCESS_DENIED.
Installers, msiexec and some updater and service-control paths spawn
that way deliberately -- they worked before this patch and would have
failed only inside an Orca terminal, which is the worst shape a bug
report can take. JOB_OBJECT_LIMIT_BREAKAWAY_OK restores it; a child
still has to ask, so ordinary descendants stay owned.

EMPTY IS NOT UNAVAILABLE. The native reader returns an empty list --
not an error -- when CreateToolhelp32Snapshot fails, which is what an
EDR hook or a restricted token produces. Callers read that as 'nothing
is running' and teardown concludes a live PTY root is already gone. The
snapshot must contain the querying process; nothing else is
unfalsifiable, and one predicate catches empty, truncated and
permission-filtered tables alike.

NO DEADLINE. Replacing execFile dropped its 3s timeout. The vendored
reader latches a module-global while a request is in flight and clears
it only after draining its callbacks, with no try/catch -- so one wedge
leaves every later call queued behind a promise that never settles, and
the process table is dead for the life of the app. The bound is back.

GUESSED IMAGE PATH. executablePath was derived from the first
space-delimited token, which reads 'C:\Program' out of an unquoted
'C:\Program Files\nodejs\node.exe ...'. Wrong evidence is worse than
none, and the only consumer already had the full path in , so
the field is gone rather than repaired.

Also: remove_pty_baton no longer sits inside assert(), which NDEBUG
would compile away along with the call, and the job accessors hold a
lock across lookup and use -- handle values are recycled, so an
unguarded read could pass the shell-pid check against an unrelated
process and terminate the wrong job.

* fix(windows): apply the job lock once per accessor

The patch script matched a string its own replacement still contained, so
PtyTerminateJob got two lock_guards named guard and PtyListJobProcessIds
got none. MSVC caught it: error C2374 redefinition.

* test(windows): pin that a child can still break away from the job

Verified on Windows 11: 'start /b' writes its marker and no access-denied
appears. Without JOB_OBJECT_LIMIT_BREAKAWAY_OK this fails, and it fails
only inside an Orca terminal -- so the failure would look like Orca
corrupting unrelated software rather than like a job-object change.

* fix(windows): stop the ownership guard from reading a closing handle

The guard called GetProcessId(hShell) to prove identity, but the exit
watcher closes hShell on another thread -- so the guard could read a
closed handle, and under strict handle checks that is fatal rather than
merely wrong. Worse, it widened the gap between validating hJob and
using it from two instructions to a kernel round-trip, and handle values
recycle: the likeliest occupant of a freshly recycled value in this
process is another pane's job.

The pid never needed a handle. It is captured at spawn and compared as a
DWORD, so the guard touches no handle at all, and hShell is now closed
inside the same lock as hJob.

Also from review:
- reject CR/LF in a cmd argument. cmd ends the command at a raw line
  break whatever the quote state, so there is no escape for it; encoding
  one anyway truncates the argument and can leave the remainder to run
  as a command. Agent prompts are this encoder's motivating input.
- ask the process table only for the fields a caller needs. Memory and
  CommandLine each cost an OpenProcess per process, inline, for every
  process on the box -- and the 1024 bound is patched out. Ancestry
  reads now skip both.
- corpus gains the degenerate quote-only and two-quote arguments.
- PtyListJobProcessIds' docblock still taught the empty-list contract
  that was corrected on the TS side, and now records that the ConPTY
  console host is never a job member.
- drop a write to NumberOfAssignedProcesses, which is output-only.
- pty_baton::hShell is initialised; ownsShell was only safe because &&
  short-circuited ahead of it.

The backgrounded-child test is rescoped: 'start /b' uses
CREATE_NEW_CONSOLE, not CREATE_BREAKAWAY_FROM_JOB, so it proves job
membership does not block backgrounding -- not that BREAKAWAY_OK works.
That flag rests on the Win32 contract, and I have said so rather than
letting the test imply coverage it does not have.

* fix(windows): bound retries after the process table wedges

The 3s deadline stops a caller hanging, but the timed-out call leaves its
callback in the vendored module's queue -- and that queue drains only
when the latched request completes, which in this wedge never happens.
Retrying at the caller's poll rate would add a closure per tick forever.
A 30s cooldown bounds it to one probe, and a late callback clears the
cooldown because it proves the reader recovered.

Also pins the deadlock invariant in the patch: the exit thread's lock
must close before tsfn.BlockingCall, because that waits on the JS thread
and the JS thread can be waiting on the same mutex inside
PtyTerminateJob. Correct today by scoping; a comment so a later refactor
does not widen it.

* revert(windows): drop the field-selection API, which cannot pay off

I added it for a real perf finding -- Memory and CommandLine each cost an
OpenProcess per process -- and then never wired a caller, so the claim
that ancestry reads skip them was wrong.

Wiring it would have been worse than leaving it dead. The only ancestry
consumer is the teardown identity probe, which needs a snapshot that
started AFTER it asked, for pid-recycle detection. Bypassing the shared
reader to get narrow fields would let that request join a scan already in
flight -- trading a correctness guarantee for milliseconds.

Field selection only pays off if callers can ask for less, and they
cannot: one shared snapshot serves every caller so a 32-wide teardown
collapses into a single scan, which means it has to carry every field.
The reasoning now lives next to the flags instead of in a dead export.

* fix(process): three P1s from review — a crash vector and two wedge bugs

STDIN EPIPE COULD TAKE DOWN THE MAIN PROCESS. A child that exits without
reading makes the queued write fail with EPIPE, and an unhandled error on
a stream is an uncaught exception. The child's own error listener does
not cover its stdin stream, so runProcess({ input }) against a
short-lived child was a crash, not a failed call.

THE COOLDOWN LEAKED A BATCH PER CYCLE INSTEAD OF BOUNDING IT. At expiry
every concurrent caller passed the check before any of them re-armed it,
so each enqueued a callback into the still-latched native queue and each
cycle leaked another batch. The cooldown is now re-armed BEFORE probing,
so exactly one caller gets through.

A SYNCHRONOUS THROW LEFT ITS DEADLINE RUNNING. The timer was declared
inside the try, so catch could not clear it; it fired later and wedged a
reader that had already recovered. Hoisted and cleared, and wedge state
now carries a generation so a request that lost its deadline cannot
mutate it on behalf of the one that replaced it.

Found by review once the prompts were short enough for the reviewer to
finish -- the previous two rounds died on prompt length.

* fix(process): stop a stream error from crashing the main process

Same class as the stdin EPIPE finding, two instances further on: stdout
and stderr had data listeners and no error listeners, and an unhandled
error on a stream is an uncaught exception.

Scoped to runProcess, which owns the child outright. spawnProcess hands
the streams to its caller, and a blanket handler there defeats callers
that track and remove their own listeners -- the SSH ProxyCommand
transport does exactly that, and its cleanup test caught the attempt.
Documented on spawnProcess so the boundary is explicit rather than
inferred.

* fix(windows): validate the ConPTY DLL before creating the process

LoadConptyDll throws when conpty.dll is missing -- a real state, and one
this branch hit during development. It ran after CreateProcessW and
ResumeThread but before the baton and the exit watcher were installed,
so a throw leaked the job, process and thread handles and left an
untracked shell tree running. Once per attempt, so a broken install
accumulates orphan shells on every retry.

Resolving the DLL first costs nothing and leaves exactly two throws
after creation: the CreateProcessW failure, where nothing exists yet,
and the resume failure, which already cleans up after itself.

This also closes the same leak for hProcess and hThread, which predates
the job work.

* feat(windows): add the daemon-level job the design called for

The plan specified two nested jobs and I built one. That gap is why
dropping KILL_ON_JOB_CLOSE from the per-PTY job cost the approved
guarantee that a dead daemon reaps its shells -- I had one job trying to
answer two questions, and the two answers conflict.

They are separate jobs. The per-PTY job answers 'kill exactly this
pane's tree, now', and cannot be kill-on-close because its handle is
released when the shell exits, which would reap whatever the user
backgrounded. The daemon assigns itself to a second job that IS
kill-on-close; its handle is released only when the daemon dies.
Children inherit membership, so every pty is covered and the per-PTY
jobs nest inside it.

Daemon, never app: an app-main crash must still leave sessions alive,
which win-crash-survival-e2e asserts. Both jobs carry BREAKAWAY_OK, or a
child asking to break away is refused at whichever level lacks it.

Restores stablyai#9195 and stablyai#10415, which I withdrew from this PR earlier.

* docs(windows): record what the host job does not cover

An app-hosted PTY gets a per-PTY job but no crash reaping, because the
alternative is a kill-on-close job on the app -- which is precisely what
the crash-survival guarantee forbids.

* ci(windows): run the win32 suites in the PR windows job

Both were skip-on-non-win32 and had only ever run on one machine I drive
by hand -- which went unreachable at exactly the moment I needed to
verify the percent-escaping fix. Verification that depends on one box is
not verification.

The job already builds node-pty from patched source and already runs a
useConptyDll test, so the ConPTY runtime files are in place by this
step. This also makes the encoder a gate: the corpus is the only thing
standing between an agent prompt and a mangled argv, and it now runs
against real cmd.exe on every PR.

* fix(deps): refresh the lockfile for the current patch hashes

pnpm records a hash per patched dependency, and I regenerated both
patches repeatedly across the review rounds without refreshing the
lockfile. Every local run used --frozen-lockfile's looser sibling, so
nothing caught it until CI did:

  ERR_PNPM_LOCKFILE_CONFIG_MISMATCH  Cannot proceed with the frozen
  installation. The current "patchedDependencies" configuration doesn't
  match the value found in the lockfile

Verified with pnpm install --frozen-lockfile locally this time.

* ci(windows): build node-pty from source before the win32 suites

CI proved the encoder fix on real cmd.exe -- 26/26 -- and in the same run
proved the job suite had been testing an unpatched binary. node-pty
prefers its upstream prebuild, which does not contain this patch, so
every job-object export was absent and isPtyJobOwnershipAvailable() was
false.

That guard is why the failure was loud rather than a vacuous pass, and
it is the reason the assertion exists.

Packaging was never affected: rebuild-native-deps.mjs already builds
node-pty from source for Electron and restores the ConPTY runtime files.
The gap was the node-runtime test environment only.

Not changing requiresPatchedNodePtySourceBuild's win32 exemption here.
Its premise -- that the patch is Unix-only -- is now false, but lifting
it also needs pnpm rebuild to force a source build, and I cannot
validate that on macOS and Linux from here. Recorded as a follow-up
instead of changed blind.

* test(windows): gate the host-job guarantee in CI

The daemon-level job had one hand-run proof and no automated coverage --
the same shape of gap that let an unpatched node-pty go unnoticed until
CI caught it.

It needs a real second process, because the assertion is about what
happens when that process is force-killed: a host in a kill-on-close job
must strand neither its pty nor a grandchild spawned detached, which is
the process a parent-pid walk cannot see.

Runs in the Windows PR job alongside the per-pty and encoder suites, so
both halves of the two-job design are now gated rather than asserted.

* fix(windows): serialise host-job creation

Two callers racing PtyAssignCurrentProcessToJob would each create a job,
put the process in both, and leak the first handle -- and the handle is
what keeps a kill-on-close job alive, so a leaked one is never released.
'Only JS calls it' is not a guarantee: a worker thread with its own
N-API env shares these statics.

Also records the ordering requirement it depends on.
AssignProcessToJobObject adds only the named process; children inherit
membership, but a pty that already exists does not join retroactively
and would not be reaped. The daemon assigns at startup, before the
ConPTY warmup and before any session, which is correct today and now
stated rather than implied.

* fix(daemon): keep the host job off the startup path

Assigning the host job at daemon startup resolves the node-pty native
module, which loads the ConPTY addon -- and paying that before the
endpoint is published delayed readiness enough that daemon-boot-smoke
failed on windows-latest, deterministically.

windows-conpty-warmup already carries the comment for this exact
hazard ('setImmediate keeps the ready/handshake path ahead of the
warm-up') and I put an eager load in front of it anyway.

Moved to the pty spawn path, which already pays ConPTY cost, and
memoised. Children inherit job membership, so assigning immediately
before the first spawn still covers every pty -- and nothing can spawn
one before the endpoint exists.

(cherry picked from commit 2b1254d)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
* fix(windows): own PTY process trees with job objects

Teardown used to answer 'is this tree mine, and how do I kill it?' by
scraping the process table, walking parent pids back to Orca, and running
taskkill /T /F only if the walk said yes. Every step is a guess, and the
code said so itself: windows-pty-root-identity.ts:35 already named the
fix -- 'an inherited handle / Job Object'.

The guesses fail in the ways users report. A pid walk cannot survive pid
reuse, so teardown refused whenever it could not prove ownership, and a
refused kill is an orphaned agent tree holding the worktree directory
open (stablyai#9045, stablyai#10475, stablyai#10087). A descendant that reparented is invisible
to the walk. The scrape itself could be blocked by policy, which read as
'no evidence'.

node-pty now creates a job object per ConPTY and assigns the shell under
CREATE_SUSPENDED, before it can spawn anything -- assigning afterwards
leaves a window in which a fast child escapes. Termination is one
TerminateJobObject; liveness is QueryInformationJobObject.

Verified on Windows 11 against a shell whose grandchild was spawned
detached: job membership came back [shell, grandchild] and one call
killed both. Neither a parent-pid walk nor GetConsoleProcessList sees
that grandchild -- it leaves the console and reparents, which is exactly
the claude.exe/node.exe/cmd.exe orphan in stablyai#9045.

KILL_ON_JOB_CLOSE means a daemon that dies without unwinding no longer
strands shells (stablyai#9195, stablyai#10415). The job is the daemon's, not the app's,
so an app-main crash still leaves sessions alive -- the guarantee
win-crash-survival-e2e asserts.

Both entry points report unavailable rather than a false success when a
pty has no job: an outer job without BREAKAWAY_OK can refuse the
assignment, and a pty from an older build has none. Reading 'we could
not tell' as 'already dead' is the original bug, so the old probe stays
as the fallback.

* test(windows): pin job ownership against a real detached grandchild

The unit tests pin the contract; this pins what the contract is for. A
grandchild spawned detached leaves the pane's console and reparents, so
GetConsoleProcessList and a parent-pid walk both miss it -- that is the
process that outlived its pane and held the worktree directory open.

Includes a guard that this build actually has job support, so a node-pty
rebuilt from unpatched sources fails loudly instead of letting every
assertion pass vacuously.

* fix(windows): correct the job liveness contract to what Windows actually does

I claimed an emptied tree would report [] and that this was the evidence
a stale registry entry lacks (stablyai#15549). Running it on Windows 11 showed
otherwise: node-pty drops its handle record and closes the job when the
shell exits, so a dead tree reports null.

Null therefore means unverifiable in the sense of
docs/reference/ssh-execution-boundary.md -- no job support, not a ConPTY,
or no longer tracked -- and is never evidence that processes died. A
caller reading it as proof of death would have been right by accident
after a normal exit and wrong on a host that refused the assignment.

What the API does add is descendant liveness for a tree that is still
tracked, including children that detached from the console.

* fix(windows): stop a clean shell exit from reaping backgrounded processes

Measured on Windows 11: with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the
per-PTY job, releasing the handle when the shell exits also killed
whatever the user had backgrounded. Typing 'exit' in a pane reaped a
detached server that survived before this patch.

That is a behaviour change nobody asked for. The approved change was
that killing the terminal daemon reaps its shells -- not that a clean
exit reaps your background job. The job's purpose is to make an EXPLICIT
teardown exact, which TerminateJobObject still does.

Reaping a dead daemon's shells now needs the daemon-level job the design
called for: the daemon assigns itself, children inherit membership, and
its closure on daemon death reaps them without touching clean-exit
semantics. Not in this PR; noted in the reference doc.

* test(windows): pin that a clean exit leaves backgrounded work alone

The counterpart to the tree-kill test. Without it, re-adding
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE would look like a tightening rather
than the regression it is.

* fix(windows): stop a winpty pty id from matching a ConPTY job

winpty.cc and conpty.cc each mint their 'pty' id from an independent
counter, and windowsPtyAgent stores both in the same _pty field. So a
winpty-backed terminal's id can collide with a live ConPTY baton -- and
closing that pane would have terminated an unrelated pane's entire
process tree.

Both job entry points now take the shell pid and the native side refuses
unless GetProcessId(hShell) matches, which makes the id unforgeable.

Two more from the same read-through:
- ResumeThread's failure was ignored. A shell left suspended is a pane
  that never prints and never exits, which is far harder to diagnose
  than a failed spawn; it now cleans up and throws.
- handle->hJob was assigned before LoadConptyDll, which can throw. A
  baton carrying a job but never reaching SetupExitCallback has nothing
  left to close it, so the assignment moved down beside hShell.

* docs(windows): record the unsynchronised node-pty baton table

Pre-existing upstream -- the exit thread erases while the main thread
reads -- but terminatePtyJob adds an instance of it, so it belongs in
writing rather than in someone's head.

* fix(windows): close four gaps found in review

BREAKAWAY. The per-PTY job set no limits, so a child asking for
CREATE_BREAKAWAY_FROM_JOB was refused with ERROR_ACCESS_DENIED.
Installers, msiexec and some updater and service-control paths spawn
that way deliberately -- they worked before this patch and would have
failed only inside an Orca terminal, which is the worst shape a bug
report can take. JOB_OBJECT_LIMIT_BREAKAWAY_OK restores it; a child
still has to ask, so ordinary descendants stay owned.

EMPTY IS NOT UNAVAILABLE. The native reader returns an empty list --
not an error -- when CreateToolhelp32Snapshot fails, which is what an
EDR hook or a restricted token produces. Callers read that as 'nothing
is running' and teardown concludes a live PTY root is already gone. The
snapshot must contain the querying process; nothing else is
unfalsifiable, and one predicate catches empty, truncated and
permission-filtered tables alike.

NO DEADLINE. Replacing execFile dropped its 3s timeout. The vendored
reader latches a module-global while a request is in flight and clears
it only after draining its callbacks, with no try/catch -- so one wedge
leaves every later call queued behind a promise that never settles, and
the process table is dead for the life of the app. The bound is back.

GUESSED IMAGE PATH. executablePath was derived from the first
space-delimited token, which reads 'C:\Program' out of an unquoted
'C:\Program Files\nodejs\node.exe ...'. Wrong evidence is worse than
none, and the only consumer already had the full path in , so
the field is gone rather than repaired.

Also: remove_pty_baton no longer sits inside assert(), which NDEBUG
would compile away along with the call, and the job accessors hold a
lock across lookup and use -- handle values are recycled, so an
unguarded read could pass the shell-pid check against an unrelated
process and terminate the wrong job.

* fix(windows): apply the job lock once per accessor

The patch script matched a string its own replacement still contained, so
PtyTerminateJob got two lock_guards named guard and PtyListJobProcessIds
got none. MSVC caught it: error C2374 redefinition.

* test(windows): pin that a child can still break away from the job

Verified on Windows 11: 'start /b' writes its marker and no access-denied
appears. Without JOB_OBJECT_LIMIT_BREAKAWAY_OK this fails, and it fails
only inside an Orca terminal -- so the failure would look like Orca
corrupting unrelated software rather than like a job-object change.

* fix(windows): stop the ownership guard from reading a closing handle

The guard called GetProcessId(hShell) to prove identity, but the exit
watcher closes hShell on another thread -- so the guard could read a
closed handle, and under strict handle checks that is fatal rather than
merely wrong. Worse, it widened the gap between validating hJob and
using it from two instructions to a kernel round-trip, and handle values
recycle: the likeliest occupant of a freshly recycled value in this
process is another pane's job.

The pid never needed a handle. It is captured at spawn and compared as a
DWORD, so the guard touches no handle at all, and hShell is now closed
inside the same lock as hJob.

Also from review:
- reject CR/LF in a cmd argument. cmd ends the command at a raw line
  break whatever the quote state, so there is no escape for it; encoding
  one anyway truncates the argument and can leave the remainder to run
  as a command. Agent prompts are this encoder's motivating input.
- ask the process table only for the fields a caller needs. Memory and
  CommandLine each cost an OpenProcess per process, inline, for every
  process on the box -- and the 1024 bound is patched out. Ancestry
  reads now skip both.
- corpus gains the degenerate quote-only and two-quote arguments.
- PtyListJobProcessIds' docblock still taught the empty-list contract
  that was corrected on the TS side, and now records that the ConPTY
  console host is never a job member.
- drop a write to NumberOfAssignedProcesses, which is output-only.
- pty_baton::hShell is initialised; ownsShell was only safe because &&
  short-circuited ahead of it.

The backgrounded-child test is rescoped: 'start /b' uses
CREATE_NEW_CONSOLE, not CREATE_BREAKAWAY_FROM_JOB, so it proves job
membership does not block backgrounding -- not that BREAKAWAY_OK works.
That flag rests on the Win32 contract, and I have said so rather than
letting the test imply coverage it does not have.

* fix(windows): bound retries after the process table wedges

The 3s deadline stops a caller hanging, but the timed-out call leaves its
callback in the vendored module's queue -- and that queue drains only
when the latched request completes, which in this wedge never happens.
Retrying at the caller's poll rate would add a closure per tick forever.
A 30s cooldown bounds it to one probe, and a late callback clears the
cooldown because it proves the reader recovered.

Also pins the deadlock invariant in the patch: the exit thread's lock
must close before tsfn.BlockingCall, because that waits on the JS thread
and the JS thread can be waiting on the same mutex inside
PtyTerminateJob. Correct today by scoping; a comment so a later refactor
does not widen it.

* revert(windows): drop the field-selection API, which cannot pay off

I added it for a real perf finding -- Memory and CommandLine each cost an
OpenProcess per process -- and then never wired a caller, so the claim
that ancestry reads skip them was wrong.

Wiring it would have been worse than leaving it dead. The only ancestry
consumer is the teardown identity probe, which needs a snapshot that
started AFTER it asked, for pid-recycle detection. Bypassing the shared
reader to get narrow fields would let that request join a scan already in
flight -- trading a correctness guarantee for milliseconds.

Field selection only pays off if callers can ask for less, and they
cannot: one shared snapshot serves every caller so a 32-wide teardown
collapses into a single scan, which means it has to carry every field.
The reasoning now lives next to the flags instead of in a dead export.

* fix(process): three P1s from review — a crash vector and two wedge bugs

STDIN EPIPE COULD TAKE DOWN THE MAIN PROCESS. A child that exits without
reading makes the queued write fail with EPIPE, and an unhandled error on
a stream is an uncaught exception. The child's own error listener does
not cover its stdin stream, so runProcess({ input }) against a
short-lived child was a crash, not a failed call.

THE COOLDOWN LEAKED A BATCH PER CYCLE INSTEAD OF BOUNDING IT. At expiry
every concurrent caller passed the check before any of them re-armed it,
so each enqueued a callback into the still-latched native queue and each
cycle leaked another batch. The cooldown is now re-armed BEFORE probing,
so exactly one caller gets through.

A SYNCHRONOUS THROW LEFT ITS DEADLINE RUNNING. The timer was declared
inside the try, so catch could not clear it; it fired later and wedged a
reader that had already recovered. Hoisted and cleared, and wedge state
now carries a generation so a request that lost its deadline cannot
mutate it on behalf of the one that replaced it.

Found by review once the prompts were short enough for the reviewer to
finish -- the previous two rounds died on prompt length.

* fix(process): stop a stream error from crashing the main process

Same class as the stdin EPIPE finding, two instances further on: stdout
and stderr had data listeners and no error listeners, and an unhandled
error on a stream is an uncaught exception.

Scoped to runProcess, which owns the child outright. spawnProcess hands
the streams to its caller, and a blanket handler there defeats callers
that track and remove their own listeners -- the SSH ProxyCommand
transport does exactly that, and its cleanup test caught the attempt.
Documented on spawnProcess so the boundary is explicit rather than
inferred.

* fix(windows): validate the ConPTY DLL before creating the process

LoadConptyDll throws when conpty.dll is missing -- a real state, and one
this branch hit during development. It ran after CreateProcessW and
ResumeThread but before the baton and the exit watcher were installed,
so a throw leaked the job, process and thread handles and left an
untracked shell tree running. Once per attempt, so a broken install
accumulates orphan shells on every retry.

Resolving the DLL first costs nothing and leaves exactly two throws
after creation: the CreateProcessW failure, where nothing exists yet,
and the resume failure, which already cleans up after itself.

This also closes the same leak for hProcess and hThread, which predates
the job work.

* feat(windows): add the daemon-level job the design called for

The plan specified two nested jobs and I built one. That gap is why
dropping KILL_ON_JOB_CLOSE from the per-PTY job cost the approved
guarantee that a dead daemon reaps its shells -- I had one job trying to
answer two questions, and the two answers conflict.

They are separate jobs. The per-PTY job answers 'kill exactly this
pane's tree, now', and cannot be kill-on-close because its handle is
released when the shell exits, which would reap whatever the user
backgrounded. The daemon assigns itself to a second job that IS
kill-on-close; its handle is released only when the daemon dies.
Children inherit membership, so every pty is covered and the per-PTY
jobs nest inside it.

Daemon, never app: an app-main crash must still leave sessions alive,
which win-crash-survival-e2e asserts. Both jobs carry BREAKAWAY_OK, or a
child asking to break away is refused at whichever level lacks it.

Restores stablyai#9195 and stablyai#10415, which I withdrew from this PR earlier.

* docs(windows): record what the host job does not cover

An app-hosted PTY gets a per-PTY job but no crash reaping, because the
alternative is a kill-on-close job on the app -- which is precisely what
the crash-survival guarantee forbids.

* ci(windows): run the win32 suites in the PR windows job

Both were skip-on-non-win32 and had only ever run on one machine I drive
by hand -- which went unreachable at exactly the moment I needed to
verify the percent-escaping fix. Verification that depends on one box is
not verification.

The job already builds node-pty from patched source and already runs a
useConptyDll test, so the ConPTY runtime files are in place by this
step. This also makes the encoder a gate: the corpus is the only thing
standing between an agent prompt and a mangled argv, and it now runs
against real cmd.exe on every PR.

* fix(deps): refresh the lockfile for the current patch hashes

pnpm records a hash per patched dependency, and I regenerated both
patches repeatedly across the review rounds without refreshing the
lockfile. Every local run used --frozen-lockfile's looser sibling, so
nothing caught it until CI did:

  ERR_PNPM_LOCKFILE_CONFIG_MISMATCH  Cannot proceed with the frozen
  installation. The current "patchedDependencies" configuration doesn't
  match the value found in the lockfile

Verified with pnpm install --frozen-lockfile locally this time.

* ci(windows): build node-pty from source before the win32 suites

CI proved the encoder fix on real cmd.exe -- 26/26 -- and in the same run
proved the job suite had been testing an unpatched binary. node-pty
prefers its upstream prebuild, which does not contain this patch, so
every job-object export was absent and isPtyJobOwnershipAvailable() was
false.

That guard is why the failure was loud rather than a vacuous pass, and
it is the reason the assertion exists.

Packaging was never affected: rebuild-native-deps.mjs already builds
node-pty from source for Electron and restores the ConPTY runtime files.
The gap was the node-runtime test environment only.

Not changing requiresPatchedNodePtySourceBuild's win32 exemption here.
Its premise -- that the patch is Unix-only -- is now false, but lifting
it also needs pnpm rebuild to force a source build, and I cannot
validate that on macOS and Linux from here. Recorded as a follow-up
instead of changed blind.

* test(windows): gate the host-job guarantee in CI

The daemon-level job had one hand-run proof and no automated coverage --
the same shape of gap that let an unpatched node-pty go unnoticed until
CI caught it.

It needs a real second process, because the assertion is about what
happens when that process is force-killed: a host in a kill-on-close job
must strand neither its pty nor a grandchild spawned detached, which is
the process a parent-pid walk cannot see.

Runs in the Windows PR job alongside the per-pty and encoder suites, so
both halves of the two-job design are now gated rather than asserted.

* fix(windows): serialise host-job creation

Two callers racing PtyAssignCurrentProcessToJob would each create a job,
put the process in both, and leak the first handle -- and the handle is
what keeps a kill-on-close job alive, so a leaked one is never released.
'Only JS calls it' is not a guarantee: a worker thread with its own
N-API env shares these statics.

Also records the ordering requirement it depends on.
AssignProcessToJobObject adds only the named process; children inherit
membership, but a pty that already exists does not join retroactively
and would not be reaped. The daemon assigns at startup, before the
ConPTY warmup and before any session, which is correct today and now
stated rather than implied.

* fix(daemon): keep the host job off the startup path

Assigning the host job at daemon startup resolves the node-pty native
module, which loads the ConPTY addon -- and paying that before the
endpoint is published delayed readiness enough that daemon-boot-smoke
failed on windows-latest, deterministically.

windows-conpty-warmup already carries the comment for this exact
hazard ('setImmediate keeps the ready/handshake path ahead of the
warm-up') and I put an eager load in front of it anyway.

Moved to the pty spawn path, which already pays ConPTY cost, and
memoised. Children inherit job membership, so assigning immediately
before the first spawn still covers every pty -- and nothing can spawn
one before the endpoint exists.
@AmethystLiang

Copy link
Copy Markdown
Contributor

thanks for reporting. looking into it

@AmethystLiang

Copy link
Copy Markdown
Contributor

thanks for reporting. looking into it

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(windows): own PTY process trees with job objects

Teardown used to answer 'is this tree mine, and how do I kill it?' by
scraping the process table, walking parent pids back to Orca, and running
taskkill /T /F only if the walk said yes. Every step is a guess, and the
code said so itself: windows-pty-root-identity.ts:35 already named the
fix -- 'an inherited handle / Job Object'.

The guesses fail in the ways users report. A pid walk cannot survive pid
reuse, so teardown refused whenever it could not prove ownership, and a
refused kill is an orphaned agent tree holding the worktree directory
open (stablyai#9045, stablyai#10475, stablyai#10087). A descendant that reparented is invisible
to the walk. The scrape itself could be blocked by policy, which read as
'no evidence'.

node-pty now creates a job object per ConPTY and assigns the shell under
CREATE_SUSPENDED, before it can spawn anything -- assigning afterwards
leaves a window in which a fast child escapes. Termination is one
TerminateJobObject; liveness is QueryInformationJobObject.

Verified on Windows 11 against a shell whose grandchild was spawned
detached: job membership came back [shell, grandchild] and one call
killed both. Neither a parent-pid walk nor GetConsoleProcessList sees
that grandchild -- it leaves the console and reparents, which is exactly
the claude.exe/node.exe/cmd.exe orphan in stablyai#9045.

KILL_ON_JOB_CLOSE means a daemon that dies without unwinding no longer
strands shells (stablyai#9195, stablyai#10415). The job is the daemon's, not the app's,
so an app-main crash still leaves sessions alive -- the guarantee
win-crash-survival-e2e asserts.

Both entry points report unavailable rather than a false success when a
pty has no job: an outer job without BREAKAWAY_OK can refuse the
assignment, and a pty from an older build has none. Reading 'we could
not tell' as 'already dead' is the original bug, so the old probe stays
as the fallback.

* test(windows): pin job ownership against a real detached grandchild

The unit tests pin the contract; this pins what the contract is for. A
grandchild spawned detached leaves the pane's console and reparents, so
GetConsoleProcessList and a parent-pid walk both miss it -- that is the
process that outlived its pane and held the worktree directory open.

Includes a guard that this build actually has job support, so a node-pty
rebuilt from unpatched sources fails loudly instead of letting every
assertion pass vacuously.

* fix(windows): correct the job liveness contract to what Windows actually does

I claimed an emptied tree would report [] and that this was the evidence
a stale registry entry lacks (stablyai#15549). Running it on Windows 11 showed
otherwise: node-pty drops its handle record and closes the job when the
shell exits, so a dead tree reports null.

Null therefore means unverifiable in the sense of
docs/reference/ssh-execution-boundary.md -- no job support, not a ConPTY,
or no longer tracked -- and is never evidence that processes died. A
caller reading it as proof of death would have been right by accident
after a normal exit and wrong on a host that refused the assignment.

What the API does add is descendant liveness for a tree that is still
tracked, including children that detached from the console.

* fix(windows): stop a clean shell exit from reaping backgrounded processes

Measured on Windows 11: with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE on the
per-PTY job, releasing the handle when the shell exits also killed
whatever the user had backgrounded. Typing 'exit' in a pane reaped a
detached server that survived before this patch.

That is a behaviour change nobody asked for. The approved change was
that killing the terminal daemon reaps its shells -- not that a clean
exit reaps your background job. The job's purpose is to make an EXPLICIT
teardown exact, which TerminateJobObject still does.

Reaping a dead daemon's shells now needs the daemon-level job the design
called for: the daemon assigns itself, children inherit membership, and
its closure on daemon death reaps them without touching clean-exit
semantics. Not in this PR; noted in the reference doc.

* test(windows): pin that a clean exit leaves backgrounded work alone

The counterpart to the tree-kill test. Without it, re-adding
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE would look like a tightening rather
than the regression it is.

* fix(windows): stop a winpty pty id from matching a ConPTY job

winpty.cc and conpty.cc each mint their 'pty' id from an independent
counter, and windowsPtyAgent stores both in the same _pty field. So a
winpty-backed terminal's id can collide with a live ConPTY baton -- and
closing that pane would have terminated an unrelated pane's entire
process tree.

Both job entry points now take the shell pid and the native side refuses
unless GetProcessId(hShell) matches, which makes the id unforgeable.

Two more from the same read-through:
- ResumeThread's failure was ignored. A shell left suspended is a pane
  that never prints and never exits, which is far harder to diagnose
  than a failed spawn; it now cleans up and throws.
- handle->hJob was assigned before LoadConptyDll, which can throw. A
  baton carrying a job but never reaching SetupExitCallback has nothing
  left to close it, so the assignment moved down beside hShell.

* docs(windows): record the unsynchronised node-pty baton table

Pre-existing upstream -- the exit thread erases while the main thread
reads -- but terminatePtyJob adds an instance of it, so it belongs in
writing rather than in someone's head.

* fix(windows): close four gaps found in review

BREAKAWAY. The per-PTY job set no limits, so a child asking for
CREATE_BREAKAWAY_FROM_JOB was refused with ERROR_ACCESS_DENIED.
Installers, msiexec and some updater and service-control paths spawn
that way deliberately -- they worked before this patch and would have
failed only inside an Orca terminal, which is the worst shape a bug
report can take. JOB_OBJECT_LIMIT_BREAKAWAY_OK restores it; a child
still has to ask, so ordinary descendants stay owned.

EMPTY IS NOT UNAVAILABLE. The native reader returns an empty list --
not an error -- when CreateToolhelp32Snapshot fails, which is what an
EDR hook or a restricted token produces. Callers read that as 'nothing
is running' and teardown concludes a live PTY root is already gone. The
snapshot must contain the querying process; nothing else is
unfalsifiable, and one predicate catches empty, truncated and
permission-filtered tables alike.

NO DEADLINE. Replacing execFile dropped its 3s timeout. The vendored
reader latches a module-global while a request is in flight and clears
it only after draining its callbacks, with no try/catch -- so one wedge
leaves every later call queued behind a promise that never settles, and
the process table is dead for the life of the app. The bound is back.

GUESSED IMAGE PATH. executablePath was derived from the first
space-delimited token, which reads 'C:\Program' out of an unquoted
'C:\Program Files\nodejs\node.exe ...'. Wrong evidence is worse than
none, and the only consumer already had the full path in , so
the field is gone rather than repaired.

Also: remove_pty_baton no longer sits inside assert(), which NDEBUG
would compile away along with the call, and the job accessors hold a
lock across lookup and use -- handle values are recycled, so an
unguarded read could pass the shell-pid check against an unrelated
process and terminate the wrong job.

* fix(windows): apply the job lock once per accessor

The patch script matched a string its own replacement still contained, so
PtyTerminateJob got two lock_guards named guard and PtyListJobProcessIds
got none. MSVC caught it: error C2374 redefinition.

* test(windows): pin that a child can still break away from the job

Verified on Windows 11: 'start /b' writes its marker and no access-denied
appears. Without JOB_OBJECT_LIMIT_BREAKAWAY_OK this fails, and it fails
only inside an Orca terminal -- so the failure would look like Orca
corrupting unrelated software rather than like a job-object change.

* fix(windows): stop the ownership guard from reading a closing handle

The guard called GetProcessId(hShell) to prove identity, but the exit
watcher closes hShell on another thread -- so the guard could read a
closed handle, and under strict handle checks that is fatal rather than
merely wrong. Worse, it widened the gap between validating hJob and
using it from two instructions to a kernel round-trip, and handle values
recycle: the likeliest occupant of a freshly recycled value in this
process is another pane's job.

The pid never needed a handle. It is captured at spawn and compared as a
DWORD, so the guard touches no handle at all, and hShell is now closed
inside the same lock as hJob.

Also from review:
- reject CR/LF in a cmd argument. cmd ends the command at a raw line
  break whatever the quote state, so there is no escape for it; encoding
  one anyway truncates the argument and can leave the remainder to run
  as a command. Agent prompts are this encoder's motivating input.
- ask the process table only for the fields a caller needs. Memory and
  CommandLine each cost an OpenProcess per process, inline, for every
  process on the box -- and the 1024 bound is patched out. Ancestry
  reads now skip both.
- corpus gains the degenerate quote-only and two-quote arguments.
- PtyListJobProcessIds' docblock still taught the empty-list contract
  that was corrected on the TS side, and now records that the ConPTY
  console host is never a job member.
- drop a write to NumberOfAssignedProcesses, which is output-only.
- pty_baton::hShell is initialised; ownsShell was only safe because &&
  short-circuited ahead of it.

The backgrounded-child test is rescoped: 'start /b' uses
CREATE_NEW_CONSOLE, not CREATE_BREAKAWAY_FROM_JOB, so it proves job
membership does not block backgrounding -- not that BREAKAWAY_OK works.
That flag rests on the Win32 contract, and I have said so rather than
letting the test imply coverage it does not have.

* fix(windows): bound retries after the process table wedges

The 3s deadline stops a caller hanging, but the timed-out call leaves its
callback in the vendored module's queue -- and that queue drains only
when the latched request completes, which in this wedge never happens.
Retrying at the caller's poll rate would add a closure per tick forever.
A 30s cooldown bounds it to one probe, and a late callback clears the
cooldown because it proves the reader recovered.

Also pins the deadlock invariant in the patch: the exit thread's lock
must close before tsfn.BlockingCall, because that waits on the JS thread
and the JS thread can be waiting on the same mutex inside
PtyTerminateJob. Correct today by scoping; a comment so a later refactor
does not widen it.

* revert(windows): drop the field-selection API, which cannot pay off

I added it for a real perf finding -- Memory and CommandLine each cost an
OpenProcess per process -- and then never wired a caller, so the claim
that ancestry reads skip them was wrong.

Wiring it would have been worse than leaving it dead. The only ancestry
consumer is the teardown identity probe, which needs a snapshot that
started AFTER it asked, for pid-recycle detection. Bypassing the shared
reader to get narrow fields would let that request join a scan already in
flight -- trading a correctness guarantee for milliseconds.

Field selection only pays off if callers can ask for less, and they
cannot: one shared snapshot serves every caller so a 32-wide teardown
collapses into a single scan, which means it has to carry every field.
The reasoning now lives next to the flags instead of in a dead export.

* fix(process): three P1s from review — a crash vector and two wedge bugs

STDIN EPIPE COULD TAKE DOWN THE MAIN PROCESS. A child that exits without
reading makes the queued write fail with EPIPE, and an unhandled error on
a stream is an uncaught exception. The child's own error listener does
not cover its stdin stream, so runProcess({ input }) against a
short-lived child was a crash, not a failed call.

THE COOLDOWN LEAKED A BATCH PER CYCLE INSTEAD OF BOUNDING IT. At expiry
every concurrent caller passed the check before any of them re-armed it,
so each enqueued a callback into the still-latched native queue and each
cycle leaked another batch. The cooldown is now re-armed BEFORE probing,
so exactly one caller gets through.

A SYNCHRONOUS THROW LEFT ITS DEADLINE RUNNING. The timer was declared
inside the try, so catch could not clear it; it fired later and wedged a
reader that had already recovered. Hoisted and cleared, and wedge state
now carries a generation so a request that lost its deadline cannot
mutate it on behalf of the one that replaced it.

Found by review once the prompts were short enough for the reviewer to
finish -- the previous two rounds died on prompt length.

* fix(process): stop a stream error from crashing the main process

Same class as the stdin EPIPE finding, two instances further on: stdout
and stderr had data listeners and no error listeners, and an unhandled
error on a stream is an uncaught exception.

Scoped to runProcess, which owns the child outright. spawnProcess hands
the streams to its caller, and a blanket handler there defeats callers
that track and remove their own listeners -- the SSH ProxyCommand
transport does exactly that, and its cleanup test caught the attempt.
Documented on spawnProcess so the boundary is explicit rather than
inferred.

* fix(windows): validate the ConPTY DLL before creating the process

LoadConptyDll throws when conpty.dll is missing -- a real state, and one
this branch hit during development. It ran after CreateProcessW and
ResumeThread but before the baton and the exit watcher were installed,
so a throw leaked the job, process and thread handles and left an
untracked shell tree running. Once per attempt, so a broken install
accumulates orphan shells on every retry.

Resolving the DLL first costs nothing and leaves exactly two throws
after creation: the CreateProcessW failure, where nothing exists yet,
and the resume failure, which already cleans up after itself.

This also closes the same leak for hProcess and hThread, which predates
the job work.

* feat(windows): add the daemon-level job the design called for

The plan specified two nested jobs and I built one. That gap is why
dropping KILL_ON_JOB_CLOSE from the per-PTY job cost the approved
guarantee that a dead daemon reaps its shells -- I had one job trying to
answer two questions, and the two answers conflict.

They are separate jobs. The per-PTY job answers 'kill exactly this
pane's tree, now', and cannot be kill-on-close because its handle is
released when the shell exits, which would reap whatever the user
backgrounded. The daemon assigns itself to a second job that IS
kill-on-close; its handle is released only when the daemon dies.
Children inherit membership, so every pty is covered and the per-PTY
jobs nest inside it.

Daemon, never app: an app-main crash must still leave sessions alive,
which win-crash-survival-e2e asserts. Both jobs carry BREAKAWAY_OK, or a
child asking to break away is refused at whichever level lacks it.

Restores stablyai#9195 and stablyai#10415, which I withdrew from this PR earlier.

* docs(windows): record what the host job does not cover

An app-hosted PTY gets a per-PTY job but no crash reaping, because the
alternative is a kill-on-close job on the app -- which is precisely what
the crash-survival guarantee forbids.

* ci(windows): run the win32 suites in the PR windows job

Both were skip-on-non-win32 and had only ever run on one machine I drive
by hand -- which went unreachable at exactly the moment I needed to
verify the percent-escaping fix. Verification that depends on one box is
not verification.

The job already builds node-pty from patched source and already runs a
useConptyDll test, so the ConPTY runtime files are in place by this
step. This also makes the encoder a gate: the corpus is the only thing
standing between an agent prompt and a mangled argv, and it now runs
against real cmd.exe on every PR.

* fix(deps): refresh the lockfile for the current patch hashes

pnpm records a hash per patched dependency, and I regenerated both
patches repeatedly across the review rounds without refreshing the
lockfile. Every local run used --frozen-lockfile's looser sibling, so
nothing caught it until CI did:

  ERR_PNPM_LOCKFILE_CONFIG_MISMATCH  Cannot proceed with the frozen
  installation. The current "patchedDependencies" configuration doesn't
  match the value found in the lockfile

Verified with pnpm install --frozen-lockfile locally this time.

* ci(windows): build node-pty from source before the win32 suites

CI proved the encoder fix on real cmd.exe -- 26/26 -- and in the same run
proved the job suite had been testing an unpatched binary. node-pty
prefers its upstream prebuild, which does not contain this patch, so
every job-object export was absent and isPtyJobOwnershipAvailable() was
false.

That guard is why the failure was loud rather than a vacuous pass, and
it is the reason the assertion exists.

Packaging was never affected: rebuild-native-deps.mjs already builds
node-pty from source for Electron and restores the ConPTY runtime files.
The gap was the node-runtime test environment only.

Not changing requiresPatchedNodePtySourceBuild's win32 exemption here.
Its premise -- that the patch is Unix-only -- is now false, but lifting
it also needs pnpm rebuild to force a source build, and I cannot
validate that on macOS and Linux from here. Recorded as a follow-up
instead of changed blind.

* test(windows): gate the host-job guarantee in CI

The daemon-level job had one hand-run proof and no automated coverage --
the same shape of gap that let an unpatched node-pty go unnoticed until
CI caught it.

It needs a real second process, because the assertion is about what
happens when that process is force-killed: a host in a kill-on-close job
must strand neither its pty nor a grandchild spawned detached, which is
the process a parent-pid walk cannot see.

Runs in the Windows PR job alongside the per-pty and encoder suites, so
both halves of the two-job design are now gated rather than asserted.

* fix(windows): serialise host-job creation

Two callers racing PtyAssignCurrentProcessToJob would each create a job,
put the process in both, and leak the first handle -- and the handle is
what keeps a kill-on-close job alive, so a leaked one is never released.
'Only JS calls it' is not a guarantee: a worker thread with its own
N-API env shares these statics.

Also records the ordering requirement it depends on.
AssignProcessToJobObject adds only the named process; children inherit
membership, but a pty that already exists does not join retroactively
and would not be reaped. The daemon assigns at startup, before the
ConPTY warmup and before any session, which is correct today and now
stated rather than implied.

* fix(daemon): keep the host job off the startup path

Assigning the host job at daemon startup resolves the node-pty native
module, which loads the ConPTY addon -- and paying that before the
endpoint is published delayed readiness enough that daemon-boot-smoke
failed on windows-latest, deterministically.

windows-conpty-warmup already carries the comment for this exact
hazard ('setImmediate keeps the ready/handshake path ahead of the
warm-up') and I put an eager load in front of it anyway.

Moved to the pty spawn path, which already pays ConPTY cost, and
memoised. Children inherit job membership, so assigning immediately
before the first spawn still covers every pty -- and nothing can spawn
one before the endpoint exists.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Worktree deletion fails with "Failed to physically stop every PTY" — orphaned claude.exe/node.exe/cmd.exe processes on Windows

3 participants