Repository navigation
perf(windows): split the process table into two flag sets - #17866
Conversation
MDE flags "suspicious memory activity" on the process-table reader: it opened a handle into every process on the box and read each one's PEB on a repeating cadence. Two changes narrow that. Drop `Memory` outright. It cost a second OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ) plus GetProcessMemoryInfo per process, and nothing reads a working set off this table -- the Resource Manager runs its own sweep, and the addon stores WorkingSetSize into a DWORD so anything above 4 GB wraps. Split the rest in two. `readWindowsProcessIdentityTable[Fresh]` is a bare Toolhelp32 walk with zero per-process handles, and returns `WindowsProcessIdentityRow`, which has no `command` to read. `readWindowsProcessTable[Fresh]` keeps the command line for the callers that match on it. PTY root identity and the owner start-time probe move to the cheap reader; agent recognition, port attribution, codex turn processes and structured-TUI matching all genuinely need the command line and stay. Two independently single-flighted caches, never one per caller: the fan-out this module prevents is one scan per caller, and each reader still serves every caller wanting its flag set. The wedge gate and the 3s deadline stay shared, because both readers call the same addon and one wedged read latches its one `requestInProgress`. With no binding there is only the 1.4s PowerShell scan to run, so the identity view rides the detailed snapshot rather than forking a second one. Measured on Windows 11, 492 processes (p50/p95): identity 6.3/7.0 ms, detailed 12.3/13.4 ms, previous memory+commandLine 13.1/14.1 ms.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Dropped
Memoryeverywhere — the flag cost a secondOpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ)per process, itsWorkingSetSizewraps above 4 GB, and no caller read it; removed from the row type and the detailed projection. - Split into identity vs detailed flag sets —
readWindowsProcessIdentityTable[Fresh]()returnsWindowsProcessIdentityRow(pid/ppid/name/creationTimeMs, flagsNone | CreationTime, zero handles);readWindowsProcessTable[Fresh]()returnsWindowsProcessRow(+ command, flags+ CommandLine, one handle). Distinct row types enforce the split at the type level. - Migrated the two cheap callers —
windows-pty-root-identity.ts(ancestry walk) andagent-session-process-identity-probe.ts(creation time) now use the identity reader via the newqueryWindowsProcessLinksFresh. - CIM fallback coalescing — with no binding,
identitySource()routes identity reads to the detailed snapshot so a relay never forks a secondpowershell.exe. - Shared wedge gate — both readers share
unreturnedReads,nativeReaderEpoch, and the 3 s deadline, so one wedged read still latches exactly one callback whichever flag set asked for it. - Tests — assert flag bits on both paths, single-flight per flag set, runtime absence of
commandon identity rows (native path), the shared wedge gate, self-presence/deadline on the identity path, and single-scan relay behavior.
One wording nit in the PR description: it says command is stripped from identity rows "including on the CIM fallback path," but on the no-binding path identitySource() routes identity reads through the detailed reader, so those rows do carry command (as the new relay test asserts). The repo docs state this correctly; only the PR-body parenthetical overstates. Not blocking.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The two flag-set readers could both be in flight at once, and the vendored wrapper does not tolerate that. `getRawProcessList` pushes the callback onto one list and calls the addon only when no request is in progress, so a second concurrent caller's `flags` are DISCARDED and it is handed the first caller's rows. Measured against the real addon: identity issued first, both callers got the same array, 0 of 541 rows with a command line. A detailed read overlapping an identity read therefore returned a table with every command line empty, which agent recognition reads as "no agent" -- silently, and only under concurrency. Nothing already here excluded that. Each snapshot cache single-flights only within itself, and the wedge set latches only after a read misses its 3s deadline, so through the healthy ~12ms of a scan neither reader excluded the other. Overlap is the normal state: panes poll detailed at 750ms while a teardown takes identity snapshots. `nativeReadGate` admits one native read at a time across both flag sets. It also fixes the relay path, where `adaptAddon` has no queue at all and two simultaneous CreateToolhelp32Snapshot calls are the crash the vendor's queue exists to prevent. Every link settles, so a wedged read never strands a waiter; the waiter re-checks the wedge and rejects. With one call outstanding, retention stays bounded at one callback rather than one per reader. Also from review: - The CIM fallback now belongs to the detailed flag set alone, and the identity view projects that snapshot through `toIdentityRow`, so an identity row carries no command line on a no-binding host either. - The concurrency test modelled the wrapper's coalescing queue, which the previous synchronous mock could not express; verified failing without the gate and passing with it. - `agent-session-process-identity-probe` early-returns when the creation-time flag is unavailable, which no shipped addon build provides, instead of scanning the table to produce null. - Corrected the cost framing: Memory took an OpenProcess(...|VM_READ) it never read through, so dropping it halves per-process handle opens and leaves the PEB/ReadProcessMemory telemetry unchanged.
Two review follow-ups, both about tests passing for the wrong reason.
`resetNativeReaderState` replaced the read gate with a resolved promise,
so waiters still holding the old chain ran beside reads queued on the
new one. Reachable only from the `__set*ForTests` hooks, which is what
makes it worth fixing: it hands a suite two concurrent calls into its
own mock addon -- the exact condition the concurrency tests exist to
detect. Chain onto the gate instead; every link settles within the
deadline, so the bounded wait that costs is the right trade.
The coalescing mock shaped every field off the CommandLine bit, so an
identity read that did request CreationTime got `creationTimeMs`
stripped. The identity-side assertion was then only `!('command' in
row)`, which a correctly flagged read and a coalesced one satisfy
equally: a future regression losing identity flags under concurrency
would have kept the case green. Gate each field on its own bit and
assert `creationTimeMs` positively, inside the helper both orderings
share.
Concurrency assertions move to a new bare-addon mock. The coalescing
mock's own latch means it can never report more than one call in
flight, so measuring exclusion there proved nothing; the bare addon has
no queue -- like `adaptAddon` on a relay, where re-entering
CreateToolhelp32Snapshot is a real crash -- and makes re-entry visible.
Verified by deletion: restoring `nativeReadGate = Promise.resolve()`
fails the reset case with `expected 2 to be 1`, and restoring the
single-bit mock fails both overlap orderings on `creationTimeMs`.
The section opened "Two defects have now shipped", numbered two, then described the third in its closing paragraph -- a list that reads as a complete account while quietly omitting one, which is the exact failure the section exists to warn about. Say three and number it, and note that the third arrived inside the fix for the first two. Also record why the creationTimeMs and flags-array assertions are not redundant, in the doc and beside the assertions: the flags array catches a read served another flag set's rows, the positional creationTimeMs check catches field shaping (identity dropping CreationTime, or toIdentityRow not forwarding it). Neither sees the other's failure.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior review is commit 610efa6c, which fixes the concurrency defect the split introduced and corrects the one wording discrepancy the prior review flagged.
- Serialized native reads across both flag sets —
readNativeRowsnow chains every read on a module-globalnativeReadGate, so the vendored wrapper's coalescing (a second concurrent caller'sflagsare discarded and it is served the first caller's rows) can no longer hand an overlapping identity + detailed read a table with every command line empty. The gate settles on both fulfill and reject viaignoreSettlement, so a wedged read's 3 s deadline still releases the gate and a waiter re-checks the wedge and rejects rather than stranding. - Relay identity rows now drop
command—readIdentityRowsprojects the detailed snapshot throughtoIdentityRowwhenmoduleLoader() === null, so an identity row carries no command line on any host. This makes the code match the PR description (the prior review's only nit). - Identity probe early-returns —
agent-session-process-identity-probe.tsreturnsnullwithout scanning whenisWindowsProcessStartTimeAvailable()is false, which is every shipped build; previously it scanned the whole table to produce the samenull. - Concurrency test harness — the suite now models the wrapper's
requestInProgresslatch over a shared callback queue and asserts each flag set gets its own rows with never two native calls in flight (maxConcurrentNativeCalls === 1).
Verification: the four affected suites pass (85 tests), and pnpm tc:node is clean.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior review is commits d6bb1b5 and c305ad3, a test-quality follow-up that fixes the mock defects the author identified and re-arms the concurrency assertions so they can actually fail.
- Chained the read gate across resets —
resetNativeReaderStatenow appends a settled link tonativeReadGate(nativeReadGate.then(ignoreSettlement, ignoreSettlement)) instead of replacing it withPromise.resolve(), so a waiter still holding the old chain cannot run beside a read queued on the new one. Test-only path, but it is exactly the path the concurrency suite exercises. - Field-accurate coalescing mock — the mock now gates
commandLineon its ownCommandLinebit andcreationTimeMson its ownCreationTimebit, rather than shaping both off theCommandLinebit, which had silently strippedcreationTimeMsfrom a correctly flagged identity read. - Bare-addon concurrency mock — added a queue-less relay addon mock (
installBareAddonModule) where re-entry is observable, and moved themaxConcurrentNativeCalls === 1assertions onto it. The coalescing mock's own latch made that assertion vacuous there. - Positive
creationTimeMsassertion —expectEachViewGotItsOwnFlagsnow asserts the identity view actually carriescreationTimeMs([undefined, 1_700_000_000_000]), not just the absence ofcommand, catching field-shaping regressions that no flags-array assertion would see. - Two new tests —
never re-enters the bare relay addon when both flag sets overlap, andkeeps one read in flight across a test reset. Both fail when the gate is reverted to replacement semantics (author-verified by deletion).
Verification: windows-process-table.test.ts (39), agent-session-process-identity-probe.test.ts (20), windows-foreground-process-rows.test.ts (6), and windows-pty-root-identity.test.ts (22) all pass; pnpm tc:node and oxlint on the changed TS files are clean.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Every comment here that justified the flag split in terms of PEB reads became false when the command-line reader moved to the kernel. Left alone, the enumeration doc contradicted itself inside one file: the flag-set section described three chained `ReadProcessMemory` calls per process while the sections below it explained that the addon contains no such primitive and has no PEB fallback. The measurement is now attributed rather than merged. Dropping `Memory` halved the per-process handle opens and nothing else -- both handles carried `PROCESS_VM_READ` at the time -- and it was replacing the PEB walk that took `PROCESS_VM_READ` and `ReadProcessMemory` out of the addon. Neither change substitutes for the other, which is worth keeping straight: the split's remaining value is the handle itself, not the memory access. Also adds `relay/windows-port-scan.ts` to the caller table, the one caller this effort introduced, and records that it reads only pid/name through the detailed reader -- free while a pane is polling, not free on a headless relay.
There was a problem hiding this comment.
Important
This docs-only commit replaces the accurate PEB-walk description with a claim the addon now asks the kernel via ProcessCommandLineInformation and "no longer contains" the ReadProcessMemory primitive. That is false for the shipped addon, and the new caller row it adds for relay/windows-port-scan.ts is also fabricated.
Reviewed changes
- Rewrote the
CommandLineflag docs —docs/reference/windows-process-enumeration.mdand the code comments inwindows-process-table.tsnow describeCommandLineasOpenProcess(PROCESS_QUERY_LIMITED_INFORMATION)+NtQueryInformationProcess(ProcessCommandLineInformation), asserting the PEB walk was removed "this release". - Added a
relay/windows-port-scan.tscaller row — classifies it as readingnamevia the detailed reader, with a paragraph about it being "the one mismatch".
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe Windows process table now exposes separate identity and detailed row readers with distinct flags and caches. Native snapshot reads share a serialization gate. Identity callers avoid command-line access and handle opens. Start-time probing checks feature availability before scanning. Tests cover flags, projections, concurrency, cache behavior, reset handling, deadlines, wedges, and CIM fallback behavior. Documentation describes the new readers, addon inspection states, and a direct Claude Code lifecycle hook path. Merge Risk: 🟡 Moderate · up to The PR currently fails required TypeScript and documentation checks, so these localized issues should be fixed before merge. 🚥 Pre-merge checks | ✅ 1 | ❌ 4❌ Failed checks (4 warnings)
✅ Passed checks (1 passed)
Full details: Description checkExplanation The description gives detailed technical context and testing information, but it does not follow the required template. It omits the required ELI5, What Changed, Why, Linked Issue, Visual Proof, checklist, and review sections. Resolution Rewrite the description using the repository template. Add the required headings, link the addressed issue under Linked Issue, state N/A with a reason under Visual Proof if applicable, and complete or explain the testing and checklist items. Full details: Linked Issues checkExplanation The directly linked issue [ Full details: Docstring CoverageExplanation Docstring coverage is 60.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 7 files. (2 skipped: 2 unsupported.) ✨ 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: b6f92c81-a41e-4b7b-892f-19d672831e70
📒 Files selected for processing (8)
docs/reference/windows-edr-posture.mddocs/reference/windows-process-enumeration.mdsrc/main/providers/windows-foreground-process-rows.tssrc/main/runtime/agent-session-process-identity-probe.tssrc/main/windows-pty-root-identity.tssrc/main/windows/windows-process-table-cim-scan.tssrc/main/windows/windows-process-table.test.tssrc/main/windows/windows-process-table.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
There was a problem hiding this comment.
Caution
This delta does not address the prior [!IMPORTANT] finding — it compounds it. The merge brought docs/reference/windows-edr-posture.md onto the branch and rewrote main's accurate "that signal is still present" text into an assertion that "the memory read is gone," backed by a fabricated fourth patch hunk, fabricated measurements, and an inspectWindowsProcessTreeAddon() function that does not exist. The shipped addon still walks every process's PEB with ReadProcessMemory.
Reviewed changes
- Merged
main— a catch-up merge (6th commit) that pulleddocs/reference/windows-edr-posture.mdonto the branch and reconciled the branch's docs against the current tree. - Rewrote the
windows-edr-posture.md"Every process gets a handle" section — replaced the accurate "still present" disclosure with "the memory read is gone," citing a fourth patch hunk,ReadProcessMemory 1128 → 0/0x0410 → 0x1000measurements, and aninspectWindowsProcessTreeAddon()gate.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
docs/reference/windows-edr-posture.md (1)
259-259: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAvoid an unintended Markdown heading.
Line 259 starts with
#18875. Markdown treats it as an ATX heading and markdownlint reports MD018. Prefix the text withIssueso the paragraph remains ordinary text.Proposed fix
-#18875 is a worked example of that doctrine. +Issue `#18875` is a worked example of that doctrine.Source: Linters/SAST tools
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 3804d795-738f-414d-b88d-2cbf61adb2a1
📒 Files selected for processing (1)
docs/reference/windows-edr-posture.md
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
…e's addon attachWindowsProcessNames reads only `name`, so it should move to `readWindowsProcessIdentityTable` once #17866 lands -- on that PR's detailed reader it would open per-process handles for a field it discards. The reader does not exist on this branch, so the call stays as-is with the follow-up recorded rather than pulling #17866 in. The process-table perf table's two Toolhelp32 rows assume the optional `windows-process-tree.node` addon. The desktop bundles it; no released relay does, so on an SSH host the CIM row is the operative number. Comment-only.
The identity and detailed tables are separate snapshot readers with independent TTLs, so the detailed path's existing freshness guard says nothing about the ancestry walk's. Cover the identity reader on its own.
There was a problem hiding this comment.
Reviewed changes
The delta since the prior review is commit a8456b6, a single test.
- Pinned the identity reader's fresh path against its own TTL cache —
never answers the ancestry links from the identity TTL cache eitherseedsreadWindowsProcessIdentityTable(), re-mocks the addon, proves the identity cache is live (not merely expired), then assertsqueryWindowsProcessLinksFresh()still issues a fresh scan (count 1 → 2) returning the new rows. This closes a real coverage gap: the sibling TTL test only pinned the detailed reader (queryWindowsProcessRowsFresh), while the teardown ancestry walk (windows-pty-root-identity.ts→queryWindowsProcessLinksFresh) reads the separateidentityReadercache whose freshness can regress independently.
The test is correct and meaningful — verified 7/7 in the file pass, and both assertions (scanCount() === 2 and the [process.pid, 300] rows) would fail if queryWindowsProcessLinksFresh were reverted to the cached reader.
⚠️ Still blocked on the previously-flagged docs overclaim
This commit is test-only and does not touch the docs, so I am not approving. The [!CAUTION] finding from the prior review — windows-edr-posture.md:122-148, windows-process-enumeration.md:43-62, and the windows-process-table.ts header/DETAILED_PROJECTION comments all still claim the shipped 0.8.0 addon dropped the PEB read — remains unaddressed, with the four Pullfrog threads open. The new test is fine to land on its own, but the PR as a whole is not mergeable until those claims are reconciled with the real addon (which still walks the PEB via ReadProcessMemory).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
* fix(windows): scan ports natively instead of encoded PowerShell Microsoft Defender for Endpoint scored the relay's Windows port scan as suspicious PowerShell plus network discovery (T1049). The command line was `-ExecutionPolicy Bypass -EncodedCommand <base64>` around a Get-NetTCPConnection/Get-Process join -- base64 next to a policy override is the highest-weighted token pair on a PowerShell command line, and netstat only ever ran as its fallback. Invert the chain. `netstat.exe -ano` is now the primary reader and the owning process name comes from the shared native process table, which exists to keep PID lookups off PowerShell. The payload survives only as a last resort, and without the override: execution policy gates script files, never `-Command`, so nothing needed it (verified: `-ExecutionPolicy Restricted -Command` runs). Drop `-p tcp` while inverting: on Windows that protocol name means IPv4 only, so as a primary reader it would have hidden every `[::]` listener the payload used to report. Names arrive as `sshd.exe` from the table and are published as `sshd`, keeping the sshd filter and old clients' rendering intact. Routes both spawns through runProcess, removing the file from the child_process and windowsHide ratchets. * fix(windows): read netstat state by shape and refuse a truncated table Review of the port-scan inversion found two ways the new primary path could be silently wrong, both of which would have kept the flagged PowerShell payload running on exactly the hosts this change targets. `LISTENING` is not in netstat.exe. It lives in System32\<locale>\netstat.exe.mui and MUI selection follows the UI language, so the pinned-locale env in relay-command-env.ts cannot reach it -- a German host prints `ABHOEREN` and the word test parsed zero rows. The zero-listeners guard then read that as a blocked reader and ran `Get-NetTCPConnection` every 12-30s forever, or returned nothing at all where PowerShell is also restricted. Keep the word as the fast path and, when it finds nothing over output that did contain TCP rows, re-read by shape: only a listening socket has no peer. Measured on this host across all four states present (LISTENING 47, ESTABLISHED 49, CLOSE_WAIT 29, TIME_WAIT 213): zero non-listening rows with a zero peer, zero listening rows without one, and the same 47 rows parse after substituting the German state words. Shape stays the fallback because `BOUND` also prints a zero peer. Truncation was invisible: createOutputSink discards overflow, ProcessResult carries no flag, so a capped read still exits 0 and its head still parses. netstat orders IPv4 TCP, then IPv6 TCP, then UDP, so a host with tens of thousands of TIME_WAIT rows would have lost every `[::]` listener -- the exact loss dropping `-p tcp` exists to prevent, and one the zero-listeners guard cannot see. Refuse the read instead. A `truncated` flag on the shared sink would be cleaner and is left as a follow-up rather than widened into this PR. Also: decline to wait on the shared process table once the request is aborted (it takes no signal and must not be cancelled for other callers); note the name lookup as best-effort, since a TTL-cached snapshot can hand a recycled PID its previous owner name; log once on either fall-through, because both are permanent and invisible when wrong; and drop a stderr assertion that any PowerShell autoload banner would redden. Correcting the cost claim in the previous commit: the aggregate win holds with the native addon (netstat 21ms vs the retired payload 860ms at 532 processes), not without it. The addon is optional, the snapshot TTL is 500ms and the scan cadence is 12-30s, so a relay with no active agent pane never warms its own cache and pays ~1.4s cold on the CIM path -- slower than what it replaced. * fix(windows): log the port-scan fall-through on the relay diagnostic stream Checked where this code actually runs before trusting the log. `console.warn` did reach a file, but relayLogLine is the right call and the reasoning is worth recording. `scanWindowsListeningPorts` runs only in the detached relay daemon: relay.ts returns early for --connect and --orca-cli, so PortScanHandler is reached only through runRelayDaemon, and both launchers start it detached with a log file (POSIX `> relay.log 2>&1`, Windows `1>relay.log 2>relay.err.log` via Win32_Process.Create). installRelayLogRotation then wraps both streams into relay.log, which is the file the documented diagnostics tail reads. Verified by installing the real rotation over a temp path and reading the file back. So the line surfaced -- but untimestamped, in a log whose format exists so reconnect flaps can be correlated with the events around them (#7773). relayLogLine is that format and the relay idiom in 41 other places, and "since when has this host been stuck on PowerShell" is most of what this line is for. The test spies on process.stderr to pin the stream and the ISO stamp rather than just asserting something was called, since a fall-through logged somewhere unread is the failure being guarded against. Also fixes a comment that ended its own block early: `relay-*/relay.log` in a doc comment contains `*/`. * fix(windows): keep the dominant zero-peer state when reading a localized netstat Shape alone promoted any zero-peer TCP row, not just listeners. `BOUND` and `CLOSED` print a zero peer too, and on a localized host their state words are exactly as unreadable as the listening one -- so a German host with listeners plus one BOUND socket published a phantom listener. Reachable on an English host too: with zero listeners a lone BOUND row is promoted AND, because the result is then non-empty, it suppresses the blocked-reader fall-through. Group the zero-peer rows by state word and keep only the largest group. A transient BOUND or CLOSED socket cannot outnumber the listeners (51 against 0 on this host), so this removes the class rather than special-casing the words, which would just be the localization bug again. An exact tie keeps every tied group rather than guessing -- no worse than reading shape alone. Verified against real netstat output: injecting a BOUND row into the localized capture leaves the result identical to the English answer (47 rows, no phantom 65001). The new test has teeth -- reverting the grouping fails it and nothing else. Corrects two claims that were slightly wrong: the docblock said shape was the fallback because BOUND prints a zero peer, which described the hazard without saying it was unhandled; and a test comment said an English host "never sees a bound socket", true only when it has at least one readable LISTENING row. Also gates the fall-through log per reason instead of per module, so a host that parses nothing today and truncates tomorrow reports both faults. Same one-shot cost, and the vocabulary is two fixed strings so the set cannot grow. That guard matters more than it looks: --log-file rotates stdout only, so the file stderr can land in is unrotated. * docs(windows): note the direction the zero-peer majority rule can fail in The docblock described the tie case and stopped there, which reads as a complete account of the limits when it is not: a majority rule inverts if the majority is wrong, and enough transient zero-peer sockets would publish the phantoms and drop the real listeners. Someone would reasonably have concluded the rule was safe in both directions. Trigger numbers and the repro stay in the PR discussion; the code only needs the reader to know the rule has a direction, and the hatch (defer to the PowerShell reader, which reads the state word instead of inferring it) since that is the part a future editor would otherwise re-derive. * ci(windows): run the real-netstat port scan suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * test(windows): lower both child-process ratchets to the ground this PR took Migrating the port scan off `node:child_process` onto `runProcess` drops `src/relay/windows-port-scan.ts` from both allowlists, so both offender counts fall by one. Each ratchet pins the count from below as well as above, so a pin left above reality fails and re-opens room for the next direct import to land for free. * docs(windows): qualify the no-PowerShell claim on the netstat scan The scan starts no PowerShell of its own, but no released relay carries the optional `windows-process-tree.node` addon (only dev-channel-win-build.yml builds it), so the shared process-table read falls back to a CIM scan that forks one `powershell.exe`. The EDR win is the removal of the `-EncodedCommand` / `-ExecutionPolicy Bypass` shape, not the elimination of PowerShell. Comment-only. * docs(windows): record the identity-reader follow-up and the perf table's addon attachWindowsProcessNames reads only `name`, so it should move to `readWindowsProcessIdentityTable` once #17866 lands -- on that PR's detailed reader it would open per-process handles for a field it discards. The reader does not exist on this branch, so the call stays as-is with the follow-up recorded rather than pulling #17866 in. The process-table perf table's two Toolhelp32 rows assume the optional `windows-process-tree.node` addon. The desktop bundles it; no released relay does, so on an SSH host the CIM row is the operative number. Comment-only. * docs(windows): state the CIM scan as the relay's normal path, not a fallback No released relay carries the optional `windows-process-tree.node` addon -- release-cut.yml has zero references to it and only dev-channel-win-build.yml builds it -- so the PowerShell CIM scan is what every SSH host runs. The call-site docstring read as a conditional fallback standalone. Comment-only. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/windows/windows-process-table.test.ts (1)
774-774: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winType
resolvebefore assigning itsresolveproperty.
resolveis inferred as(specifier: string) => unknown, so line 774 accesses a property that does not exist on that type and causes TS2339. Declareresolvewith the intersection type before assigning the property.Proposed fix
- const resolve = (specifier: string): unknown => { + const resolve: ((specifier: string) => unknown) & { + resolve: (specifier: string) => string + } = (specifier: string): unknown => {
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 2375ad24-50a7-413c-9843-5530f735e36f
📒 Files selected for processing (5)
docs/reference/windows-edr-posture.mddocs/reference/windows-process-enumeration.mdsrc/main/providers/windows-foreground-process-rows.test.tssrc/main/windows/windows-process-table.test.tssrc/main/windows/windows-process-table.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- docs/reference/windows-edr-posture.md
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The new commit is a merge of origin/main that resolves the previously-flagged docs overclaim and wires main's command-line recovery signal into the detailed read path.
- Merged
main— brought in#17886(command lines read from the kernel viaNtQueryInformationProcess(ProcessCommandLineInformation)+PROCESS_QUERY_LIMITED_INFORMATION, with aprocess_commandline.ccpatch hunk and theinspectWindowsProcessTreeAddon()check) and#17861(native port scan), making the docs' "the memory read is gone" andwindows-port-scan.tscaller-row claims accurate. This retired all four open Pullfrog threads. - Wired
reportWindowsCommandLineRecoveryHealthinto the detailed read path — gated onflags & CommandLineand running after the self-presence guard, so a host-wide refusal of the kernel query emits one warning per session instead of silently degrading agent identity matching to image names.
One non-blocking note: the PR description still frames the addon as walking the PEB ("three chained ReadProcessMemory calls", "moves the PEB/RPM telemetry not at all", "separate work, owned elsewhere"). With #17886 now merged in, the branch eliminates the PEB read, so that framing is stale and worth a refresh before merge.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…lyai#17861) * fix(windows): scan ports natively instead of encoded PowerShell Microsoft Defender for Endpoint scored the relay's Windows port scan as suspicious PowerShell plus network discovery (T1049). The command line was `-ExecutionPolicy Bypass -EncodedCommand <base64>` around a Get-NetTCPConnection/Get-Process join -- base64 next to a policy override is the highest-weighted token pair on a PowerShell command line, and netstat only ever ran as its fallback. Invert the chain. `netstat.exe -ano` is now the primary reader and the owning process name comes from the shared native process table, which exists to keep PID lookups off PowerShell. The payload survives only as a last resort, and without the override: execution policy gates script files, never `-Command`, so nothing needed it (verified: `-ExecutionPolicy Restricted -Command` runs). Drop `-p tcp` while inverting: on Windows that protocol name means IPv4 only, so as a primary reader it would have hidden every `[::]` listener the payload used to report. Names arrive as `sshd.exe` from the table and are published as `sshd`, keeping the sshd filter and old clients' rendering intact. Routes both spawns through runProcess, removing the file from the child_process and windowsHide ratchets. * fix(windows): read netstat state by shape and refuse a truncated table Review of the port-scan inversion found two ways the new primary path could be silently wrong, both of which would have kept the flagged PowerShell payload running on exactly the hosts this change targets. `LISTENING` is not in netstat.exe. It lives in System32\<locale>\netstat.exe.mui and MUI selection follows the UI language, so the pinned-locale env in relay-command-env.ts cannot reach it -- a German host prints `ABHOEREN` and the word test parsed zero rows. The zero-listeners guard then read that as a blocked reader and ran `Get-NetTCPConnection` every 12-30s forever, or returned nothing at all where PowerShell is also restricted. Keep the word as the fast path and, when it finds nothing over output that did contain TCP rows, re-read by shape: only a listening socket has no peer. Measured on this host across all four states present (LISTENING 47, ESTABLISHED 49, CLOSE_WAIT 29, TIME_WAIT 213): zero non-listening rows with a zero peer, zero listening rows without one, and the same 47 rows parse after substituting the German state words. Shape stays the fallback because `BOUND` also prints a zero peer. Truncation was invisible: createOutputSink discards overflow, ProcessResult carries no flag, so a capped read still exits 0 and its head still parses. netstat orders IPv4 TCP, then IPv6 TCP, then UDP, so a host with tens of thousands of TIME_WAIT rows would have lost every `[::]` listener -- the exact loss dropping `-p tcp` exists to prevent, and one the zero-listeners guard cannot see. Refuse the read instead. A `truncated` flag on the shared sink would be cleaner and is left as a follow-up rather than widened into this PR. Also: decline to wait on the shared process table once the request is aborted (it takes no signal and must not be cancelled for other callers); note the name lookup as best-effort, since a TTL-cached snapshot can hand a recycled PID its previous owner name; log once on either fall-through, because both are permanent and invisible when wrong; and drop a stderr assertion that any PowerShell autoload banner would redden. Correcting the cost claim in the previous commit: the aggregate win holds with the native addon (netstat 21ms vs the retired payload 860ms at 532 processes), not without it. The addon is optional, the snapshot TTL is 500ms and the scan cadence is 12-30s, so a relay with no active agent pane never warms its own cache and pays ~1.4s cold on the CIM path -- slower than what it replaced. * fix(windows): log the port-scan fall-through on the relay diagnostic stream Checked where this code actually runs before trusting the log. `console.warn` did reach a file, but relayLogLine is the right call and the reasoning is worth recording. `scanWindowsListeningPorts` runs only in the detached relay daemon: relay.ts returns early for --connect and --orca-cli, so PortScanHandler is reached only through runRelayDaemon, and both launchers start it detached with a log file (POSIX `> relay.log 2>&1`, Windows `1>relay.log 2>relay.err.log` via Win32_Process.Create). installRelayLogRotation then wraps both streams into relay.log, which is the file the documented diagnostics tail reads. Verified by installing the real rotation over a temp path and reading the file back. So the line surfaced -- but untimestamped, in a log whose format exists so reconnect flaps can be correlated with the events around them (stablyai#7773). relayLogLine is that format and the relay idiom in 41 other places, and "since when has this host been stuck on PowerShell" is most of what this line is for. The test spies on process.stderr to pin the stream and the ISO stamp rather than just asserting something was called, since a fall-through logged somewhere unread is the failure being guarded against. Also fixes a comment that ended its own block early: `relay-*/relay.log` in a doc comment contains `*/`. * fix(windows): keep the dominant zero-peer state when reading a localized netstat Shape alone promoted any zero-peer TCP row, not just listeners. `BOUND` and `CLOSED` print a zero peer too, and on a localized host their state words are exactly as unreadable as the listening one -- so a German host with listeners plus one BOUND socket published a phantom listener. Reachable on an English host too: with zero listeners a lone BOUND row is promoted AND, because the result is then non-empty, it suppresses the blocked-reader fall-through. Group the zero-peer rows by state word and keep only the largest group. A transient BOUND or CLOSED socket cannot outnumber the listeners (51 against 0 on this host), so this removes the class rather than special-casing the words, which would just be the localization bug again. An exact tie keeps every tied group rather than guessing -- no worse than reading shape alone. Verified against real netstat output: injecting a BOUND row into the localized capture leaves the result identical to the English answer (47 rows, no phantom 65001). The new test has teeth -- reverting the grouping fails it and nothing else. Corrects two claims that were slightly wrong: the docblock said shape was the fallback because BOUND prints a zero peer, which described the hazard without saying it was unhandled; and a test comment said an English host "never sees a bound socket", true only when it has at least one readable LISTENING row. Also gates the fall-through log per reason instead of per module, so a host that parses nothing today and truncates tomorrow reports both faults. Same one-shot cost, and the vocabulary is two fixed strings so the set cannot grow. That guard matters more than it looks: --log-file rotates stdout only, so the file stderr can land in is unrotated. * docs(windows): note the direction the zero-peer majority rule can fail in The docblock described the tie case and stopped there, which reads as a complete account of the limits when it is not: a majority rule inverts if the majority is wrong, and enough transient zero-peer sockets would publish the phantoms and drop the real listeners. Someone would reasonably have concluded the rule was safe in both directions. Trigger numbers and the repro stay in the PR discussion; the code only needs the reader to know the rule has a direction, and the hatch (defer to the PowerShell reader, which reads the state word instead of inferring it) since that is the part a future editor would otherwise re-derive. * ci(windows): run the real-netstat port scan suite in CI The win32 suite only self-skips off Windows, so it passed vacuously in every lane. Register it the way the cmd-shim suite is registered. * test(windows): lower both child-process ratchets to the ground this PR took Migrating the port scan off `node:child_process` onto `runProcess` drops `src/relay/windows-port-scan.ts` from both allowlists, so both offender counts fall by one. Each ratchet pins the count from below as well as above, so a pin left above reality fails and re-opens room for the next direct import to land for free. * docs(windows): qualify the no-PowerShell claim on the netstat scan The scan starts no PowerShell of its own, but no released relay carries the optional `windows-process-tree.node` addon (only dev-channel-win-build.yml builds it), so the shared process-table read falls back to a CIM scan that forks one `powershell.exe`. The EDR win is the removal of the `-EncodedCommand` / `-ExecutionPolicy Bypass` shape, not the elimination of PowerShell. Comment-only. * docs(windows): record the identity-reader follow-up and the perf table's addon attachWindowsProcessNames reads only `name`, so it should move to `readWindowsProcessIdentityTable` once stablyai#17866 lands -- on that PR's detailed reader it would open per-process handles for a field it discards. The reader does not exist on this branch, so the call stays as-is with the follow-up recorded rather than pulling stablyai#17866 in. The process-table perf table's two Toolhelp32 rows assume the optional `windows-process-tree.node` addon. The desktop bundles it; no released relay does, so on an SSH host the CIM row is the operative number. Comment-only. * docs(windows): state the CIM scan as the relay's normal path, not a fallback No released relay carries the optional `windows-process-tree.node` addon -- release-cut.yml has zero references to it and only dev-channel-win-build.yml builds it -- so the PowerShell CIM scan is what every SSH host runs. The call-site docstring read as a conditional fallback standalone. Comment-only. --------- Co-authored-by: Orca Worker <orca-worker@localhost>
…7866) * perf(windows): split the process table into two flag sets MDE flags "suspicious memory activity" on the process-table reader: it opened a handle into every process on the box and read each one's PEB on a repeating cadence. Two changes narrow that. Drop `Memory` outright. It cost a second OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ) plus GetProcessMemoryInfo per process, and nothing reads a working set off this table -- the Resource Manager runs its own sweep, and the addon stores WorkingSetSize into a DWORD so anything above 4 GB wraps. Split the rest in two. `readWindowsProcessIdentityTable[Fresh]` is a bare Toolhelp32 walk with zero per-process handles, and returns `WindowsProcessIdentityRow`, which has no `command` to read. `readWindowsProcessTable[Fresh]` keeps the command line for the callers that match on it. PTY root identity and the owner start-time probe move to the cheap reader; agent recognition, port attribution, codex turn processes and structured-TUI matching all genuinely need the command line and stay. Two independently single-flighted caches, never one per caller: the fan-out this module prevents is one scan per caller, and each reader still serves every caller wanting its flag set. The wedge gate and the 3s deadline stay shared, because both readers call the same addon and one wedged read latches its one `requestInProgress`. With no binding there is only the 1.4s PowerShell scan to run, so the identity view rides the detailed snapshot rather than forking a second one. Measured on Windows 11, 492 processes (p50/p95): identity 6.3/7.0 ms, detailed 12.3/13.4 ms, previous memory+commandLine 13.1/14.1 ms. * fix(windows): serialize native process-table reads across flag sets The two flag-set readers could both be in flight at once, and the vendored wrapper does not tolerate that. `getRawProcessList` pushes the callback onto one list and calls the addon only when no request is in progress, so a second concurrent caller's `flags` are DISCARDED and it is handed the first caller's rows. Measured against the real addon: identity issued first, both callers got the same array, 0 of 541 rows with a command line. A detailed read overlapping an identity read therefore returned a table with every command line empty, which agent recognition reads as "no agent" -- silently, and only under concurrency. Nothing already here excluded that. Each snapshot cache single-flights only within itself, and the wedge set latches only after a read misses its 3s deadline, so through the healthy ~12ms of a scan neither reader excluded the other. Overlap is the normal state: panes poll detailed at 750ms while a teardown takes identity snapshots. `nativeReadGate` admits one native read at a time across both flag sets. It also fixes the relay path, where `adaptAddon` has no queue at all and two simultaneous CreateToolhelp32Snapshot calls are the crash the vendor's queue exists to prevent. Every link settles, so a wedged read never strands a waiter; the waiter re-checks the wedge and rejects. With one call outstanding, retention stays bounded at one callback rather than one per reader. Also from review: - The CIM fallback now belongs to the detailed flag set alone, and the identity view projects that snapshot through `toIdentityRow`, so an identity row carries no command line on a no-binding host either. - The concurrency test modelled the wrapper's coalescing queue, which the previous synchronous mock could not express; verified failing without the gate and passing with it. - `agent-session-process-identity-probe` early-returns when the creation-time flag is unavailable, which no shipped addon build provides, instead of scanning the table to produce null. - Corrected the cost framing: Memory took an OpenProcess(...|VM_READ) it never read through, so dropping it halves per-process handle opens and leaves the PEB/ReadProcessMemory telemetry unchanged. * test(windows): keep read exclusion across resets and flag each field Two review follow-ups, both about tests passing for the wrong reason. `resetNativeReaderState` replaced the read gate with a resolved promise, so waiters still holding the old chain ran beside reads queued on the new one. Reachable only from the `__set*ForTests` hooks, which is what makes it worth fixing: it hands a suite two concurrent calls into its own mock addon -- the exact condition the concurrency tests exist to detect. Chain onto the gate instead; every link settles within the deadline, so the bounded wait that costs is the right trade. The coalescing mock shaped every field off the CommandLine bit, so an identity read that did request CreationTime got `creationTimeMs` stripped. The identity-side assertion was then only `!('command' in row)`, which a correctly flagged read and a coalesced one satisfy equally: a future regression losing identity flags under concurrency would have kept the case green. Gate each field on its own bit and assert `creationTimeMs` positively, inside the helper both orderings share. Concurrency assertions move to a new bare-addon mock. The coalescing mock's own latch means it can never report more than one call in flight, so measuring exclusion there proved nothing; the bare addon has no queue -- like `adaptAddon` on a relay, where re-entering CreateToolhelp32Snapshot is a real crash -- and makes re-entry visible. Verified by deletion: restoring `nativeReadGate = Promise.resolve()` fails the reset case with `expected 2 to be 1`, and restoring the single-bit mock fails both overlap orderings on `creationTimeMs`. * docs(windows): count the third test defect in the list that names them The section opened "Two defects have now shipped", numbered two, then described the third in its closing paragraph -- a list that reads as a complete account while quietly omitting one, which is the exact failure the section exists to warn about. Say three and number it, and note that the third arrived inside the fix for the first two. Also record why the creationTimeMs and flags-array assertions are not redundant, in the doc and beside the assertions: the flags array catches a read served another flag set's rows, the positional creationTimeMs check catches field shaping (identity dropping CreationTime, or toIdentityRow not forwarding it). Neither sees the other's failure. * docs(windows): stop describing a PEB read this release removed Every comment here that justified the flag split in terms of PEB reads became false when the command-line reader moved to the kernel. Left alone, the enumeration doc contradicted itself inside one file: the flag-set section described three chained `ReadProcessMemory` calls per process while the sections below it explained that the addon contains no such primitive and has no PEB fallback. The measurement is now attributed rather than merged. Dropping `Memory` halved the per-process handle opens and nothing else -- both handles carried `PROCESS_VM_READ` at the time -- and it was replacing the PEB walk that took `PROCESS_VM_READ` and `ReadProcessMemory` out of the addon. Neither change substitutes for the other, which is worth keeping straight: the split's remaining value is the handle itself, not the memory access. Also adds `relay/windows-port-scan.ts` to the caller table, the one caller this effort introduced, and records that it reads only pid/name through the detailed reader -- free while a pane is polling, not free on a headless relay. * test(windows): pin the fresh links path against the identity TTL cache The identity and detailed tables are separate snapshot readers with independent TTLs, so the detailed path's existing freshness guard says nothing about the ancestry walk's. Cover the identity reader on its own. --------- Co-authored-by: Orca Worker <orca-worker@localhost>

The finding
MDE incident D, factor "suspicious memory activity", against
src/main/windows/windows-process-table.ts:Accurate. But the two flags the reader requested are not equally implicated, and the first
revision of this PR overstated what dropping one of them buys. Corrected, from the addon source:
CommandLine(process_commandline.cc:12-70) -OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ),NtQueryInformationProcess(ProcessBasicInformation)for the PEB base, thenthree chained
ReadProcessMemorycalls.Memory(process.cc:47-64) -OpenProcesswith the same access mask, thenGetProcessMemoryInfo. ZeroReadProcessMemory. It acquiresVM_READand never uses it.Measured here (541 processes, 405 openable), per detailed scan, before -> after:
OpenProcess(... | PROCESS_VM_READ)NtQueryInformationProcessReadProcessMemorySo this PR halves a handle-open count and moves the PEB/RPM telemetry not at all. That is not
nothing - repeated
PROCESS_VM_READopens against protected processes are themselves scored, andthat attempt rate halves - but the PEB/RPM sequence is the heaviest-weighted signal and it is
untouched here, and a detailed scan still opens
lsass.exewithPROCESS_VM_READevery 750 ms.Eliminating the PEB read itself is separate work, owned elsewhere.
Caller trace - the report's own caveat, resolved
The report flagged fix #4 as "Unverified: I have not traced how many callers actually consume
commandLine. If most do, this fix collapses." Traced:command?memoryBytes?windows-agent-foreground-process.ts(viaqueryWindowsPaneProcessInventory)local-workspace-platform-port-scanner.tscodex-structured-turn-processes.tsstructured-tui-process-identity.tsprocessCommandMatcheswindows-pty-root-identity.tspid/ppidancestry walk onlytaskkill /T /Fagent-session-process-identity-probe.tscreationTimeMsonlycodex-structured-location-support.tswindows-process-table-cim-scan.ts(no-binding fallback)commandTwo honest conclusions:
memoryByteshas no consumer at all.src/main/memory/collector.tsreads Electron's owngetAppMetricsplus a separateGet-CimInstancesweep, never this table. TheMemoryflag waspure cost - and the value is unusable anyway, since
process.h:22declaresDWORD memoryandprocess.cc:60castsWorkingSetSizeinto it, so anything above 4 GB wraps.750 ms / 2 s is the repeating cadence the report describes. This PR does not remove the
repeating PEB read. It removes the PEB read from the two teardown/identity callers that never
wanted it, and drops a handle from every scan. Saying otherwise would be overclaiming.
What this changes
Dropped
Memoryeverywhere. One fewerOpenProcess(... | PROCESS_VM_READ)per process perscan, including the hot one.
Split the rest into two flag sets, with distinct row types so the type system enforces it
rather than an optional field everyone dereferences:
readWindowsProcessIdentityTable[Fresh]()WindowsProcessIdentityRowNone | CreationTimereadWindowsProcessTable[Fresh]()WindowsProcessRow(addscommand)+ CommandLineOpenProcessWindowsProcessRowextendsWindowsProcessIdentityRow, so a detailed row still satisfies anidentity-shaped consumer, but
commandis absent from an identity row at the type level and atruntime, on the native path and on the no-binding path.
Serialized native reads across both flag sets - see below; this is the load-bearing part.
windows-pty-root-identity.ts(through a newqueryWindowsProcessLinksFresh) andagent-session-process-identity-probe.tsnow use the cheap reader.The concurrency defect the first revision introduced, and the fix
Two independently single-flighted readers can both be in flight at once, and the vendored
wrapper does not tolerate that.
getRawProcessListpushes the callback onto one list and callsthe addon only when no request is in progress, so a second concurrent caller's
flagsarediscarded and it is served the first caller's rows. Reproduced against the real addon: identity
issued first, both callers got the same array object,
541 rows, 0 with commandLine. Detailedissued first: 405 with commandLine.
A detailed read overlapping an identity read therefore returned a table with every command line
empty, which agent recognition reads as "no agent" - silent, wrong, and only under concurrency.
And overlap is the normal state, not an edge case: other panes keep polling detailed at 750 ms
during a teardown, and
codex-structured-turn-processes.tsissues fresh detailed scans on turnstop.
Nothing already in the module excluded it. Each cache single-flights only within itself (
inFlightis a closure per reader,
process-table-snapshot.ts:265-268), and the wedge set latches onlyafter a read misses its 3 s deadline, so through the healthy ~12 ms of a scan neither reader
excluded the other.
nativeReadGatenow admits exactly one native read at a time across both flag sets. The same fixcloses the relay hazard:
adaptAddonhas no queue at all, so two simultaneousCreateToolhelp32Snapshotcalls were possible - precisely the crash the vendor's queue exists toprevent - and the old comment claiming "we hold our own single-flight" was false. Every gate link
settles (a wedged read still rejects on its deadline), so a waiter is never stranded; it re-checks
the wedge and rejects instead.
Invariants preserved
wanting its flag set, so a 32-wide teardown still collapses into one scan of each. A third cache
would need a third flag set, not a third caller.
outstanding, retention stays bounded at exactly one callback - not one per reader.
readSequenceis module-global and monotonic, so a late callback can only clear its own wedge.
nativeReaderEpochreset semantics unchanged; both readers and the read gate reset together,so an abandoned reader's outstanding call cannot stall its replacement.
the identity view projects that snapshot through
toIdentityRow. Tested.Measured on this box (Windows 11, 492 processes, 40 iterations after warm-up)
OpenProcessper scanpid+ppid+name)+ commandLine)+ memory + commandLine)Against the patched addon built from
config/patches/@[email protected]source. Serialization means anoverlapping pair now costs 6.3 + 12.3 ms sequentially rather than one coalesced (and wrong) 12.3 ms.
Known latent gap (pre-existing, not introduced here)
Nothing in the repo supplies a
CreationTimeflag at all. The package enum isNone/Memory/CommandLine,process_worker.cc:29-45emits nocreationTimeMs, the vendoredpatch adds none, and
adaptAddon'sPROCESS_DATA_FLAGlacks the bit. SocreationTimeMsisalways
undefinedin production andisWindowsProcessStartTimeAvailable()is alwaysfalse-Windows PID-reuse-safe ownership does not actually work today. This needs its own owner.
Two consequences here.
IDENTITY_PROJECTION.flagsevaluates to0, so the identity readergenuinely opens zero handles today. And
agent-session-process-identity-probe.tsnow early-returnson
isWindowsProcessStartTimeAvailable()instead of scanning the entire table to producenull-which also removes the caller most likely to trigger the coalescing race above.
Verification
pnpm tc- clean.oxlintwhole repo - exit 0 (only pre-existing rendererexhaustive-depswarnings);oxlint --type-awareon changed files - clean. Nomax-linesdisable. Noas/anyadded.pnpm run check:code-quality:changedcould not run here (spawnSync pnpm.cmd EINVALin thisshell); its two oxlint scans were run directly instead.
windows-foreground-process-rows,windows-agent-foreground-process-scan-volume,agent-foreground-process*,windows-pty-root-identity,relay-native-dependency-coverage,structured-tui-process-identity,codex-structured-turn-processes.integration,pty-shell-utils,local-workspace-port-scanner.windows-pty-job.win32.test.ts/windows-host-job.win32.test.ts(isPtyJobOwnershipAvailable()false - this worktree's postinstall could not rebuild node-pty from patched source: node-gyp
MSB3191, path >260 chars in a nested worktree), and two inagent-session-process-identity-probe.test.ts(theCreationTimegap above).Tests
The concurrency test now models the wrapper's
globalRequestQueue- onerequestInProgresslatchover a shared callback list, resolved asynchronously, with a second caller's flags discarded. The
previous synchronous mock could not express the hazard. Verified by removing the gate: the three
concurrency tests fail with exactly the production symptom (
expected [ 4 ] to deeply equal [ 4, 6 ], and the detailed reader's command-line assertion failing), and pass with it.Also covered: the identity path issues neither
CommandLinenorMemory(and0on the relayaddon); identity rows carry no
commandkey at runtime on both the native and no-binding paths;the detailed path asks for
CommandLinewithoutMemory; a 32-wide burst collapses to one scanper flag set; deadline, empty-snapshot rejection and self-presence hold on the identity path; the
wedge gate is shared in both directions with exactly one callback retained; one CIM scan serves
both views; an identity read missing our own pid still rejects.
Test-quality follow-ups (review round 2)
Both non-blocking findings are fixed, and both were the same shape as my own earlier mock defect:
a test that passes for a reason other than the one it claims to check. That has now happened
three times in this file, so the pattern is written down in the reference doc.
resetNativeReaderStatedropped mutual exclusion across the reset. It replaced the gatewith
Promise.resolve(), so waiters still holding the old chain ran beside reads queued on thenew one. Test-only, which is precisely why it matters: it hands a suite two concurrent calls
into its own mock, the exact condition the concurrency tests exist to detect. Now chains
(
nativeReadGate.then(ignoreSettlement, ignoreSettlement)); every link settles within thedeadline, so the wait is bounded.
CommandLinebit, so an identity read thatdid request
CreationTimegotcreationTimeMsstripped. The identity-side assertion was thenonly
!('command' in row)— satisfied by a correctly flagged read and by a coalesced one, soa future regression losing identity flags under concurrency would have kept the case green. Each
field is now gated on its own bit, and
creationTimeMsis asserted positively inside thehelper both orderings share. That check and the flags-array check are not redundant and both
must stay: the flags array catches a read served the other set's rows, while the positional
creationTimeMscheck catches field shaping — identity droppingCreationTimefrom its flags,or
toIdentityRowfailing to forward it — which no flags assertion would notice. Noted in thedoc and beside the assertions so neither gets deleted as duplicate later.
A third problem surfaced while verifying the first — inside the fix for the other two, which is
the point of writing the pattern down. My initial reset test asserted
maxConcurrentNativeCalls === 1against the coalescing mock — but that mock's ownrequestInProgresslatch means it can never report more than one call in flight, so the assertionheld whether or not this module excluded anything. It passed against the broken reset. Concurrency
assertions now run against a new bare-addon mock (no queue — like
adaptAddonon a relay, wherere-entering
CreateToolhelp32Snapshotis a real crash), which makes re-entry observable. Thevacuous assertion is removed from the coalescing path with a comment saying why.
Verified by deletion, both directions: restoring
nativeReadGate = Promise.resolve()fails thereset case with
expected 2 to be 1(matching the reviewer's independently measuredconcurrentMax = 2); restoring the single-bit mock fails both overlap orderings oncreationTimeMs.Risks for a reviewer
sequentially. That is the cost of correctness given the wrapper's coalescing; the alternative is
a single reader issuing both field sets, which would reinstate the unconditional PEB read.
memoryBytesis gone from the public type. Nothing in tree read it.third flag set is ever added, re-check that bound.
coalescing mock cannot observe re-entry; use the bare-addon mock for that.
CreationTime,GetProcessTimesneeds its own handle, so re-checkthe "identity = zero handles" claim then.