Repository navigation
fix(windows): revalidate PTY liveness from the job object, not a forked helper - #16419
Conversation
…rked helper node-pty answers "which processes are attached to this pane's console?" by FORKING a helper, because GetConsoleProcessList must run from a process attached to that console. Orca asked on a foreground poll, per pane, so each read spawned a conpty_console_list_agent -- hundreds of hidden processes exhausting RAM within minutes, respawning as fast as they were killed (#10857). QueryInformationJobObject has no console-attachment constraint: any process holding the job handle can ask. Orca already creates that job per PTY, and listPtyJobProcessIds has exposed it since the W1/W2 work with zero callers. One syscall, no children. Semantics the three call sites rely on are preserved: a root-only set still proves the shell is alone (so a stale agent can be retired), and size > 1 still proves something is running under it. The single difference is that a descendant detached from the console stays in the job -- which widens the set, the conservative direction for every caller. Also fixes the third call site, which returned { available: false } whenever membership was unavailable AND a recognized agent existed -- i.e. exactly while an agent was running. Membership only ever narrowed the candidate list, so an unavailable answer now leaves it unfiltered instead of failing the whole resolution. The no-fork test is asserted through a module-level vi.mock of node:child_process. A vi.spyOn of a require()'d child_process does not intercept the module's own import binding: the first version of that test passed with a fork() deliberately reintroduced.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds synchronous Windows PTY job-membership lookup and asynchronous console-attached process lookup. Foreground resolution now fails closed when console membership is unavailable. Daemon and local PTY tracking use job membership for cached-agent revalidation, with age-based retirement for detached descendants. Tests update provider mocks, cover lookup failure and timeout behavior, validate cached identity retention, and add the new tests to reliability gates. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Linked Issues checkExplanation The changes address issue Full details: Out of Scope Changes checkExplanation The production changes, helper renames, test updates, new coverage, import allowlist update, and reliability-gate configuration all support the Windows foreground process and helper-fork changes for issue Full details: Description checkExplanation The description follows the repository template. It explains the problem, changes, rationale, user impact, linked issue, testing, visual proof, review invariants, and checklist status. The AI Disclosure section is blank, but the description is otherwise complete and on topic. ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/providers/windows-conpty-process-membership.ts (1)
8-33: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the incident narrative. Keep the contract and the reason for the job-object lookup. Remove repeated incident history from source and tests.
src/main/providers/windows-conpty-process-membership.ts#L8-L33: reduce this block to a short contract comment.src/main/providers/windows-conpty-process-membership.test.ts#L19-L25: remove the duplicate implementation history.
As per coding guidelines: “DO NOT: be verbose” and “BE CONCISE. 1 LINE if possible.”Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c3e76abd-70fc-474a-bd81-c3ba2d71e19c
📒 Files selected for processing (10)
src/main/daemon/pty-subprocess-foreground-degraded-scan.test.tssrc/main/daemon/pty-subprocess/foreground-process-tracker.tssrc/main/providers/agent-foreground-process-pi.test.tssrc/main/providers/agent-foreground-process.test.tssrc/main/providers/local-pty-provider-foreground-process.test.tssrc/main/providers/local-pty-provider-test-harness.tssrc/main/providers/local-pty-provider.tssrc/main/providers/windows-agent-foreground-process.tssrc/main/providers/windows-conpty-process-membership.test.tssrc/main/providers/windows-conpty-process-membership.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Validated on real Windows hardware, including a WSL paneRun against the installed app's own patched node-pty ( For each case I spawned a real ConPTY and asked both ways — the new job read and the old forked console-list helper — then compared:
The WSL case is the interesting one and it behaves as predicted. The job reports 4 pids where the console reports 2 — the extra two are the WSL-side processes that are not console members. That is the documented delta: the job is a superset, which widens membership. For all three callers that is the conservative direction — it keeps a live agent rather than retiring it early — and the So on a patched build the new path is equivalent where it matters and strictly more informative for WSL panes, with zero forked helpers. Note on availabilityWhen I checked this machine earlier for #16059, the installed app's native had only the five base exports. It now has all three job symbols, so the patch has reached this build. On a build without it, |
Readiness review caught that this PR changed two different questions as if they were one, and the repo's own plan doc had already said so: "The job is the wrong set here -- it would re-admit precisely the detached process the filter exists to drop." (windows-wsl-root-cause-plan.html, Use B) The two uses: - Use A, `size > 1` at local-pty-provider and the daemon tracker -- "is anything in this pane besides the shell?". The job answers this, in-process and with no fork. Unchanged from the previous commit. - Use B, the candidate filter -- "which of these are ATTACHED TO THIS CONSOLE?". Its whole job is dropping a descendant that detached, and the job object keeps those, so answering it from the job makes the filter a no-op in its motivating case: a detached `Start-Process droid` would be granted byte authority, and a detached sibling would make an attached agent look ambiguous. Use B goes back to GetConsoleProcessList, in its own module named for what it answers, with its fail-closed null restored. That path is not the #10857 storm: it runs only when a recognized agent candidate already exists, not on every foreground poll. Bounding it to one pooled supervised helper is the remaining half, and per the plan doc either half alone takes #10857 from unbounded to one. My earlier claim that widening membership is "the conservative direction for every caller" was wrong -- true for Use A, backwards for Use B. The hardware run did not catch it because I measured a WSL pane, where the superset is harmless, and never a detached GUI child, which is the divergence.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8ed9217e-563b-4023-bd53-e9f4642f17d0
📒 Files selected for processing (7)
src/main/daemon/pty-subprocess/foreground-process-tracker.tssrc/main/providers/agent-foreground-process-pi.test.tssrc/main/providers/agent-foreground-process.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/windows-agent-foreground-process.tssrc/main/providers/windows-conpty-process-membership.test.tssrc/main/providers/windows-console-attached-processes.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
Round 2 of review. Two blockers, both from moving the forking code to a new file without moving what guarded it. - The child_process import ratchet was RED: windows-console-attached-processes.ts imports node:child_process and was unlisted, and the old entry was stale. I never ran that suite -- lint and the providers/daemon tests both pass without it, which is exactly the gap the ratchet exists to close. Entry repointed; count unchanged at 159. - The forking module had ZERO tests. Its 11 assertions -- bounded timeout, single kill, spawn error, malformed message, helper-pid removal -- were in the file that now answers a different question, so the module that actually caused #10857 was shipping untested. Moved with the code. Also: nothing pinned the round-1 fix itself. No test drove console attachment to null and asserted the fail-closed result, so re-deleting that branch would have gone green. Now covered, and verified to fail when the branch is removed. Cleanups the split left behind: `consoleMembershipUnavailable`/`consoleProcessIds` renamed to `pane*` where they now hold job membership, the duplicated `WindowsConptyMembershipDeps` type name, comments still describing the console on the job path, and eight reliability-gate paths pointing at the moved tests.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/providers/windows-console-attached-processes.test.ts (1)
1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the file preamble. The test names already describe these cases. Keep one short comment for the relocation reason.
As per coding guidelines: “DO NOT: be verbose, explain the obvious, walk through the code ("WHY not HOW").”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b869b225-8f03-41b2-9aff-dcb6c6b3ff96
📒 Files selected for processing (7)
config/reliability-gates.jsoncsrc/main/daemon/pty-subprocess/foreground-process-tracker.tssrc/main/providers/agent-foreground-process.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/windows-console-attached-processes.test.tssrc/main/providers/windows-console-attached-processes.tssrc/shared/child-process/__fixtures__/child-process-import-allowlist.txt
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/daemon/pty-subprocess/foreground-process-tracker.ts
- src/main/providers/local-pty-provider.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
…irement Round 3. The job read had reintroduced #9258's bug by a new mechanism. `size > 1` returned unconditionally, so any pane holding a console-detached descendant never retired its cached agent. A WSL pane always holds some: the measurement in this PR's own test recorded job [40980,104068,4888,69908] against console [69908,40980], i.e. console said "shell alone, retire" while the job said "three others alive, keep". #9258's third commit describes the identical failure from the other direction -- a bare shell reading as [helper, shell] "looked like it still had a child ... the foreground refresh held the exited agent's identity indefinitely" -- and that is what came back. It bites because the read branch that serves the cached name across a Windows shell fallback is deliberately untimed: #9258 made it so on the stated assumption that "the background refresh authoritatively retires it". Removing the retire authority left the identity with no bound at all. Second-order: a non-null cache makes idleNoEvidenceShell false, which pins the refresh at the 1s TTL, so an idle WSL pane also scanned the process table every second forever. A TTL on the read would have been the wrong fix -- untimed is deliberate, because on Windows the fallback name is structurally uninformative. Instead the job answer is treated as what it is: a SUPERSET of the console, which cannot tell a working agent from a leftover. Proof of absence retires immediately (size 1, unchanged); an inconclusive answer ages out at 30s; unverifiable (null) still holds forever per ssh-execution-boundary.md. Only successful scans that found no agent advance the clock -- a degraded scan returns before this -- so the fix cannot expire an agent it simply failed to see. Also from review: - Restore the root requirement the forked probe had. Without it a set of one non-root pid -- shell gone, descendant alive -- read as "shell alone, retire", inverting the truth. - Rename to windows-pty-job-membership.ts / readWindowsPtyJobProcessIds. The old name still said ConPTY console while reading the job, and conflating those two sets is precisely the bug aee07c2 reverted. Same for windows-console-foreground.ts, which guards a job read now. - Gate the two files that had no coverage: the job read and the retire path.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/providers/local-pty-provider.ts (1)
1421-1428: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftBound cached-agent retention for multi-member job results.
When a WSL job retains detached processes,
paneProcessIds.size > 1remains true. Line 1426 then returnscachedAgentbefore resolution, and this cache has no age, so an exited agent can remain the foreground process for the pane lifetime. Track a refresh time and fall through after a bounded age, asforeground-process-tracker.tsdoes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: dfe3378c-7c4d-47e1-a6bb-b149972481b4
📒 Files selected for processing (28)
config/reliability-gates.jsoncsrc/main/daemon/pty-subprocess-cwd-cancel-identity.test.tssrc/main/daemon/pty-subprocess-env-inheritance.test.tssrc/main/daemon/pty-subprocess-foreground-degraded-scan.test.tssrc/main/daemon/pty-subprocess-foreground-identity.test.tssrc/main/daemon/pty-subprocess-git-credential-guard.test.tssrc/main/daemon/pty-subprocess-handle-lifecycle.test.tssrc/main/daemon/pty-subprocess-managed-agent-env.test.tssrc/main/daemon/pty-subprocess-windows-shell-launch.test.tssrc/main/daemon/pty-subprocess-wsl-launch.test.tssrc/main/daemon/pty-subprocess.test.tssrc/main/daemon/pty-subprocess/foreground-process-tracker.tssrc/main/providers/local-pty-provider-foreground-process.test.tssrc/main/providers/local-pty-provider-io-events.test.tssrc/main/providers/local-pty-provider-session-inventory.test.tssrc/main/providers/local-pty-provider-shell-readiness.test.tssrc/main/providers/local-pty-provider-shutdown.test.tssrc/main/providers/local-pty-provider-spawn-cwd-safety.test.tssrc/main/providers/local-pty-provider-spawn-env.test.tssrc/main/providers/local-pty-provider-spawn-session.test.tssrc/main/providers/local-pty-provider-test-harness.tssrc/main/providers/local-pty-provider-windows-shell-launch.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/windows-cached-agent-revalidation.test.tssrc/main/providers/windows-cached-agent-revalidation.tssrc/main/providers/windows-console-foreground.test.tssrc/main/providers/windows-pty-job-membership.test.tssrc/main/providers/windows-pty-job-membership.ts
💤 Files with no reviewable changes (1)
- src/main/providers/windows-console-foreground.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
The previous commit fixed the daemon retire path and left the identical bug in the local provider, which I found while asking the reviewer to check for it. local-pty-provider.ts returned the cached agent early on `size > 1` and that early return skips the scan at the bottom of getForegroundProcess -- the ONLY code that can delete ptyLastRecognizedForeground. So on a WSL pane, whose job always holds console-detached plumbing, the short-circuit was permanent and the identity could never be cleared. Same failure, second location, and the daemon fix did nothing for it because this path never calls retireStaleForegroundIdentity. The cache was a bare Map<id, name> with no timestamp, so bounding it needs one. Added ptyLastRecognizedForegroundAt, stamped only when the recognized name actually changes, and paired with every existing delete including pane teardown so the new map cannot outlive the old one. The 30s threshold now lives in windows-cached-agent-revalidation.ts rather than being duplicated: that module already answers "can we revalidate this cached agent without a scan", and the max age is the other half of that question. Also renamed two tests that still said "ConPTY console presence" while driving a job read. Re-conflating those two sets by name is how this PR got its first two review rounds wrong.
…change My own previous commit was wrong, and wrong in the direction #9258 exists to prevent. Review caught it; the test in this commit reproduces it first. I stamped ptyLastRecognizedForegroundAt only when the recognized name CHANGED. That makes the value the time of first recognition, so the age measures how long the agent has been running rather than how long since we last confirmed it. For a live agent recognized as the same name every cycle the stamp never moved, the age crossed 30s and stayed there, and the short-circuit died permanently. Two consequences, the second serious: - every getForegroundProcess call on a >30s-old agent pane ran the whole-table scan, defeating the exact optimization the branch exists for; - with the short-circuit off, one available-but-agentless snapshot was enough to delete a LIVE agent's identity, because paneMembershipUnavailable is false in this state so the degraded-scan substitution does not engage. That is the false "agent done" this code's own comment warns about. The daemon path was already right -- it re-stamps refreshedAt on every positive recognition -- so the same constant meant two different things in the two files. Now both mean "time since we last saw the agent", which turns the bound from "disable the short-circuit after 30s" into "force one revalidating scan every 30s": ~16-31ms per pane per 30s via the native process table. Test asserts the scan count stops incrementing after the revalidation, and fails against the stamp-on-change form. Also correct the shared docstring, which had dropped the invariant the whole design rests on, and stop calling this a WSL bug: the trigger is a persistent console-detached job member plus a fallback that reads as a shell. wsl.exe is not in SHELL_NAMES, so a plain WSL pane does not even reach this code -- WSL is just where it was measured.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4ada6b4d-6fc5-4a6f-9811-d9309bfb71cc
📒 Files selected for processing (4)
src/main/daemon/pty-subprocess/foreground-process-tracker.tssrc/main/providers/local-pty-provider-foreground-process.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/windows-cached-agent-revalidation.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/daemon/pty-subprocess/foreground-process-tracker.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
Hardware measurements (Windows 11, installed app's patched node-pty)Run against Idle panes: job vs console
Stable across all six samples in every case — nothing settles or drifts. WSL job members by name: The fast path is byte-identical. For powershell and cmd the two sets are equal and size 1, so The job is a strict superset for WSL, as designed: A correction to this PR's earlier severity claimAn earlier revision of this description argued the job's So the never-retire behaviour for WSL panes is pre-existing, not introduced here. The age bound added in this PR now bounds it on both paths, which makes this a fix for an older bug rather than a mitigation of a new one. I was not able to reproduce the shape that would be a true regression — job Cost, which is the point of the change
Roughly 16,000–32,000× cheaper, and with no process created. That is the #10857 fix stated in measured terms: the polling path went from forking a process per pane per poll to a sub-microsecond syscall. The 32 ms per console read also calibrates the 30 s age bound from the other side — the surviving Use B reads are event-driven, and one forced revalidation per pane per 30 s is negligible against that. |
Elegance pass. No behaviour change -- all three mutation checks still bind
(restoring the size>1 veto, stamping only on name change, dropping the root
requirement each turn their tests red).
- windows-pty-job-membership.ts 54 -> 31 lines. A deps object carrying one
optional function became a defaulted parameter, the accumulate loop became a
filter, and the docblock lost two thirds of its bulk.
It also lost a claim that was simply false: it said a widened set "is the
conservative direction for every caller: it keeps a live agent rather than
retiring it early". For the retire caller, never retiring IS the failure --
that is the bug this stack just fixed, still being described as a feature
three commits later.
- One local `identityOlderThan(ms)` in the tracker replaces two hand-rolled
`Date.now() - refreshedAt` comparisons, one of which I had added.
- The provider's two parallel maps collapse into one Map<id, {name, at}>.
Parallel maps meant every delete site had to remember its sibling, in three
places; the reviewer flagged the leak risk and I fixed it by pairing them,
which leaves the hazard for the next person. One map removes the class.
Comments trimmed to the load-bearing sentence throughout, per AGENTS.md.
The job short-circuit and retirement veto only knew 'something besides the shell is alive', so a detached leftover pinned a dead agent's name for the 30s age bound, and 30s of incomplete-but-successful scans could retire a live one. The scan already knows which row proved the name: carry that pid through the resolution, and judge the cache against the job with it -- membership of a known pid in a complete, inescapable job list is proof of life (restamp, never expire), and its absence is proof of exit (retire now, leftovers notwithstanding). Unanchored identities keep the age-bound superset behavior.
…cycled pid Review findings on the pid anchor: 1. The anchor followed the LEAF that proved a collapsed name: 'omp' reported, pi's pid stored. Pi exiting or restarting under a live OMP then read as the wrapper's exit -- retiring the identity before a scan that (degraded) may miss OMP, a false 'agent done'. resolveOuterWrapperForegroundIdentity now carries the pid of the process the name belongs to. 2. A bare numeric pid can be recycled inside the pane's job, making membership falsely confirm a dead identity indefinitely. Command lines are immutable, so a scan row holding the anchor pid without recognizing as an agent proves a different process: the resolution reports it (anchorPidForeign) and both consumers retire immediately. A query-denied row (command falls back to the image name) stays inconclusive -- never grounds to drop a live agent.
…pid walk A squatter that inherited the pane job from a leftover whose creator then exited is orphaned out of the shell-rooted descendant projection, so the foreign-anchor refutation never saw its row. Pluck the anchor pid's row from the same whole-table snapshot instead; a job member holding the pid is in the table even when no ppid chain reaches it.
Two review findings on the exit verdicts: 1. 'exited' deleted the cache before the scan, so an agent restarting under a new pid plus a degraded scan at that instant reported the shell -- a false 'agent done'. Only the shell standing alone is decisive now; an anchor leaving a job that still has members downgrades to unanchored, age-bounded evidence and lets the scan decide. The daemon tracker keeps immediate retirement: its verdict path only runs after an available scan already found no agent. 2. The foreign-anchor refutation treated any recognized row as 'ours'. A pid recycled by a DIFFERENT agent now compares against the cached name the anchor is supposed to prove.
…nt (#16563) * fix(windows): let a build with no job exports still retire a dead agent #16419 (a1ec047) routed the foreground poll's liveness question to the job object. On a build whose node-pty lacks the job exports the read returns null, which judgeCachedAgentJobEvidence reports as 'unavailable' -- correctly refusing to treat loss of contact as death. But that is the wrong reading here, and it matters more than it looks: **every shipped Windows release is such a build.** The patch adding listJobProcessIds is in no v1.4.* tag, 1.4.188 included (#16059). So for every Windows user today the read is null on every poll, the verdict is always 'unavailable', and the retire path never fires at all. Their panes keep a dead agent's name indefinitely, and because a non-null cache makes idleNoEvidenceShell false, the refresh also stays pinned at the 1s TTL instead of backing off to 15s. That is worse than what #16419 replaced: the forked probe was expensive but it did retire. The distinction the verdict was missing is between "we could have asked and could not" and "there is nothing to ask". Only the first is unverifiable. A build with no job exports is the second, so it now returns 'unsupported' and the authoritative scan decides alone -- exactly as it already does off Windows. Deliberately NOT falling back to the forked console probe: that is the #10857 storm this whole path exists to avoid, and re-forking per poll for the entire current fleet would be the worse trade. The scan that reaches this branch has already reported available and found no agent; trusting it needs no fork. Also deliberately not age-based: an earlier draft retired on age alone, which would expire a LIVE agent that a scan could have confirmed, since 'unproven' short-circuits the scan. isWindowsPtyJobReadable() sits beside the read rather than being imported from windows-pty-job, so one module mock controls both facts. Without that, every Windows-simulating test on a macOS runner silently took the unsupported path, because isPtyJobOwnershipAvailable() is false off Windows -- the suite would have been testing a configuration no Windows user has. * test: give every job-membership mock the readability export Nine of the nineteen files mocking windows-pty-job-membership supplied only readWindowsPtyJobProcessIds, so isWindowsPtyJobReadable resolved to undefined in those suites. They pass today only because none of them reaches the call; the first one that does gets 'isWindowsPtyJobReadable is not a function'. Left alone this is the same trap the export exists to prevent -- a suite that is green about a configuration no user runs -- just arriving as a crash instead of a wrong answer. All nineteen now declare which build they simulate.
…ed helper (stablyai#16419) * fix(windows): answer console membership from the job object, not a forked helper node-pty answers "which processes are attached to this pane's console?" by FORKING a helper, because GetConsoleProcessList must run from a process attached to that console. Orca asked on a foreground poll, per pane, so each read spawned a conpty_console_list_agent -- hundreds of hidden processes exhausting RAM within minutes, respawning as fast as they were killed (stablyai#10857). QueryInformationJobObject has no console-attachment constraint: any process holding the job handle can ask. Orca already creates that job per PTY, and listPtyJobProcessIds has exposed it since the W1/W2 work with zero callers. One syscall, no children. Semantics the three call sites rely on are preserved: a root-only set still proves the shell is alone (so a stale agent can be retired), and size > 1 still proves something is running under it. The single difference is that a descendant detached from the console stays in the job -- which widens the set, the conservative direction for every caller. Also fixes the third call site, which returned { available: false } whenever membership was unavailable AND a recognized agent existed -- i.e. exactly while an agent was running. Membership only ever narrowed the candidate list, so an unavailable answer now leaves it unfiltered instead of failing the whole resolution. The no-fork test is asserted through a module-level vi.mock of node:child_process. A vi.spyOn of a require()'d child_process does not intercept the module's own import binding: the first version of that test passed with a fork() deliberately reintroduced. * fix(windows): keep console attachment for the candidate filter Readiness review caught that this PR changed two different questions as if they were one, and the repo's own plan doc had already said so: "The job is the wrong set here -- it would re-admit precisely the detached process the filter exists to drop." (windows-wsl-root-cause-plan.html, Use B) The two uses: - Use A, `size > 1` at local-pty-provider and the daemon tracker -- "is anything in this pane besides the shell?". The job answers this, in-process and with no fork. Unchanged from the previous commit. - Use B, the candidate filter -- "which of these are ATTACHED TO THIS CONSOLE?". Its whole job is dropping a descendant that detached, and the job object keeps those, so answering it from the job makes the filter a no-op in its motivating case: a detached `Start-Process droid` would be granted byte authority, and a detached sibling would make an attached agent look ambiguous. Use B goes back to GetConsoleProcessList, in its own module named for what it answers, with its fail-closed null restored. That path is not the stablyai#10857 storm: it runs only when a recognized agent candidate already exists, not on every foreground poll. Bounding it to one pooled supervised helper is the remaining half, and per the plan doc either half alone takes stablyai#10857 from unbounded to one. My earlier claim that widening membership is "the conservative direction for every caller" was wrong -- true for Use A, backwards for Use B. The hardware run did not catch it because I measured a WSL pane, where the superset is harmless, and never a detached GUI child, which is the divergence. * fix: restore the coverage and ratchets the module split dropped Round 2 of review. Two blockers, both from moving the forking code to a new file without moving what guarded it. - The child_process import ratchet was RED: windows-console-attached-processes.ts imports node:child_process and was unlisted, and the old entry was stale. I never ran that suite -- lint and the providers/daemon tests both pass without it, which is exactly the gap the ratchet exists to close. Entry repointed; count unchanged at 159. - The forking module had ZERO tests. Its 11 assertions -- bounded timeout, single kill, spawn error, malformed message, helper-pid removal -- were in the file that now answers a different question, so the module that actually caused stablyai#10857 was shipping untested. Moved with the code. Also: nothing pinned the round-1 fix itself. No test drove console attachment to null and asserted the fail-closed result, so re-deleting that branch would have gone green. Now covered, and verified to fail when the branch is removed. Cleanups the split left behind: `consoleMembershipUnavailable`/`consoleProcessIds` renamed to `pane*` where they now hold job membership, the duplicated `WindowsConptyMembershipDeps` type name, comments still describing the console on the job path, and eight reliability-gate paths pointing at the moved tests. * fix(windows): let a superset job answer expire instead of vetoing retirement Round 3. The job read had reintroduced stablyai#9258's bug by a new mechanism. `size > 1` returned unconditionally, so any pane holding a console-detached descendant never retired its cached agent. A WSL pane always holds some: the measurement in this PR's own test recorded job [40980,104068,4888,69908] against console [69908,40980], i.e. console said "shell alone, retire" while the job said "three others alive, keep". stablyai#9258's third commit describes the identical failure from the other direction -- a bare shell reading as [helper, shell] "looked like it still had a child ... the foreground refresh held the exited agent's identity indefinitely" -- and that is what came back. It bites because the read branch that serves the cached name across a Windows shell fallback is deliberately untimed: stablyai#9258 made it so on the stated assumption that "the background refresh authoritatively retires it". Removing the retire authority left the identity with no bound at all. Second-order: a non-null cache makes idleNoEvidenceShell false, which pins the refresh at the 1s TTL, so an idle WSL pane also scanned the process table every second forever. A TTL on the read would have been the wrong fix -- untimed is deliberate, because on Windows the fallback name is structurally uninformative. Instead the job answer is treated as what it is: a SUPERSET of the console, which cannot tell a working agent from a leftover. Proof of absence retires immediately (size 1, unchanged); an inconclusive answer ages out at 30s; unverifiable (null) still holds forever per ssh-execution-boundary.md. Only successful scans that found no agent advance the clock -- a degraded scan returns before this -- so the fix cannot expire an agent it simply failed to see. Also from review: - Restore the root requirement the forked probe had. Without it a set of one non-root pid -- shell gone, descendant alive -- read as "shell alone, retire", inverting the truth. - Rename to windows-pty-job-membership.ts / readWindowsPtyJobProcessIds. The old name still said ConPTY console while reading the job, and conflating those two sets is precisely the bug aee07c2 reverted. Same for windows-console-foreground.ts, which guards a job read now. - Gate the two files that had no coverage: the job read and the retire path. * fix(windows): bound the provider's job short-circuit too The previous commit fixed the daemon retire path and left the identical bug in the local provider, which I found while asking the reviewer to check for it. local-pty-provider.ts returned the cached agent early on `size > 1` and that early return skips the scan at the bottom of getForegroundProcess -- the ONLY code that can delete ptyLastRecognizedForeground. So on a WSL pane, whose job always holds console-detached plumbing, the short-circuit was permanent and the identity could never be cleared. Same failure, second location, and the daemon fix did nothing for it because this path never calls retireStaleForegroundIdentity. The cache was a bare Map<id, name> with no timestamp, so bounding it needs one. Added ptyLastRecognizedForegroundAt, stamped only when the recognized name actually changes, and paired with every existing delete including pane teardown so the new map cannot outlive the old one. The 30s threshold now lives in windows-cached-agent-revalidation.ts rather than being duplicated: that module already answers "can we revalidate this cached agent without a scan", and the max age is the other half of that question. Also renamed two tests that still said "ConPTY console presence" while driving a job read. Re-conflating those two sets by name is how this PR got its first two review rounds wrong. * fix(windows): stamp the provider cache on every confirmation, not on change My own previous commit was wrong, and wrong in the direction stablyai#9258 exists to prevent. Review caught it; the test in this commit reproduces it first. I stamped ptyLastRecognizedForegroundAt only when the recognized name CHANGED. That makes the value the time of first recognition, so the age measures how long the agent has been running rather than how long since we last confirmed it. For a live agent recognized as the same name every cycle the stamp never moved, the age crossed 30s and stayed there, and the short-circuit died permanently. Two consequences, the second serious: - every getForegroundProcess call on a >30s-old agent pane ran the whole-table scan, defeating the exact optimization the branch exists for; - with the short-circuit off, one available-but-agentless snapshot was enough to delete a LIVE agent's identity, because paneMembershipUnavailable is false in this state so the degraded-scan substitution does not engage. That is the false "agent done" this code's own comment warns about. The daemon path was already right -- it re-stamps refreshedAt on every positive recognition -- so the same constant meant two different things in the two files. Now both mean "time since we last saw the agent", which turns the bound from "disable the short-circuit after 30s" into "force one revalidating scan every 30s": ~16-31ms per pane per 30s via the native process table. Test asserts the scan count stops incrementing after the revalidation, and fails against the stamp-on-change form. Also correct the shared docstring, which had dropped the invariant the whole design rests on, and stop calling this a WSL bug: the trigger is a persistent console-detached job member plus a fallback that reads as a shell. wsl.exe is not in SHELL_NAMES, so a plain WSL pane does not even reach this code -- WSL is just where it was measured. * refactor(windows): shrink the job-membership path Elegance pass. No behaviour change -- all three mutation checks still bind (restoring the size>1 veto, stamping only on name change, dropping the root requirement each turn their tests red). - windows-pty-job-membership.ts 54 -> 31 lines. A deps object carrying one optional function became a defaulted parameter, the accumulate loop became a filter, and the docblock lost two thirds of its bulk. It also lost a claim that was simply false: it said a widened set "is the conservative direction for every caller: it keeps a live agent rather than retiring it early". For the retire caller, never retiring IS the failure -- that is the bug this stack just fixed, still being described as a feature three commits later. - One local `identityOlderThan(ms)` in the tracker replaces two hand-rolled `Date.now() - refreshedAt` comparisons, one of which I had added. - The provider's two parallel maps collapse into one Map<id, {name, at}>. Parallel maps meant every delete site had to remember its sibling, in three places; the reviewer flagged the leak risk and I fixed it by pairing them, which leaves the hazard for the next person. One map removes the class. Comments trimmed to the load-bearing sentence throughout, per AGENTS.md. * fix(windows): preserve foreground cache age evidence * fix(windows): anchor cached agent identity to the pid that proved it The job short-circuit and retirement veto only knew 'something besides the shell is alive', so a detached leftover pinned a dead agent's name for the 30s age bound, and 30s of incomplete-but-successful scans could retire a live one. The scan already knows which row proved the name: carry that pid through the resolution, and judge the cache against the job with it -- membership of a known pid in a complete, inescapable job list is proof of life (restamp, never expire), and its absence is proof of exit (retire now, leftovers notwithstanding). Unanchored identities keep the age-bound superset behavior. * fix(windows): anchor the reported process, and let a scan refute a recycled pid Review findings on the pid anchor: 1. The anchor followed the LEAF that proved a collapsed name: 'omp' reported, pi's pid stored. Pi exiting or restarting under a live OMP then read as the wrapper's exit -- retiring the identity before a scan that (degraded) may miss OMP, a false 'agent done'. resolveOuterWrapperForegroundIdentity now carries the pid of the process the name belongs to. 2. A bare numeric pid can be recycled inside the pane's job, making membership falsely confirm a dead identity indefinitely. Command lines are immutable, so a scan row holding the anchor pid without recognizing as an agent proves a different process: the resolution reports it (anchorPidForeign) and both consumers retire immediately. A query-denied row (command falls back to the image name) stays inconclusive -- never grounds to drop a live agent. * fix(windows): find a recycled anchor pid in the full table, not the ppid walk A squatter that inherited the pane job from a leftover whose creator then exited is orphaned out of the shell-rooted descendant projection, so the foreign-anchor refutation never saw its row. Pluck the anchor pid's row from the same whole-table snapshot instead; a job member holding the pid is in the table even when no ppid chain reaches it. * fix(windows): survive an agent restart, and refute a squatter by name Two review findings on the exit verdicts: 1. 'exited' deleted the cache before the scan, so an agent restarting under a new pid plus a degraded scan at that instant reported the shell -- a false 'agent done'. Only the shell standing alone is decisive now; an anchor leaving a job that still has members downgrades to unanchored, age-bounded evidence and lets the scan decide. The daemon tracker keeps immediate retirement: its verdict path only runs after an available scan already found no agent. 2. The foreign-anchor refutation treated any recognized row as 'ours'. A pid recycled by a DIFFERENT agent now compares against the cached name the anchor is supposed to prove.
…nt (stablyai#16563) * fix(windows): let a build with no job exports still retire a dead agent stablyai#16419 (a1ec047) routed the foreground poll's liveness question to the job object. On a build whose node-pty lacks the job exports the read returns null, which judgeCachedAgentJobEvidence reports as 'unavailable' -- correctly refusing to treat loss of contact as death. But that is the wrong reading here, and it matters more than it looks: **every shipped Windows release is such a build.** The patch adding listJobProcessIds is in no v1.4.* tag, 1.4.188 included (stablyai#16059). So for every Windows user today the read is null on every poll, the verdict is always 'unavailable', and the retire path never fires at all. Their panes keep a dead agent's name indefinitely, and because a non-null cache makes idleNoEvidenceShell false, the refresh also stays pinned at the 1s TTL instead of backing off to 15s. That is worse than what stablyai#16419 replaced: the forked probe was expensive but it did retire. The distinction the verdict was missing is between "we could have asked and could not" and "there is nothing to ask". Only the first is unverifiable. A build with no job exports is the second, so it now returns 'unsupported' and the authoritative scan decides alone -- exactly as it already does off Windows. Deliberately NOT falling back to the forked console probe: that is the stablyai#10857 storm this whole path exists to avoid, and re-forking per poll for the entire current fleet would be the worse trade. The scan that reaches this branch has already reported available and found no agent; trusting it needs no fork. Also deliberately not age-based: an earlier draft retired on age alone, which would expire a LIVE agent that a scan could have confirmed, since 'unproven' short-circuits the scan. isWindowsPtyJobReadable() sits beside the read rather than being imported from windows-pty-job, so one module mock controls both facts. Without that, every Windows-simulating test on a macOS runner silently took the unsupported path, because isPtyJobOwnershipAvailable() is false off Windows -- the suite would have been testing a configuration no Windows user has. * test: give every job-membership mock the readability export Nine of the nineteen files mocking windows-pty-job-membership supplied only readWindowsPtyJobProcessIds, so isWindowsPtyJobReadable resolved to undefined in those suites. They pass today only because none of them reaches the call; the first one that does gets 'isWindowsPtyJobReadable is not a function'. Left alone this is the same trap the export exists to prevent -- a suite that is green about a configuration no user runs -- just arriving as a crash instead of a wrong answer. All nineteen now declare which build they simulate.
…ed helper (stablyai#16419) * fix(windows): answer console membership from the job object, not a forked helper node-pty answers "which processes are attached to this pane's console?" by FORKING a helper, because GetConsoleProcessList must run from a process attached to that console. Orca asked on a foreground poll, per pane, so each read spawned a conpty_console_list_agent -- hundreds of hidden processes exhausting RAM within minutes, respawning as fast as they were killed (stablyai#10857). QueryInformationJobObject has no console-attachment constraint: any process holding the job handle can ask. Orca already creates that job per PTY, and listPtyJobProcessIds has exposed it since the W1/W2 work with zero callers. One syscall, no children. Semantics the three call sites rely on are preserved: a root-only set still proves the shell is alone (so a stale agent can be retired), and size > 1 still proves something is running under it. The single difference is that a descendant detached from the console stays in the job -- which widens the set, the conservative direction for every caller. Also fixes the third call site, which returned { available: false } whenever membership was unavailable AND a recognized agent existed -- i.e. exactly while an agent was running. Membership only ever narrowed the candidate list, so an unavailable answer now leaves it unfiltered instead of failing the whole resolution. The no-fork test is asserted through a module-level vi.mock of node:child_process. A vi.spyOn of a require()'d child_process does not intercept the module's own import binding: the first version of that test passed with a fork() deliberately reintroduced. * fix(windows): keep console attachment for the candidate filter Readiness review caught that this PR changed two different questions as if they were one, and the repo's own plan doc had already said so: "The job is the wrong set here -- it would re-admit precisely the detached process the filter exists to drop." (windows-wsl-root-cause-plan.html, Use B) The two uses: - Use A, `size > 1` at local-pty-provider and the daemon tracker -- "is anything in this pane besides the shell?". The job answers this, in-process and with no fork. Unchanged from the previous commit. - Use B, the candidate filter -- "which of these are ATTACHED TO THIS CONSOLE?". Its whole job is dropping a descendant that detached, and the job object keeps those, so answering it from the job makes the filter a no-op in its motivating case: a detached `Start-Process droid` would be granted byte authority, and a detached sibling would make an attached agent look ambiguous. Use B goes back to GetConsoleProcessList, in its own module named for what it answers, with its fail-closed null restored. That path is not the stablyai#10857 storm: it runs only when a recognized agent candidate already exists, not on every foreground poll. Bounding it to one pooled supervised helper is the remaining half, and per the plan doc either half alone takes stablyai#10857 from unbounded to one. My earlier claim that widening membership is "the conservative direction for every caller" was wrong -- true for Use A, backwards for Use B. The hardware run did not catch it because I measured a WSL pane, where the superset is harmless, and never a detached GUI child, which is the divergence. * fix: restore the coverage and ratchets the module split dropped Round 2 of review. Two blockers, both from moving the forking code to a new file without moving what guarded it. - The child_process import ratchet was RED: windows-console-attached-processes.ts imports node:child_process and was unlisted, and the old entry was stale. I never ran that suite -- lint and the providers/daemon tests both pass without it, which is exactly the gap the ratchet exists to close. Entry repointed; count unchanged at 159. - The forking module had ZERO tests. Its 11 assertions -- bounded timeout, single kill, spawn error, malformed message, helper-pid removal -- were in the file that now answers a different question, so the module that actually caused stablyai#10857 was shipping untested. Moved with the code. Also: nothing pinned the round-1 fix itself. No test drove console attachment to null and asserted the fail-closed result, so re-deleting that branch would have gone green. Now covered, and verified to fail when the branch is removed. Cleanups the split left behind: `consoleMembershipUnavailable`/`consoleProcessIds` renamed to `pane*` where they now hold job membership, the duplicated `WindowsConptyMembershipDeps` type name, comments still describing the console on the job path, and eight reliability-gate paths pointing at the moved tests. * fix(windows): let a superset job answer expire instead of vetoing retirement Round 3. The job read had reintroduced stablyai#9258's bug by a new mechanism. `size > 1` returned unconditionally, so any pane holding a console-detached descendant never retired its cached agent. A WSL pane always holds some: the measurement in this PR's own test recorded job [40980,104068,4888,69908] against console [69908,40980], i.e. console said "shell alone, retire" while the job said "three others alive, keep". stablyai#9258's third commit describes the identical failure from the other direction -- a bare shell reading as [helper, shell] "looked like it still had a child ... the foreground refresh held the exited agent's identity indefinitely" -- and that is what came back. It bites because the read branch that serves the cached name across a Windows shell fallback is deliberately untimed: stablyai#9258 made it so on the stated assumption that "the background refresh authoritatively retires it". Removing the retire authority left the identity with no bound at all. Second-order: a non-null cache makes idleNoEvidenceShell false, which pins the refresh at the 1s TTL, so an idle WSL pane also scanned the process table every second forever. A TTL on the read would have been the wrong fix -- untimed is deliberate, because on Windows the fallback name is structurally uninformative. Instead the job answer is treated as what it is: a SUPERSET of the console, which cannot tell a working agent from a leftover. Proof of absence retires immediately (size 1, unchanged); an inconclusive answer ages out at 30s; unverifiable (null) still holds forever per ssh-execution-boundary.md. Only successful scans that found no agent advance the clock -- a degraded scan returns before this -- so the fix cannot expire an agent it simply failed to see. Also from review: - Restore the root requirement the forked probe had. Without it a set of one non-root pid -- shell gone, descendant alive -- read as "shell alone, retire", inverting the truth. - Rename to windows-pty-job-membership.ts / readWindowsPtyJobProcessIds. The old name still said ConPTY console while reading the job, and conflating those two sets is precisely the bug aee07c2 reverted. Same for windows-console-foreground.ts, which guards a job read now. - Gate the two files that had no coverage: the job read and the retire path. * fix(windows): bound the provider's job short-circuit too The previous commit fixed the daemon retire path and left the identical bug in the local provider, which I found while asking the reviewer to check for it. local-pty-provider.ts returned the cached agent early on `size > 1` and that early return skips the scan at the bottom of getForegroundProcess -- the ONLY code that can delete ptyLastRecognizedForeground. So on a WSL pane, whose job always holds console-detached plumbing, the short-circuit was permanent and the identity could never be cleared. Same failure, second location, and the daemon fix did nothing for it because this path never calls retireStaleForegroundIdentity. The cache was a bare Map<id, name> with no timestamp, so bounding it needs one. Added ptyLastRecognizedForegroundAt, stamped only when the recognized name actually changes, and paired with every existing delete including pane teardown so the new map cannot outlive the old one. The 30s threshold now lives in windows-cached-agent-revalidation.ts rather than being duplicated: that module already answers "can we revalidate this cached agent without a scan", and the max age is the other half of that question. Also renamed two tests that still said "ConPTY console presence" while driving a job read. Re-conflating those two sets by name is how this PR got its first two review rounds wrong. * fix(windows): stamp the provider cache on every confirmation, not on change My own previous commit was wrong, and wrong in the direction stablyai#9258 exists to prevent. Review caught it; the test in this commit reproduces it first. I stamped ptyLastRecognizedForegroundAt only when the recognized name CHANGED. That makes the value the time of first recognition, so the age measures how long the agent has been running rather than how long since we last confirmed it. For a live agent recognized as the same name every cycle the stamp never moved, the age crossed 30s and stayed there, and the short-circuit died permanently. Two consequences, the second serious: - every getForegroundProcess call on a >30s-old agent pane ran the whole-table scan, defeating the exact optimization the branch exists for; - with the short-circuit off, one available-but-agentless snapshot was enough to delete a LIVE agent's identity, because paneMembershipUnavailable is false in this state so the degraded-scan substitution does not engage. That is the false "agent done" this code's own comment warns about. The daemon path was already right -- it re-stamps refreshedAt on every positive recognition -- so the same constant meant two different things in the two files. Now both mean "time since we last saw the agent", which turns the bound from "disable the short-circuit after 30s" into "force one revalidating scan every 30s": ~16-31ms per pane per 30s via the native process table. Test asserts the scan count stops incrementing after the revalidation, and fails against the stamp-on-change form. Also correct the shared docstring, which had dropped the invariant the whole design rests on, and stop calling this a WSL bug: the trigger is a persistent console-detached job member plus a fallback that reads as a shell. wsl.exe is not in SHELL_NAMES, so a plain WSL pane does not even reach this code -- WSL is just where it was measured. * refactor(windows): shrink the job-membership path Elegance pass. No behaviour change -- all three mutation checks still bind (restoring the size>1 veto, stamping only on name change, dropping the root requirement each turn their tests red). - windows-pty-job-membership.ts 54 -> 31 lines. A deps object carrying one optional function became a defaulted parameter, the accumulate loop became a filter, and the docblock lost two thirds of its bulk. It also lost a claim that was simply false: it said a widened set "is the conservative direction for every caller: it keeps a live agent rather than retiring it early". For the retire caller, never retiring IS the failure -- that is the bug this stack just fixed, still being described as a feature three commits later. - One local `identityOlderThan(ms)` in the tracker replaces two hand-rolled `Date.now() - refreshedAt` comparisons, one of which I had added. - The provider's two parallel maps collapse into one Map<id, {name, at}>. Parallel maps meant every delete site had to remember its sibling, in three places; the reviewer flagged the leak risk and I fixed it by pairing them, which leaves the hazard for the next person. One map removes the class. Comments trimmed to the load-bearing sentence throughout, per AGENTS.md. * fix(windows): preserve foreground cache age evidence * fix(windows): anchor cached agent identity to the pid that proved it The job short-circuit and retirement veto only knew 'something besides the shell is alive', so a detached leftover pinned a dead agent's name for the 30s age bound, and 30s of incomplete-but-successful scans could retire a live one. The scan already knows which row proved the name: carry that pid through the resolution, and judge the cache against the job with it -- membership of a known pid in a complete, inescapable job list is proof of life (restamp, never expire), and its absence is proof of exit (retire now, leftovers notwithstanding). Unanchored identities keep the age-bound superset behavior. * fix(windows): anchor the reported process, and let a scan refute a recycled pid Review findings on the pid anchor: 1. The anchor followed the LEAF that proved a collapsed name: 'omp' reported, pi's pid stored. Pi exiting or restarting under a live OMP then read as the wrapper's exit -- retiring the identity before a scan that (degraded) may miss OMP, a false 'agent done'. resolveOuterWrapperForegroundIdentity now carries the pid of the process the name belongs to. 2. A bare numeric pid can be recycled inside the pane's job, making membership falsely confirm a dead identity indefinitely. Command lines are immutable, so a scan row holding the anchor pid without recognizing as an agent proves a different process: the resolution reports it (anchorPidForeign) and both consumers retire immediately. A query-denied row (command falls back to the image name) stays inconclusive -- never grounds to drop a live agent. * fix(windows): find a recycled anchor pid in the full table, not the ppid walk A squatter that inherited the pane job from a leftover whose creator then exited is orphaned out of the shell-rooted descendant projection, so the foreign-anchor refutation never saw its row. Pluck the anchor pid's row from the same whole-table snapshot instead; a job member holding the pid is in the table even when no ppid chain reaches it. * fix(windows): survive an agent restart, and refute a squatter by name Two review findings on the exit verdicts: 1. 'exited' deleted the cache before the scan, so an agent restarting under a new pid plus a degraded scan at that instant reported the shell -- a false 'agent done'. Only the shell standing alone is decisive now; an anchor leaving a job that still has members downgrades to unanchored, age-bounded evidence and lets the scan decide. The daemon tracker keeps immediate retirement: its verdict path only runs after an available scan already found no agent. 2. The foreign-anchor refutation treated any recognized row as 'ours'. A pid recycled by a DIFFERENT agent now compares against the cached name the anchor is supposed to prove. (cherry picked from commit a1ec047)
…nt (stablyai#16563) * fix(windows): let a build with no job exports still retire a dead agent object. On a build whose node-pty lacks the job exports the read returns null, which judgeCachedAgentJobEvidence reports as 'unavailable' -- correctly refusing to treat loss of contact as death. But that is the wrong reading here, and it matters more than it looks: **every shipped Windows release is such a build.** The patch adding listJobProcessIds is in no v1.4.* tag, 1.4.188 included (stablyai#16059). So for every Windows user today the read is null on every poll, the verdict is always 'unavailable', and the retire path never fires at all. Their panes keep a dead agent's name indefinitely, and because a non-null cache makes idleNoEvidenceShell false, the refresh also stays pinned at the 1s TTL instead of backing off to 15s. That is worse than what stablyai#16419 replaced: the forked probe was expensive but it did retire. The distinction the verdict was missing is between "we could have asked and could not" and "there is nothing to ask". Only the first is unverifiable. A build with no job exports is the second, so it now returns 'unsupported' and the authoritative scan decides alone -- exactly as it already does off Windows. Deliberately NOT falling back to the forked console probe: that is the stablyai#10857 storm this whole path exists to avoid, and re-forking per poll for the entire current fleet would be the worse trade. The scan that reaches this branch has already reported available and found no agent; trusting it needs no fork. Also deliberately not age-based: an earlier draft retired on age alone, which would expire a LIVE agent that a scan could have confirmed, since 'unproven' short-circuits the scan. isWindowsPtyJobReadable() sits beside the read rather than being imported from windows-pty-job, so one module mock controls both facts. Without that, every Windows-simulating test on a macOS runner silently took the unsupported path, because isPtyJobOwnershipAvailable() is false off Windows -- the suite would have been testing a configuration no Windows user has. * test: give every job-membership mock the readability export Nine of the nineteen files mocking windows-pty-job-membership supplied only readWindowsPtyJobProcessIds, so isWindowsPtyJobReadable resolved to undefined in those suites. They pass today only because none of them reaches the call; the first one that does gets 'isWindowsPtyJobReadable is not a function'. Left alone this is the same trap the export exists to prevent -- a suite that is green about a configuration no user runs -- just arriving as a crash instead of a wrong answer. All nineteen now declare which build they simulate. (cherry picked from commit 5e900b1)
…ed helper (stablyai#16419) * fix(windows): answer console membership from the job object, not a forked helper node-pty answers "which processes are attached to this pane's console?" by FORKING a helper, because GetConsoleProcessList must run from a process attached to that console. Orca asked on a foreground poll, per pane, so each read spawned a conpty_console_list_agent -- hundreds of hidden processes exhausting RAM within minutes, respawning as fast as they were killed (stablyai#10857). QueryInformationJobObject has no console-attachment constraint: any process holding the job handle can ask. Orca already creates that job per PTY, and listPtyJobProcessIds has exposed it since the W1/W2 work with zero callers. One syscall, no children. Semantics the three call sites rely on are preserved: a root-only set still proves the shell is alone (so a stale agent can be retired), and size > 1 still proves something is running under it. The single difference is that a descendant detached from the console stays in the job -- which widens the set, the conservative direction for every caller. Also fixes the third call site, which returned { available: false } whenever membership was unavailable AND a recognized agent existed -- i.e. exactly while an agent was running. Membership only ever narrowed the candidate list, so an unavailable answer now leaves it unfiltered instead of failing the whole resolution. The no-fork test is asserted through a module-level vi.mock of node:child_process. A vi.spyOn of a require()'d child_process does not intercept the module's own import binding: the first version of that test passed with a fork() deliberately reintroduced. * fix(windows): keep console attachment for the candidate filter Readiness review caught that this PR changed two different questions as if they were one, and the repo's own plan doc had already said so: "The job is the wrong set here -- it would re-admit precisely the detached process the filter exists to drop." (windows-wsl-root-cause-plan.html, Use B) The two uses: - Use A, `size > 1` at local-pty-provider and the daemon tracker -- "is anything in this pane besides the shell?". The job answers this, in-process and with no fork. Unchanged from the previous commit. - Use B, the candidate filter -- "which of these are ATTACHED TO THIS CONSOLE?". Its whole job is dropping a descendant that detached, and the job object keeps those, so answering it from the job makes the filter a no-op in its motivating case: a detached `Start-Process droid` would be granted byte authority, and a detached sibling would make an attached agent look ambiguous. Use B goes back to GetConsoleProcessList, in its own module named for what it answers, with its fail-closed null restored. That path is not the stablyai#10857 storm: it runs only when a recognized agent candidate already exists, not on every foreground poll. Bounding it to one pooled supervised helper is the remaining half, and per the plan doc either half alone takes stablyai#10857 from unbounded to one. My earlier claim that widening membership is "the conservative direction for every caller" was wrong -- true for Use A, backwards for Use B. The hardware run did not catch it because I measured a WSL pane, where the superset is harmless, and never a detached GUI child, which is the divergence. * fix: restore the coverage and ratchets the module split dropped Round 2 of review. Two blockers, both from moving the forking code to a new file without moving what guarded it. - The child_process import ratchet was RED: windows-console-attached-processes.ts imports node:child_process and was unlisted, and the old entry was stale. I never ran that suite -- lint and the providers/daemon tests both pass without it, which is exactly the gap the ratchet exists to close. Entry repointed; count unchanged at 159. - The forking module had ZERO tests. Its 11 assertions -- bounded timeout, single kill, spawn error, malformed message, helper-pid removal -- were in the file that now answers a different question, so the module that actually caused stablyai#10857 was shipping untested. Moved with the code. Also: nothing pinned the round-1 fix itself. No test drove console attachment to null and asserted the fail-closed result, so re-deleting that branch would have gone green. Now covered, and verified to fail when the branch is removed. Cleanups the split left behind: `consoleMembershipUnavailable`/`consoleProcessIds` renamed to `pane*` where they now hold job membership, the duplicated `WindowsConptyMembershipDeps` type name, comments still describing the console on the job path, and eight reliability-gate paths pointing at the moved tests. * fix(windows): let a superset job answer expire instead of vetoing retirement Round 3. The job read had reintroduced stablyai#9258's bug by a new mechanism. `size > 1` returned unconditionally, so any pane holding a console-detached descendant never retired its cached agent. A WSL pane always holds some: the measurement in this PR's own test recorded job [40980,104068,4888,69908] against console [69908,40980], i.e. console said "shell alone, retire" while the job said "three others alive, keep". stablyai#9258's third commit describes the identical failure from the other direction -- a bare shell reading as [helper, shell] "looked like it still had a child ... the foreground refresh held the exited agent's identity indefinitely" -- and that is what came back. It bites because the read branch that serves the cached name across a Windows shell fallback is deliberately untimed: stablyai#9258 made it so on the stated assumption that "the background refresh authoritatively retires it". Removing the retire authority left the identity with no bound at all. Second-order: a non-null cache makes idleNoEvidenceShell false, which pins the refresh at the 1s TTL, so an idle WSL pane also scanned the process table every second forever. A TTL on the read would have been the wrong fix -- untimed is deliberate, because on Windows the fallback name is structurally uninformative. Instead the job answer is treated as what it is: a SUPERSET of the console, which cannot tell a working agent from a leftover. Proof of absence retires immediately (size 1, unchanged); an inconclusive answer ages out at 30s; unverifiable (null) still holds forever per ssh-execution-boundary.md. Only successful scans that found no agent advance the clock -- a degraded scan returns before this -- so the fix cannot expire an agent it simply failed to see. Also from review: - Restore the root requirement the forked probe had. Without it a set of one non-root pid -- shell gone, descendant alive -- read as "shell alone, retire", inverting the truth. - Rename to windows-pty-job-membership.ts / readWindowsPtyJobProcessIds. The old name still said ConPTY console while reading the job, and conflating those two sets is precisely the bug aee07c2 reverted. Same for windows-console-foreground.ts, which guards a job read now. - Gate the two files that had no coverage: the job read and the retire path. * fix(windows): bound the provider's job short-circuit too The previous commit fixed the daemon retire path and left the identical bug in the local provider, which I found while asking the reviewer to check for it. local-pty-provider.ts returned the cached agent early on `size > 1` and that early return skips the scan at the bottom of getForegroundProcess -- the ONLY code that can delete ptyLastRecognizedForeground. So on a WSL pane, whose job always holds console-detached plumbing, the short-circuit was permanent and the identity could never be cleared. Same failure, second location, and the daemon fix did nothing for it because this path never calls retireStaleForegroundIdentity. The cache was a bare Map<id, name> with no timestamp, so bounding it needs one. Added ptyLastRecognizedForegroundAt, stamped only when the recognized name actually changes, and paired with every existing delete including pane teardown so the new map cannot outlive the old one. The 30s threshold now lives in windows-cached-agent-revalidation.ts rather than being duplicated: that module already answers "can we revalidate this cached agent without a scan", and the max age is the other half of that question. Also renamed two tests that still said "ConPTY console presence" while driving a job read. Re-conflating those two sets by name is how this PR got its first two review rounds wrong. * fix(windows): stamp the provider cache on every confirmation, not on change My own previous commit was wrong, and wrong in the direction stablyai#9258 exists to prevent. Review caught it; the test in this commit reproduces it first. I stamped ptyLastRecognizedForegroundAt only when the recognized name CHANGED. That makes the value the time of first recognition, so the age measures how long the agent has been running rather than how long since we last confirmed it. For a live agent recognized as the same name every cycle the stamp never moved, the age crossed 30s and stayed there, and the short-circuit died permanently. Two consequences, the second serious: - every getForegroundProcess call on a >30s-old agent pane ran the whole-table scan, defeating the exact optimization the branch exists for; - with the short-circuit off, one available-but-agentless snapshot was enough to delete a LIVE agent's identity, because paneMembershipUnavailable is false in this state so the degraded-scan substitution does not engage. That is the false "agent done" this code's own comment warns about. The daemon path was already right -- it re-stamps refreshedAt on every positive recognition -- so the same constant meant two different things in the two files. Now both mean "time since we last saw the agent", which turns the bound from "disable the short-circuit after 30s" into "force one revalidating scan every 30s": ~16-31ms per pane per 30s via the native process table. Test asserts the scan count stops incrementing after the revalidation, and fails against the stamp-on-change form. Also correct the shared docstring, which had dropped the invariant the whole design rests on, and stop calling this a WSL bug: the trigger is a persistent console-detached job member plus a fallback that reads as a shell. wsl.exe is not in SHELL_NAMES, so a plain WSL pane does not even reach this code -- WSL is just where it was measured. * refactor(windows): shrink the job-membership path Elegance pass. No behaviour change -- all three mutation checks still bind (restoring the size>1 veto, stamping only on name change, dropping the root requirement each turn their tests red). - windows-pty-job-membership.ts 54 -> 31 lines. A deps object carrying one optional function became a defaulted parameter, the accumulate loop became a filter, and the docblock lost two thirds of its bulk. It also lost a claim that was simply false: it said a widened set "is the conservative direction for every caller: it keeps a live agent rather than retiring it early". For the retire caller, never retiring IS the failure -- that is the bug this stack just fixed, still being described as a feature three commits later. - One local `identityOlderThan(ms)` in the tracker replaces two hand-rolled `Date.now() - refreshedAt` comparisons, one of which I had added. - The provider's two parallel maps collapse into one Map<id, {name, at}>. Parallel maps meant every delete site had to remember its sibling, in three places; the reviewer flagged the leak risk and I fixed it by pairing them, which leaves the hazard for the next person. One map removes the class. Comments trimmed to the load-bearing sentence throughout, per AGENTS.md. * fix(windows): preserve foreground cache age evidence * fix(windows): anchor cached agent identity to the pid that proved it The job short-circuit and retirement veto only knew 'something besides the shell is alive', so a detached leftover pinned a dead agent's name for the 30s age bound, and 30s of incomplete-but-successful scans could retire a live one. The scan already knows which row proved the name: carry that pid through the resolution, and judge the cache against the job with it -- membership of a known pid in a complete, inescapable job list is proof of life (restamp, never expire), and its absence is proof of exit (retire now, leftovers notwithstanding). Unanchored identities keep the age-bound superset behavior. * fix(windows): anchor the reported process, and let a scan refute a recycled pid Review findings on the pid anchor: 1. The anchor followed the LEAF that proved a collapsed name: 'omp' reported, pi's pid stored. Pi exiting or restarting under a live OMP then read as the wrapper's exit -- retiring the identity before a scan that (degraded) may miss OMP, a false 'agent done'. resolveOuterWrapperForegroundIdentity now carries the pid of the process the name belongs to. 2. A bare numeric pid can be recycled inside the pane's job, making membership falsely confirm a dead identity indefinitely. Command lines are immutable, so a scan row holding the anchor pid without recognizing as an agent proves a different process: the resolution reports it (anchorPidForeign) and both consumers retire immediately. A query-denied row (command falls back to the image name) stays inconclusive -- never grounds to drop a live agent. * fix(windows): find a recycled anchor pid in the full table, not the ppid walk A squatter that inherited the pane job from a leftover whose creator then exited is orphaned out of the shell-rooted descendant projection, so the foreign-anchor refutation never saw its row. Pluck the anchor pid's row from the same whole-table snapshot instead; a job member holding the pid is in the table even when no ppid chain reaches it. * fix(windows): survive an agent restart, and refute a squatter by name Two review findings on the exit verdicts: 1. 'exited' deleted the cache before the scan, so an agent restarting under a new pid plus a degraded scan at that instant reported the shell -- a false 'agent done'. Only the shell standing alone is decisive now; an anchor leaving a job that still has members downgrades to unanchored, age-bounded evidence and lets the scan decide. The daemon tracker keeps immediate retirement: its verdict path only runs after an available scan already found no agent. 2. The foreign-anchor refutation treated any recognized row as 'ours'. A pid recycled by a DIFFERENT agent now compares against the cached name the anchor is supposed to prove.
…nt (stablyai#16563) * fix(windows): let a build with no job exports still retire a dead agent stablyai#16419 (882741f) routed the foreground poll's liveness question to the job object. On a build whose node-pty lacks the job exports the read returns null, which judgeCachedAgentJobEvidence reports as 'unavailable' -- correctly refusing to treat loss of contact as death. But that is the wrong reading here, and it matters more than it looks: **every shipped Windows release is such a build.** The patch adding listJobProcessIds is in no v1.4.* tag, 1.4.188 included (stablyai#16059). So for every Windows user today the read is null on every poll, the verdict is always 'unavailable', and the retire path never fires at all. Their panes keep a dead agent's name indefinitely, and because a non-null cache makes idleNoEvidenceShell false, the refresh also stays pinned at the 1s TTL instead of backing off to 15s. That is worse than what stablyai#16419 replaced: the forked probe was expensive but it did retire. The distinction the verdict was missing is between "we could have asked and could not" and "there is nothing to ask". Only the first is unverifiable. A build with no job exports is the second, so it now returns 'unsupported' and the authoritative scan decides alone -- exactly as it already does off Windows. Deliberately NOT falling back to the forked console probe: that is the stablyai#10857 storm this whole path exists to avoid, and re-forking per poll for the entire current fleet would be the worse trade. The scan that reaches this branch has already reported available and found no agent; trusting it needs no fork. Also deliberately not age-based: an earlier draft retired on age alone, which would expire a LIVE agent that a scan could have confirmed, since 'unproven' short-circuits the scan. isWindowsPtyJobReadable() sits beside the read rather than being imported from windows-pty-job, so one module mock controls both facts. Without that, every Windows-simulating test on a macOS runner silently took the unsupported path, because isPtyJobOwnershipAvailable() is false off Windows -- the suite would have been testing a configuration no Windows user has. * test: give every job-membership mock the readability export Nine of the nineteen files mocking windows-pty-job-membership supplied only readWindowsPtyJobProcessIds, so isWindowsPtyJobReadable resolved to undefined in those suites. They pass today only because none of them reaches the call; the first one that does gets 'isWindowsPtyJobReadable is not a function'. Left alone this is the same trap the export exists to prevent -- a suite that is green about a configuration no user runs -- just arriving as a crash instead of a wrong answer. All nineteen now declare which build they simulate.
ELI5
On Windows, Orca repeatedly launched a helper process to answer: "Is an agent still running in this terminal pane?"
That helper is expensive. On the reported machine, the helpers accumulated to 238 processes and about 19 GB of memory in nine minutes. Killing them did not help because foreground polling immediately launched more.
Orca already puts each Windows terminal in a Win32 job object. The job object can answer the liveness question directly, in-process, without launching anything. This PR switches the frequent foreground check to that API.
An exact console check still uses the helper when Orca is deciding whether an agent may receive terminal input. That check asks a different, security-sensitive question and only runs during explicit confirmation—not on every foreground poll.
What Changed
conpty_console_list_agent.Why
The old code used one process list for two different questions:
A job is intentionally broader than a console. Using it for input authority could mistake a detached process for the active agent. This PR therefore removes the helper from polling without weakening routing safety.
The remaining helper-backed check is event-driven and gated behind an already-recognized agent candidate. This is not a zero-helper change; it removes the recurring source responsible for the process storm.
User Impact
Linked Issue
Fixes #10857
Alternative to #16074: this keeps the useful liveness signal instead of making the foreground probe permanently unverifiable.
Visual Proof
N/A — this changes Windows background process and foreground-detection behavior; there is no UI change.
Testing
0.001-0.002 ms, versus32-33 msfor the helper-backed console lookup.Review
The important invariants are:
Agent skill upstream boundary
Notes
No UI, mobile, Git-provider, path, shortcut, remote-wire, or persistence format changes.
Checklist