Skip to content

perf(windows): split the process table into two flag sets - #17866

Merged
OrcaWin merged 10 commits into
mainfrom
OrcaWin/win-edr-process-table-flags
Sep 6, 2026
Merged

OrcaWin merged 10 commits into
mainfrom
OrcaWin/win-edr-process-table-flags

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​319 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​304
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​408 $\color{#cf222e}{\Huge{\mathbf{−}}}$​93 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​315

The finding

MDE incident D, factor "suspicious memory activity", against
src/main/windows/windows-process-table.ts:

The relocated daemon calls OpenProcess against every process on the system and reads each
one's PEB out of its address space to recover the command line, on a repeating cadence. That
is the same primitive credential dumpers use to walk process memory.

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, then
    three chained ReadProcessMemory calls.
  • Memory (process.cc:47-64) - OpenProcess with the same access mask, then
    GetProcessMemoryInfo. Zero ReadProcessMemory. It acquires VM_READ and never uses it.

Measured here (541 processes, 405 openable), per detailed scan, before -> after:

syscall before after
OpenProcess(... | PROCESS_VM_READ) 1082 541
NtQueryInformationProcess 541 541
ReadProcessMemory 1215 1215 (unchanged)

So this PR halves a handle-open count and moves the PEB/RPM telemetry not at all. That is not
nothing - repeated PROCESS_VM_READ opens against protected processes are themselves scored, and
that 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.exe with PROCESS_VM_READ every 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:

caller reads command? reads memoryBytes? cadence
windows-agent-foreground-process.ts (via queryWindowsPaneProcessInventory) yes - agent recognition matches command lines first no 750 ms / 2 s per pane - the repeating one
local-workspace-platform-port-scanner.ts yes - port->process attribution no per port-panel scan
codex-structured-turn-processes.ts yes - command is part of the turn-process identity tuple no per turn start/stop
structured-tui-process-identity.ts yes - processCommandMatches no poll during session acquisition
windows-pty-root-identity.ts no - pid/ppid ancestry walk only no per guarded taskkill /T /F
agent-session-process-identity-probe.ts no - creationTimeMs only no per owner probe
codex-structured-location-support.ts availability check only, never reads the table no -
windows-process-table-cim-scan.ts (no-binding fallback) produces command never produced one -

Two honest conclusions:

  1. memoryBytes has no consumer at all. src/main/memory/collector.ts reads Electron's own
    getAppMetrics plus a separate Get-CimInstance sweep, never this table. The Memory flag was
    pure cost - and the value is unusable anyway, since process.h:22 declares DWORD memory and
    process.cc:60 casts WorkingSetSize into it, so anything above 4 GB wraps.
  2. The hot caller genuinely needs the command line. The per-pane foreground tracker at
    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 Memory everywhere. One fewer OpenProcess(... | PROCESS_VM_READ) per process per
scan, 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:

reader row type flags per-process handles
readWindowsProcessIdentityTable[Fresh]() WindowsProcessIdentityRow None | CreationTime none
readWindowsProcessTable[Fresh]() WindowsProcessRow (adds command) + CommandLine one OpenProcess

WindowsProcessRow extends WindowsProcessIdentityRow, so a detailed row still satisfies an
identity-shaped consumer, but command is absent from an identity row at the type level and at
runtime, 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 new queryWindowsProcessLinksFresh) and
agent-session-process-identity-probe.ts now 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.
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 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. Detailed
issued 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.ts issues fresh detailed scans on turn
stop.

Nothing already in the module excluded it. Each cache single-flights only within itself (inFlight
is a closure per reader, process-table-snapshot.ts:265-268), and the wedge set latches only
after a read misses its 3 s deadline, so through the healthy ~12 ms of a scan neither reader
excluded the other.

nativeReadGate now admits exactly one native read at a time across both flag sets. The same fix
closes the relay hazard: adaptAddon has no queue at all, so two simultaneous
CreateToolhelp32Snapshot calls were possible - precisely the crash the vendor's queue exists to
prevent - 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

  • One shared snapshot per flag set, never per caller. Each reader still serves every caller
    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.
  • Wedge gate and 3 s deadline stay shared/module-global. Because only one native call is ever
    outstanding, retention stays bounded at exactly one callback - not one per reader. readSequence
    is module-global and monotonic, so a late callback can only clear its own wedge.
  • Self-presence guard applies to both flag sets and to the CIM fallback. Tested on both.
  • Reject, never resolve-empty on module absence; CIM fallback still only on module absence.
  • nativeReaderEpoch reset semantics unchanged; both readers and the read gate reset together,
    so an abandoned reader's outstanding call cannot stall its replacement.
  • No second PowerShell scan on relays. The CIM fallback belongs to the detailed flag set alone;
    the identity view projects that snapshot through toIdentityRow. Tested.

Measured on this box (Windows 11, 492 processes, 40 iterations after warm-up)

flag set p50 p95 OpenProcess per scan
identity (pid+ppid+name) 6.3 ms 7.0 ms 0
detailed (+ commandLine) 12.3 ms 13.4 ms 492
previous (+ memory + commandLine) 13.1 ms 14.1 ms 984

Against the patched addon built from
config/patches/@[email protected] source. Serialization means an
overlapping 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 CreationTime flag at all. The package enum is
None/Memory/CommandLine, process_worker.cc:29-45 emits no creationTimeMs, the vendored
patch adds none, and adaptAddon's PROCESS_DATA_FLAG lacks the bit. So creationTimeMs is
always undefined in production and isWindowsProcessStartTimeAvailable() is always false -
Windows PID-reuse-safe ownership does not actually work today. This needs its own owner.

Two consequences here. IDENTITY_PROJECTION.flags evaluates to 0, so the identity reader
genuinely opens zero handles today. And agent-session-process-identity-probe.ts now early-returns
on isWindowsProcessStartTimeAvailable() instead of scanning the entire table to produce null -
which also removes the caller most likely to trigger the coalescing race above.

Verification

  • pnpm tc - clean.
  • oxlint whole repo - exit 0 (only pre-existing renderer exhaustive-deps warnings);
    oxlint --type-aware on changed files - clean. No max-lines disable. No as/any added.
    pnpm run check:code-quality:changed could not run here (spawnSync pnpm.cmd EINVAL in this
    shell); its two oxlint scans were run directly instead.
  • All caller suites pass: 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.
  • Pre-existing failures on my box, verified identical on the unmodified tree: four in
    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 in
    agent-session-process-identity-probe.test.ts (the CreationTime gap above).

Tests

The concurrency test now models the wrapper's globalRequestQueue - one requestInProgress latch
over 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 CommandLine nor Memory (and 0 on the relay
addon); identity rows carry no command key at runtime on both the native and no-binding paths;
the detailed path asks for CommandLine without Memory; a 32-wide burst collapses to one scan
per 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.

  1. resetNativeReaderState dropped mutual exclusion across the reset. It replaced the gate
    with Promise.resolve(), so waiters still holding the old chain ran beside reads queued on the
    new 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 the
    deadline, so the wait is bounded.
  2. 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) — satisfied by a correctly flagged read and by a coalesced one, so
    a future regression losing identity flags under concurrency would have kept the case green. Each
    field is now gated on its own bit, and creationTimeMs is asserted positively inside the
    helper 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
    creationTimeMs check catches field shaping — identity dropping CreationTime from its flags,
    or toIdentityRow failing to forward it — which no flags assertion would notice. Noted in the
    doc 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 === 1 against the coalescing mock — but that mock's own
requestInProgress latch means it can never report more than one call in flight, so the assertion
held 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 adaptAddon on a relay, where
re-entering CreateToolhelp32Snapshot is a real crash), which makes re-entry observable. The
vacuous assertion is removed from the coalescing path with a comment saying why.

Verified by deletion, both directions: restoring nativeReadGate = Promise.resolve() fails the
reset case with expected 2 to be 1 (matching the reviewer's independently measured
concurrentMax = 2); restoring the single-bit mock fails both overlap orderings on
creationTimeMs.

Risks for a reviewer

  • Serialization changes timing, deliberately. An overlapping identity + detailed pair now runs
    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.
  • memoryBytes is gone from the public type. Nothing in tree read it.
  • Gate waiters are bounded by the two readers, since each single-flights internally - but if a
    third flag set is ever added, re-check that bound.
  • Concurrency claims in this suite are only as good as the mock they run against. The
    coalescing mock cannot observe re-entry; use the bare-addon mock for that.
  • If a future addon does expose CreationTime, GetProcessTimes needs its own handle, so re-check
    the "identity = zero handles" claim then.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Dropped Memory everywhere — the flag cost a second OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ) per process, its WorkingSetSize wraps 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]() returns WindowsProcessIdentityRow (pid/ppid/name/creationTimeMs, flags None | CreationTime, zero handles); readWindowsProcessTable[Fresh]() returns WindowsProcessRow (+ 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) and agent-session-process-identity-probe.ts (creation time) now use the identity reader via the new queryWindowsProcessLinksFresh.
  • CIM fallback coalescing — with no binding, identitySource() routes identity reads to the detailed snapshot so a relay never forks a second powershell.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 command on 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.

Pullfrog  | View workflow run | Using 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.
Orca Worker added 2 commits September 1, 2026 00:56
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — readNativeRows now chains every read on a module-global nativeReadGate, so the vendored wrapper's coalescing (a second concurrent caller's flags are 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 via ignoreSettlement, 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 — readIdentityRows projects the detailed snapshot through toIdentityRow when moduleLoader() === 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.ts returns null without scanning when isWindowsProcessStartTimeAvailable() is false, which is every shipped build; previously it scanned the whole table to produce the same null.
  • Concurrency test harness — the suite now models the wrapper's requestInProgress latch 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 — resetNativeReaderState now appends a settled link to nativeReadGate (nativeReadGate.then(ignoreSettlement, ignoreSettlement)) instead of replacing it with Promise.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 commandLine on its own CommandLine bit and creationTimeMs on its own CreationTime bit, rather than shaping both off the CommandLine bit, which had silently stripped creationTimeMs from a correctly flagged identity read.
  • Bare-addon concurrency mock — added a queue-less relay addon mock (installBareAddonModule) where re-entry is observable, and moved the maxConcurrentNativeCalls === 1 assertions onto it. The coalescing mock's own latch made that assertion vacuous there.
  • Positive creationTimeMs assertion — expectEachViewGotItsOwnFlags now asserts the identity view actually carries creationTimeMs ([undefined, 1_700_000_000_000]), not just the absence of command, 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, and keeps 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.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 CommandLine flag docs — docs/reference/windows-process-enumeration.md and the code comments in windows-process-table.ts now describe CommandLine as OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) + NtQueryInformationProcess(ProcessCommandLineInformation), asserting the PEB walk was removed "this release".
  • Added a relay/windows-port-scan.ts caller row — classifies it as reading name via the detailed reader, with a paragraph about it being "the one mismatch".

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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 61b84

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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, check… 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…
Linked Issues check ⚠️ Warning The directly linked issue [#4] requires Ctrl/Cmd-click handling for HTTP/HTTPS terminal links. This PR changes Windows process-table readers, row types, native-read serialization, and related tests. I… Link this PR to the correct Windows process-table issue, or implement the requirements from [#4], including modified-click handling, plain-click suppression, non-HTTP URL fallback, and the specified tests.
Out of Scope Changes check ⚠️ Warning The PR changes are unrelated to the directly linked issue [#4]. All functional and test changes concern Windows process enumeration rather than terminal link handling. Remove the Windows process-table changes from the PR or update the linked issue to the issue that authorizes this work. Keep terminal link behavior changes in a separate PR if needed.
Docstring Coverage ⚠️ Warning 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: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the primary change: splitting the Windows process table into two flag sets.
Full details: Description check

Explanation

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 check

Explanation

The directly linked issue [#4] requires Ctrl/Cmd-click handling for HTTP/HTTPS terminal links. This PR changes Windows process-table readers, row types, native-read serialization, and related tests. It does not implement any linked-issue objective.

Full details: Docstring Coverage

Explanation

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 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: b6f92c81-a41e-4b7b-892f-19d672831e70

📥 Commits

Reviewing files that changed from the base of the PR and between 61b09b7 and 458bf0e.

📒 Files selected for processing (8)
  • docs/reference/windows-edr-posture.md
  • docs/reference/windows-process-enumeration.md
  • src/main/providers/windows-foreground-process-rows.ts
  • src/main/runtime/agent-session-process-identity-probe.ts
  • src/main/windows-pty-root-identity.ts
  • src/main/windows/windows-process-table-cim-scan.ts
  • src/main/windows/windows-process-table.test.ts
  • src/main/windows/windows-process-table.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 pulled docs/reference/windows-edr-posture.md onto 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 → 0x1000 measurements, and an inspectWindowsProcessTreeAddon() gate.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread docs/reference/windows-edr-posture.md Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Avoid an unintended Markdown heading.

Line 259 starts with #18875. Markdown treats it as an ATX heading and markdownlint reports MD018. Prefix the text with Issue so 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

📥 Commits

Reviewing files that changed from the base of the PR and between 458bf0e and 7e430e6.

📒 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.

OrcaWin pushed a commit that referenced this pull request Sep 6, 2026
…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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 either seeds readWindowsProcessIdentityTable(), re-mocks the addon, proves the identity cache is live (not merely expired), then asserts queryWindowsProcessLinksFresh() 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 separate identityReader cache 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).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

OrcaWin added a commit that referenced this pull request Sep 6, 2026
* 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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Type resolve before assigning its resolve property.

resolve is inferred as (specifier: string) => unknown, so line 774 accesses a property that does not exist on that type and causes TS2339. Declare resolve with 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e430e6 and d7cdbd1.

📒 Files selected for processing (5)
  • docs/reference/windows-edr-posture.md
  • docs/reference/windows-process-enumeration.md
  • src/main/providers/windows-foreground-process-rows.test.ts
  • src/main/windows/windows-process-table.test.ts
  • src/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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 via NtQueryInformationProcess(ProcessCommandLineInformation) + PROCESS_QUERY_LIMITED_INFORMATION, with a process_commandline.cc patch hunk and the inspectWindowsProcessTreeAddon() check) and #17861 (native port scan), making the docs' "the memory read is gone" and windows-port-scan.ts caller-row claims accurate. This retired all four open Pullfrog threads.
  • Wired reportWindowsCommandLineRecoveryHealth into the detailed read path — gated on flags & CommandLine and 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin merged commit fc5fa16 into main Sep 6, 2026
27 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant