Repository navigation
Description
Context
While investigating the memory reports in #12728, #15241, #16211, #16905 and #9530, we found the same meta-pattern: the repo already ships the right primitives (process-tree-termination, run-process, bounded-map, process-table-snapshot, ratchet scripts, custom oxlint plugins), but adoption is partial and there are no resource-lifetime guardrails, so the same bug classes get re-fixed point by point.
Two concrete examples:
-
Directory handles.
grok-session-paths.tscorrectly closes itsopendirhandle infinally, but ~11 production call sites exist and several rely on implicit close. Two actually leak today:src/shared/quick-open-directory-reader.ts:throwIfFileListingCancelledcan throw betweenopendir()and thefor awaitloop, leaking the handle.src/shared/linux-proc-socket-owner-scanner.ts: an async generator over aDir; if the consumer breaks, the handle is only reclaimed by GC. This is the "Closing directory handle on garbage collection" warning reported in [Bug]: Remote SSH workspace sync unavailable — long-running relay degrades (Handshake OK, no data stream, 2–4 s close loop); manual reconnect redeploys relay and heals #12895.
-
Windows process queries. AGENTS.md says to read the process table through
windows-process-table.ts, never forkpowershell.exe, but the memory resource collector still spawnspowershell.exe Get-CimInstanceevery ~2s ([Bug]: Windows relocated terminal daemon spawns powershell.exe every ~2s (native process-tree addon missing from daemon host) #16905) because perf(windows): read the process table natively instead of forking PowerShell #15749 migrated only the identity probes.
Proposal
- Shared scoped-opendir helper (
src/shared/fs-opendir-scope.ts): awithDir(path, fn, { signal })callback helper implemented internally withawait using/AsyncDisposable(TS 7 supports this natively), plus migration of the leaking/implicit-close sites. Follow-up: an oxlint plugin (no-raw-opendir) with an allowlist so new rawopendirsites fail lint. - Native memory collector (fixes the [Bug]: Windows relocated terminal daemon spawns powershell.exe every ~2s (native process-tree addon missing from daemon host) #16905 remainder): migrate
windows-process-resource-collector.tstoreadWindowsProcessTable()and delete the PowerShell/typeperf spawn path. Known gap worth recording: the native row type does not expose commit/pagefile bytes, soprivateMemorystays absent on Windows; extending the native addon withGetProcessMemoryInfowould be a follow-up. - Reliability gates: register a
fs-resource-lifetime.dir-handle-closuregate inconfig/reliability-gates.jsonc(existing schema: protectionpartial->activewhen the migration lands), with the same pattern later for child-process-tree-termination and bounded retention. This is what turns point fixes into class fixes.
Questions
- @nwparker is any of this already in flight (given the perf(sleep): park idle agents in the worktree you are working in (#16211) #16591/fix(hibernation): park completed background tabs in the active worktree #16214 precedent we would rather not duplicate work)?
- For the gate entry: does adding a new gate with protection
partialand empty red-green evidence match your expectations for new gates, or do you prefer gating evidence only after the migration PR?
Happy to split/adjust scope however you prefer. Design notes and measurement plans are written up and can be pasted into this issue or the PRs.
Activity
AmethystLiang commentedon Aug 28, 2026
thanks for reporting. looking into it
AmethystLiang commentedon Aug 28, 2026
thanks for reporting. looking into it
nwparker commentedon Sep 3, 2026
I took over the two PRs from this issue (#17035, #17034) and closed both. Correcting the record here so nobody re-derives the same conclusion.
Proposal 1 (scoped-opendir helper) is not needed. The premise — that
for awaitover anfs.Dirleaks the handle onbreak/throw/early exit — is wrong.for awaitcalls the iterator'sreturn(), andDir'sreturn()closes. Verified on Node 24, including transitively through an async generator with a consumerbreak, and through a nested recursive frame throwing while the parent is suspended mid-loop:So the two sites named in this issue:
quick-open-directory-reader.ts— was a real leak (the one shape that does leak: throwing betweenopendir()and entering the loop). Already fixed by fix: close readiness gaps found by merged-change audit #17159,:32-55.linux-proc-socket-owner-scanner.ts— never leaked, and fix: close readiness gaps found by merged-change audit #17159 deleted the file.I swept every
opendir/opendirSyncinsrc/. All safe: either afor await, or a manual.read()loop already intry/finally(skill-package-identity.ts:215-227). There is no ~11-site adoption gap. Ano-raw-opendirlint rule would be enforcing a non-rule.Also worth knowing:
Diris already nativelyAsyncDisposable(@types/node/fs.d.ts:310), andconfig/tsconfig.node.jsonresolves totarget: esnext— soawait using dir = await opendir(p)works today without any helper, if a future site ever needs one.Proposal 3 (the gate) followed from proposal 1, so it goes with it.
Proposal 2 (Windows process queries) is untouched by any of this and still stands on its own —
windows-process-resource-collector.tsstill spawningpowershell.exe Get-CimInstanceis a separate, real issue. Worth splitting into its own ticket rather than leaving it buried under a refuted premise.Two genuine findings this turned up, both worth their own issues:
config/scripts/check-reliability-gates.mjsonly shape-validates evidence.assertionRefsare checked to be non-empty strings whosefileis intestFiles(:228-241); the file is never opened.evidenceRunsneed oneresult: "passed"entry (:211-226) but are never executed. A gate asserting coverage that does not exist passes cleanly — which is exactly how chore(gates): register dir-handle-closure reliability gate #17034 got a green check. Worth deciding whether that's acceptable by design (the refs are prose, not literalit()names, so exact matching won't work) or whether it needs a real linkage.The GC warning in [Bug]: Remote SSH workspace sync unavailable — long-running relay degrades (Handshake OK, no data stream, 2–4 s close loop); manual reconnect redeploys relay and heals #12895's relay log is real and still unexplained. Given the above it is not coming from these
opendirsites, so it's worth re-deriving from the relay process itself. That's the thread actually worth pulling.@espetro — thanks for the writeup; the meta-pattern framing (point fixes vs. class fixes) is the right instinct even though this particular class turned out to be already-safe. Detailed refutation with repros is in the PR comments.
nwparker commentedon Sep 3, 2026
Correction to my comment above — one point I got wrong, and it matters for anyone acting on it.
I wrote that
Diris nativelyAsyncDisposablesoawait using dir = await opendir(p)"works today without any helper." That is true for main / preload / renderer code, which runs on Electron 43's bundled Node 24. It is not true forsrc/shared/orsrc/relay/code, and that's exactly where theseopendirsites live.Two independent runtime floors break it:
Dir's disposal methods are@since v24.1.0(@types/node/fs.d.ts:305-316). Below that, aDirhas no[Symbol.asyncDispose]at all.target: 'node18'(config/scripts/build-relay.mjs:117) and the SSH toolchain floor isMIN_NODE_MAJOR = 18(ssh-remote-node-toolchain-probe.ts:5).src/relay/pty-handler.ts:293already documents working around this ("the relay still targets Node 18, which lacksArray.prototype.toReversed").And this code path is relay-bound:
src/relay/fs-handler-readdir-fallback.ts:17→shared/quick-open-readdir-walk→shared/quick-open-directory-reader.esbuild lowers
await usinginto a__usinghelper that resolves the symbol at runtime, but leaves a class's computed[Symbol.asyncDispose]key un-lowered. When the symbol is missing the two disagree and it throws. Simulated against a realtarget: node18bundle withSymbol.asyncDispose/Symbol.disposeremoved:In the relay that surfaces as: every readdir-fallback directory read throws → swallowed to
[]→ Quick Open silently empty on that SSH host.So the honest scoreboard on this axis, which I had backwards:
await usingon a rawDir(what I suggested)[Symbol.asyncDispose](what #17035 did)try { … } finally { await dir.close().catch(() => {}) }My suggestion was worse than the PR's on remote-host compatibility. Credit where due — #17035's wrapper, whatever else was wrong with it, degraded over a narrower range than the "just use the native one" advice I gave.
None of this revives either PR: the leaks still don't exist,
mainstill needs no change, and the sites in question are all safe byfor await's auto-close. But the rule for this repo is: noawait usinginsrc/shared/orsrc/relay/until the relay's Node floor moves. Plaintry/finallyis the portable form, and it's what every existing site already uses.Thanks to the reviewer who caught the relay target — I'd checked
config/tsconfig.node.json(target: esnext) and the electron-vite bundle and stopped there, missing that the relay has its own esbuild build with a much older floor.nwparker commentedon Sep 27, 2026
Closing this umbrella after checking the remaining scope. The directory-handle premise and its proposed gate were refuted in the review of #17035/#17034; the sole real quick-open leak was fixed by #17159. The separate Windows process-query remainder is now resolved by #22872, and #16905 was closed with that evidence. The reliability-gate validation concern and the still-unexplained #12895 relay warning are distinct follow-up investigations, not remaining work in this proposal. Reopen if any original scope is still outstanding.