Skip to content

fix(windows): read command lines from the kernel, not each process's PEB - #17886

Merged
OrcaWin merged 17 commits into
mainfrom
OrcaWin/win-edr-commandline-no-peb
Sep 6, 2026
Merged

OrcaWin merged 17 commits into
mainfrom
OrcaWin/win-edr-commandline-no-peb

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 1, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​795 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​783
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1059 $\color{#cf222e}{\Huge{\mathbf{−}}}$​73 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​986

The primitive being replaced

MDE incident D flagged Orca for "suspicious memory activity". The addon's CommandLine flag (src/process_commandline.cc in @vscode/[email protected]) recovered each process's command line by:

OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);   // 0x0410
NtQueryInformationProcess(h, ProcessBasicInformation, &pbi, ...);        // PEB base
ReadProcessMemory(h, pbi.PebBaseAddress, &peb, ...);                     // 1
ReadProcessMemory(h, peb.ProcessParameters, &params, ...);               // 2
ReadProcessMemory(h, params.CommandLine.Buffer, &buffer[0], ...);        // 3

OpenProcess(…VM_READ) + ReadProcessMemory across every pid on a repeating timer is behaviourally identical to a credential dumper. #17866 halves the handle count by dropping the useless Memory flag but, as it says itself, leaves the PEB read on the hot path.

Windows 8.1 added NtQueryInformationProcess's ProcessCommandLineInformation class (0x3C = 60). It returns the same string as a UNICODE_STRING the kernel builds, needing only PROCESS_QUERY_LIMITED_INFORMATION. Electron 43's floor is Windows 10, so every OS Orca supports has it. The entry point is resolved with GetProcAddress on ntdll.dll (no import library), and the buffer size comes from a null-buffer probe answering STATUS_INFO_LENGTH_MISMATCH.

The same hunk drops PROCESS_VM_READ from GetProcessMemoryUsage and GetCpuUsage, which acquired it and never read an address space — GetProcessMemoryInfo and GetProcessTimes are satisfied by PROCESS_QUERY_LIMITED_INFORMATION.

There is no PEB fallback

The first revision kept the PEB reader behind a latch. Review caught that this was a single point of total defeat: ClassifyQueryFailure mapped STATUS_INVALID_INFO_CLASS / NOT_SUPPORTED / NOT_IMPLEMENTED from any one target onto a process-wide, one-way, never-cleared switch back to PROCESS_VM_READ plus three ReadProcessMemory per pid per scan — for the life of the process, with no log line and nothing observable from JS.

It did not need a kernel without class 60. It needed one anomalous NTSTATUS from one process. And the environment this PR exists for is one where an EDR hooks ntdll: a hook returning STATUS_INVALID_INFO_CLASS for a class it does not recognise would have silently reinstated the exact primitive being removed, on precisely the machines it was written for. Same under Wine or any instrumented ntdll.

So the fallback is deleted, not guarded. GetProcessCommandLine returns false and leaves the command line empty — already a documented, tolerated outcome (WindowsProcessRow.command is "empty when the process denied a query handle"; callers fall back to the image name). Degrading to no command line is recoverable; silently resuming address-space reads is not.

Because the returned UNICODE_STRING crosses that same hookable boundary, Buffer/Length are now bounds-checked against the allocation — against buffer.size(), not size, which the second query clobbers — and the probe size is capped at the header plus 64 KiB (Length is a USHORT) so a bogus size cannot bad_alloc an entire scan instead of one process. NT_SUCCESS is tested explicitly rather than as an inequality.

Access-right reduction, measured in-process

Counted by replacing the loaded .node's import-address-table entries for OpenProcess and ReadProcessMemory with counting stubs — observed calls from the real binary. Windows 11, 543 processes, unelevated.

per CommandLine scan before (0.8.0 as vendored) after
OpenProcess calls 543 543
desired access 0x0410 — PROCESS_VM_READ | PROCESS_QUERY_INFORMATION (×543) 0x1000 — PROCESS_QUERY_LIMITED_INFORMATION (×543)
ReadProcessMemory calls 1128 0

Stronger than a zero count: the IAT hook reports readProcessMemorySlots: 0 — there is no import slot to patch, because the symbol is absent from the binary entirely.

PROCESS_QUERY_INFORMATION implicitly grants PROCESS_QUERY_LIMITED_INFORMATION, so this is a strictly weaker right — confirmed empirically: 0 processes opened with the old mask and not the new one.

Match rate and differences

processes both readers recovered 405 (other runs: 399, 376)
byte-identical 405 / 405 = 100.00%
differing 0
recovered only by the new path 3
recovered only by the PEB path 0

The three the old path could not reach (GCC.exe, ctfmon.exe, ChsIME.exe) refused PROCESS_QUERY_INFORMATION | PROCESS_VM_READ with ERROR_ACCESS_DENIED and granted PROCESS_QUERY_LIMITED_INFORMATION. ~132 SYSTEM/protected processes deny both identically.

Targeted string-identity cases, all byte-identical: a 24,087-character argv with embedded quotes, non-ASCII (é, 中) and trailing whitespace; the longest real command line on the box (15,448); and a WOW64 (32-bit) target, the PEB path's known cross-bitness hazard.

Latency

End-to-end through getProcessList, 21 scans each:

flags before after
None 7.5 / 8.4 ms 7.6 / 8.2 ms
CommandLine 13.5 / 14.5 ms 12.3 / 13.5 ms
Memory | CommandLine 14.9 / 15.9 ms 13.5 / 14.9 ms

The published tarball ships a loadable unpatched prebuilt

Review found my "an un-applied patch cannot silently ship the flagged reader" claim was false as written, and it was right. @vscode/[email protected] publishes build/Release/windows_process_tree.node in the tarball. It is node-addon-api, so it loads under Node and Electron; allowBuilds is false and CI installs with --ignore-scripts; ensure-native-runtime.mjs's health check was a bare require(), which the prebuilt passes. Both of my original guards checked source text and could never see it.

This is not hypothetical — the new check fires in this very worktree: the shared node_modules currently carries the upstream prebuilt, with ReadProcessMemory in its import table, loading fine.

The fix keys on the now-absent import, so it is a property of the binary:

  • windowsProcessTreeAddonReadsProcessMemory() — reads the compiled .node and reports whether it still carries the symbol.
  • ensureWindowsProcessTreeCommandLinePatch() deletes such a binary, so a skipped rebuild fails loudly instead of using the prebuilt.
  • ensure-native-runtime.mjs treats it as a load failure, which is what triggers a rebuild — and rebuildNodeRuntimeModules() now repairs the source and stages the headers before node-gyp, so the self-heal actually completes instead of recompiling the same unpatched reader.
  • The relay build asserts it on the artifact it just produced.

The repair never worked

git apply run inside a work tree prefixes patch paths with the cwd-relative prefix, skips everything that does not match, and exits 0. Reproduced here: exit 0, marker count 0 afterwards. The package dir is always under the project root in production, so the repair branch was dead code that always fell through to its own post-check throw with a message that misdescribed what happened. My fixture missed it because mkTempProject() builds in %TEMP%, outside any repo — where the identical command works.

Fixed by blinding git to the repo (GIT_DIR pointed at a non-existent path; GIT_CEILING_DIRECTORIES does not work). Verified inside the repo work tree: repairs correctly, and is idempotent. The test now calls initGitWorkTree() first, and the fixture writes the real pristine source reconstructed from the patch's own pre-image — verified byte-identical to the upstream file — so git apply has genuine bytes to match rather than a placeholder.

Also from review

  • ProcessInfo pinfo{} — memory was uninitialized stack garbage. Measured before: 538/538 processes reported non-zero working sets with the value 458 repeated 82 times. After: 404/538 non-zero, matching the openable count, no repeated garbage. Pre-existing upstream bug in the function this patch already edits.
  • windows-process-table.ts:194 no longer describes CommandLine as "a PEB read".
  • patchedFile() in the test no longer drops truly-empty context lines; its reconstruction is verified byte-identical to git apply output for both files.
  • The addon suite now fails rather than skips on win32, since both readers emit byte-identical strings and a skipping suite would pass against the very binary this patch exists to keep out.

How the patched addon ships

pnpm-workspace.yaml → patchedDependencies['@vscode/[email protected]']. rebuild-native-deps.mjs rebuilds against Electron's ABI (x64 + arm64) with force: true; build-windows-process-tree-relay-addon.mjs compiles the relay artifact against Node headers. Verified by reconstructing pristine 0.8.0, applying this patch (all three files clean) and building with node-gyp rebuild --arch=x64; every measurement above is from that binary.

Lockfile: the patch hash appears in three places — patchedDependencies, the importer's version: key, and the snapshot key (patch_hash=…). All three are updated; missing the latter two would break --frozen-lockfile.

Conflicts with #17866

git merge-tree showed zero conflicts at review time. This revision adds an edit to src/main/windows/windows-process-table.ts — a 5-line comment reflow at line 194 (NB6), requested in review because the stale "PEB read" wording sits outside both PRs' edit regions and would otherwise survive both. That is the one new conflict surface; it is comment-only.

Verification

  • tsc -p config/tsconfig.node.json ✅ (needs --max-old-space-size=8192 here), tsc -p config/tsconfig.tc.cli.json ✅
  • oxlint ✅ — 5 warnings, all pre-existing react-hooks/exhaustive-deps in src/renderer, none in changed files
  • config/scripts/rebuild-native-deps-node-pty.test.mjs ✅ all pass, including the two new repair cases
  • vitest src/main/windows/ — 59 passed, 2 failed:
    • windows-host-job.win32.test.ts — fails identically on a stashed tree, genuinely pre-existing.
    • the new "was built from the patched source" case — a true positive, see above.

Correction to my earlier claims. I previously reported 4 pre-existing failures in src/main/windows/ and 2 in package-electron-runtime-contract.test.mjs. Re-measured on a repaired node_modules: the three windows-pty-job.win32 failures are gone — they were the broken install, exactly as flagged. The package-electron-runtime-contract failures are environment, not product: Could not resolve package serve-sim, whose symlink in the shared node_modules points into a different agent's worktree. The reviewer's 22/22 pass is correct; my "pre-existing" label was wrong.

Risks for a reviewer

  1. No fallback at all. If a hooked ntdll refuses class 60, command lines are empty everywhere and agent-identity matching degrades to image names. That is the deliberate trade — the alternative was silently resuming the flagged primitive — but it is a behaviour cliff, not a graceful one, and it cannot be exercised on any supported OS.
  2. The win32 addon test now fails on a stale native build. Under pnpm test this self-heals (ensure-native-runtime.mjs repairs and rebuilds first); under bare npx vitest in a worktree whose shared node_modules predates this patch, it fails. That is the intended signal, and it matches the existing isPtyJobOwnershipAvailable() precedent, but it will surface for anyone on a stale install.
  3. The repair mutates node_modules. Consistent with applyWindowsProcessTreeBuildFixes(), but in a multi-worktree setup that store is shared.
  4. Class 60 is not in winternl.h, so the class travels as a ULONG and UNICODE_STRING is read from a raw buffer — now bounds-checked and size-capped.
  5. git must be on PATH for the repair; failure is a loud throw, not a silent unpatched build.
  6. The end-to-end self-heal chain is verified by parts (detect → repair-in-work-tree → delete stale binary → compile → absent import), not as one run, because completing it here would rewrite the node_modules other worktrees share.

P0: pnpm install --frozen-lockfile was failing on this branch

Commit 0b0c9d4b7e. This broke every CI job and the release build (the branch's own package (windows) job died at 25s with it), and it was shipped twice.

Two coupled defects. config/patches/@[email protected] was committed with CRLF — 174 CR bytes, against zero on main — and .gitattributes pins /config/patches/*.patch -text precisely so checkout cannot convert it, so those bytes reached every runner on every platform. And pnpm hashes a patch LF-normalized, so the raw sha256 of a CRLF file is a number pnpm never produces:

raw sha256(patchBytes) 322965470c05f63d8527f7d8e892ee26ee444136b66b57fd64c362a9f2ff05d1
LF-normalized f8ea245391c94da5770045aeea01fa6de466c2199c6ef46b5b769b398aa9823e

The lockfile carried the raw value at all three sites. It is the only one of the seven patches where the two digests differ, which is why the other six passed and this one did not.

Fix: normalized the patch to LF and took pnpm's own value from pnpm install --no-frozen-lockfile — nothing hand-computed. With the file LF-only the two interpretations coincide, so the lockfile, the contract test's no-CR assertion and its hash assertion all agree at one number. config/scripts/windows-process-tree-patch-contract.test.mjs, which was red on this branch for the same reason, is green again. The lockfile diff is exactly the three hash lines — no other churn.

Measured, in isolated scratch dirs holding only the manifest, lockfile, workspace file and config/patches/:

  • shipped state → ERR_PNPM_LOCKFILE_CONFIG_MISMATCH, exit 1
  • LF patch + shipped raw hash → still exit 1 (normalizing alone does not fix it; the hash is the functional half)
  • CRLF patch + LF hash → exit 0 (confirming pnpm normalizes before hashing)
  • fixed state, exported with git archive from the commit to simulate a CI checkout → exit 0

The regression check is the installer, not a digest. Two separate reviews "verified" the shipped hash by recomputing sha256(patchBytes) and matching the lockfile; both agreed and both were wrong, because both repeated the same wrong assumption about which bytes pnpm hashes. So config/scripts/patched-dependencies-frozen-install.test.mjs runs pnpm install --frozen-lockfile --lockfile-only --ignore-scripts against a copy of the real files and asserts exit 0 — verified by deletion: restoring the shipped hash fails it with the exact ERR_PNPM_LOCKFILE_CONFIG_MISMATCH from the failed CI job.

Also corrected the .gitattributes comment claiming pnpm hashes patches byte-for-byte — the claim that produced the wrong hash twice. The -text setting stays, so a patch reads and diffs identically everywhere.

The follow-on claim in this paragraph was wrong, and the next section is the correction. I wrote that the LF patch "still applies through the real repair path" on the strength of rebuild-native-deps-node-pty.test.mjs passing. That suite could not have told me otherwise.

Follow-up 1: normalizing the patch broke the git apply repair

Commit 9104d51582. The LF normalization above and the git apply repair path introduced in this PR are coupled, and I verified only one of them.

The 174 CR bytes were not editor noise. They sat on exactly the pre-image lines and nowhere else, because @vscode/[email protected] ships those two sources as CRLF:

section - lines with CR + lines with CR
src/process.cc 107 107 111 0
src/process_commandline.cc 67 67 125 0
binding.gyp 5 0 3 0

So normalizing the patch made its pre-image stop matching the file it is applied against. Reconstructing the true CRLF pre-image from the pre-normalization blob and applying the current LF patch:

core.autocrlf plain -c core.autocrlf=input
true 0 0
input 0 0
false 1 — "patch does not apply" 0

false is Git's own built-in default and what "checkout as-is" selects in the Git for Windows installer. (On this box the true that hid it comes from the installer's system gitconfig at C:/Program Files/Git/etc/gitconfig — nothing in the repo.) There the repair throws, ensureWindowsProcessTreeCommandLinePatch reports "still reads the PEB, and repairing it … failed", isWindowsNativeLockError does not match that text, and pnpm install fails with no path forward. That repair path is new in this PR, so this is introduced here, not inherited.

Fix: force -c core.autocrlf=input on the repair's git apply. Chosen over --ignore-whitespace — both fix every cell and both leave the applied file fully LF, but input relaxes line endings only, so a hunk whose real content drifted is still rejected. A repair that rewrites a security-relevant source file should stay strict about everything except the thing that is legitimately ambiguous. The patch stays LF: windows-process-tree-patch-contract.test.mjs (pre-existing on main) forbids CR bytes in it, and pnpm computes the same hash either way.

Why the suite said it was fine. rebuild-native-deps-test-fixtures.mjs built its pre-image from the patch itself, joined with '\n' — so fixture and patch agreed by construction on any encoding. It now emits the CRLF the real package ships, and the case runs under both autocrlf modes, pinned through a temp HOME gitconfig (the repair blinds git to the repo with GIT_DIR, so it reads global config, which outranks the system file).

Verified by deletion, both directions:

fixture pre-image -c core.autocrlf=input autocrlf=false case
LF (old) absent passes — vacuous
CRLF (real) absent fails, with the exact "still reads the PEB" dead end
CRLF (real) present passes

Both halves are load-bearing: the flag fixes the defect, the CRLF fixture is what lets the case see it. autocrlf=true passes in every row, which is why one configuration was never enough.

Was the normalization safe at all? Yes, and this is the part worth keeping: a real pnpm install applies the LF patch to the CRLF tarball sources without complaint and materializes them as LF, marker present, ReadProcessMemory absent. pnpm uses its own applier, so the primary install path was never affected — only the git apply fallback was.

Follow-up 2: the packaged binary had no check, and the install test could not see a patch

Commit da4eedfdf1.

Nothing checked the addon that ships. The relay build asserts its own artifact and ensure-native-runtime.mjs asserts what it loads, but the binary copied into the packaged app was unchecked, so a rebuild that quietly produced the upstream reader would reach users. rebuild-native-deps.mjs now asserts clean on it after rebuild().

That is also the caller D4's tri-state was missing. Every existing site branches on === 'unpatched', so 'missing' still behaved exactly like 'clean' everywhere — which was the whole point of making it a state. Here both non-clean states fail, and they fail differently: after a rebuild that reported success, an absent binary is a broken build, not an absence to shrug at. The fake rebuild() now emits stand-in bytes and takes addon: 'clean' | 'unpatched' | 'none'; verified by deletion — with the assertion removed, both new cases pass.

--lockfile-only never applies a patch, so the frozen-install case was bounded to hash consistency and the real question — can pnpm still put the patched reader on disk? — had nothing covering it. Added a case that installs @vscode/[email protected] for real with the patch and asserts the materialized src/process_commandline.cc carries the marker and no longer carries ReadProcessMemory. ~1.5s for the pair.

One correction to the brief I was given: that case does not catch the git apply breakage from Follow-up 1. Measured — with -c core.autocrlf=input removed it passes cleanly, because pnpm install uses pnpm's own applier and never runs our repair script. What it does catch is a patch pnpm can no longer apply: corrupting a single pre-image line fails both cases. The repair path stays covered by the CRLF fixture instead.

Dead timeout fixed. The frozen-install case passed timeoutMs: 300_000 to the spawn while config/vitest.config.ts capped the case itself at 30s, so on a cold runner vitest would have killed it first. Both cases now declare the budget they use.

Merge coordination with #17866, updated

The five named lines are confirmed absent from this branch and no stale PEB claim survives in the sources it touches. But the overlap is real and worth stating for whoever lands second: #17866's subject — splitting the flag sets — is precisely the block this branch leaves at windows-process-table.ts:256-259 and rewrites around. Expect a hand-reconciled conflict on loadWindowsProcessTree and the flags constant. The trap is that taking either side wholesale silently drops one of the two features, so that hunk needs merging by hand rather than by resolution shortcut.


Follow-up round: five reviewed findings applied

Commits e7f2e963fa, 1ce0249ab0, 1dd00a9b2c, 15c0b5e947, b211283657.

D1 — pnpm install while Orca is running aborted with a raw EPERM stack. The stale-binary guard in rebuild-native-deps.mjs sat outside the try whose catch classifies Windows file locks and prints "Close running Orca/Electron/dev processes for this worktree". Reproduced empirically first: rmSync against a loaded (memory-mapped) addon throws EPERM, Permission denied, force: true does not help (it only swallows ENOENT), and a cold copy of the same file deletes fine. Moving the guard inside the try is the whole fix — the classifier already matches the EPERM text. New end-to-end case runs the real script against a temp project whose stale addon is held open by a live child process; verified by deletion: against the old placement it fails with the raw syscall: 'rm' stack.

D2 — the no-fallback cliff is now observable (this retires risk #1 above). One warning per session, keyed on the reviewer's signal: our own pid always grants the handle and always has a command line, so rows.find(r => r.pid === process.pid) coming back empty is unambiguous evidence the info class is refused host-wide. No threshold, no per-process logging, and gated on the CommandLine flag actually being requested so a future identity-only reader cannot trip it. The suite's SELF fixture gained a command line for the same reason: a self row without one is the alarm.

D3 — the binary check now covers the relay's staged addon. loadWindowsProcessTree checks ./windows-process-tree.node beside the bundle and refuses one that still imports the symbol, falling back to the CIM scan. The build-time assertion was not enough: a bundle and the addon beside it redeploy independently. The predicate is duplicated rather than imported — the config-script copy is install-time tooling that drags in node-gyp and child_process, and this module is bundled into the app and the relay. The doc's Packaging section states the redeploy dependency too. Verified by deletion: with the check removed, the unpatched staged addon is bound and the CIM fallback never runs.

D4 — the check is tri-state. windowsProcessTreeAddonReadsProcessMemory() → inspectWindowsProcessTreeAddon(addonPath) returning 'clean' | 'unpatched' | 'missing', over an explicit binary path (which is also what makes D3 possible). All three existing callers updated, and each now states which state it acts on. Verified by deletion: folding 'missing' back into 'clean' fails the absence case.

D5 — loadAddon() moved into beforeAll. At collection time a missing addon took the seven patch-text cases down with it. Verified both ways against a deliberately unresolvable path: at collection time vitest reports "no tests" for the whole file; from beforeAll the seven text cases pass and only the three addon cases go.

Also fixed: ensure-native-runtime.test.mjs staged only the script, not the windows-process-tree-gyp-rebuild.mjs import this PR added, so every case in that suite died with ERR_MODULE_NOT_FOUND. Now uses copyScriptWithLocalModules, whose doc comment names exactly this failure.

Merge coordination with #17866

The five contradictory doc/comment lines flagged in the composition review — windows-process-table.ts:32 ("Dropping Memory halves the per-process handle opens but not the PEB reads"), :46 ("Adds the PEB-derived command line"), :259 (PROCESS_VM_READ plus an NtQueryInformationProcess for the PEB address), and docs/reference/windows-process-enumeration.md:62 / :179-180 — do not exist on this branch. They are entirely #17866's to own; grepping this tree for PEB returns only correct, historical uses. Nothing was edited for them here, so no new conflict surface was created.

Lines this round did touch, for whoever resolves the merge:

  • src/main/windows/windows-process-table.ts — new import line at the top; a new stagedRelayAddonIsUnpatched() helper and FLAGGED_ADDON_IMPORT constant after RELAY_ADDON_FILENAME; the relay branch of loadWindowsProcessTree() restructured from a ternary into early returns; a 3-line health call added inside the getAllProcesses callback right after the self-presence guard; __setWindowsProcessTreeRequireForTests signature widened to NativeRequire.
  • docs/reference/windows-process-enumeration.md — the windowsProcessTreeAddonReadsProcessMemory() sentence in "There is no PEB fallback, deliberately"; "Three checks close that" → "Four checks close that" plus a fourth bullet; one paragraph appended to Packaging.
  • config/scripts/: windows-process-tree-gyp-rebuild.mjs (the inspector and its call site), ensure-native-runtime.mjs and build-windows-process-tree-relay-addon.mjs (import plus one call each), rebuild-native-deps.mjs (the win32 block moved inside the try).
  • .gitattributes (one comment), config/patches/@[email protected] (line endings only), pnpm-lock.yaml (three hash lines).

Verification, this round

  • config/scripts/run-typecheck-projects-in-parallel.mjs ✅ exit 0
  • oxlint --config .oxlintrc.json src config tests ✅ exit 0 (same 5 pre-existing react-hooks/exhaustive-deps warnings in src/renderer, none in changed files); check-max-lines-ratchet.mjs ✅; oxfmt --check ✅ on the touched files
  • New/changed suites all pass: windows-process-table.test.ts (30), windows-command-line-recovery-health.test.ts (5), windows-process-tree-gyp-rebuild.test.mjs (7), rebuild-native-deps-windows-process-tree.test.mjs (1), patched-dependencies-frozen-install.test.mjs (1), windows-process-tree-patch-contract.test.mjs (1, now green), rebuild-native-deps.test.mjs, rebuild-native-deps-node-pty.test.mjs
  • pnpm-lock.yaml diff is exactly the three patch-hash lines.

Failures I did not fix, stated plainly. This worktree borrows node_modules from another worktree on a different branch (pnpm install cannot run in long paths on this box — LongPathsEnabled is 0), so its @vscode/windows-process-tree is built from that branch's unpatched source and its node-pty is likewise foreign. Each was confirmed identical on the pristine PR head, or on origin/main:

  • windows-pty-job.win32.test.ts (3) and windows-host-job.win32.test.ts (1) — borrowed node-pty reports no job ownership. Identical on the pristine head.
  • ensure-native-runtime.test.mjs (2) — not the borrowed node_modules, which is what I first said. The cause is inside the %TEMP% fixture: conpty.dll is never staged for these two cases. On Windows the only cases that run are the two that skip writePatchedNodePtyBuildArtifacts; the ones that call it are skipIf(win32). Verified by reading the fixture and by the failure naming a path under %TEMP%, and confirmed failing on origin/main with the same assertion. Still pre-existing and host-shaped — but the mechanism I named was wrong, which is now the fourth "environmental" attribution in this effort to do that. I have stopped calling a failure environmental without naming the specific file and line that produces it.

I earlier listed windows-process-tree-patch-contract.test.mjs as environmental CRLF noise. It was not — it was the P0 above, and it is now green.

Correction: the binary assertion has now been executed truthfully

I first reported that windows-process-tree-command-line-patch.test.ts — "was built from the patched source, not the published prebuild" — could only be observed failing here, against a borrowed node_modules carrying main's patch, and that the dumpbin result had to stand on its own. That is no longer the limit of the evidence.

A patched build does exist on this box, and the suite has been run against it: 10/10 pass, including the ReadProcessMemory byte check and the live command-line recovery scan. The addon was confirmed to be a build of this PR's patched source — its staged src/process_commandline.cc is byte-identical to the current patch's post-image modulo line endings — and it is clean of ReadProcessMemory while carrying NtQueryInformationProcess. Package resolution was shadowed for the run and the shadows removed afterwards; the patch touches only binding.gyp and the two .cc files, so the JS side is unaffected.

So the check now discriminates in both directions: it passes against the patched addon and fails against main's. That is the property that makes it a guard rather than an assertion nobody has seen succeed. The three remaining local failures above are unchanged and all still trace to the borrowed foreign node_modules.

CI registration

Commit aa601a1a38 closes a lane gap found alongside this work: src/main/windows/windows-process-tree-command-line-patch.test.ts and config/scripts/rebuild-native-deps-windows-process-tree.test.mjs ran in no CI lane — the one windows-2022 job runs a curated file list, and the full suite runs only on ubuntu, where both self-skip. Both are now in the Test Windows-specific boundaries step in .github/workflows/pr.yml and in WINDOWS_PACKAGE_TESTS in config/scripts/pr-code-change-scope.mjs, with a comment recording that the step invokes vitest directly rather than through pnpm test, so the addon assertions hold only once install-node-dependencies has rebuilt natives. classifyPrJobs returns package_windows: true for both paths.

Worth noting that this lane could not have worked before the P0 above: install-node-dependencies runs pnpm install --frozen-lockfile --ignore-scripts, which was the failing command. The native-modules cache key also hashes the patch file, so the LF normalization busts it and the lane gets a fresh compile rather than a restored stale build.



Scope of impact (added after SSH review; corrected)

No released relay carries windows-process-tree.node — verified on both platforms. build-windows-process-tree-relay-addon.mjs appears only in .github/workflows/dev-channel-win-build.yml:240-241, never in release-cut.yml, and src/shared/relay-artifacts.ts:57 marks the artifact optional: true so its absence is not a build failure. Confirmed by extracting the real orca-windows-setup.exe from v1.4.197 (NSIS → $PLUGINSDIR/app-64.7z): resources\relay\win32-x64\ and win32-arm64\ contain the seven JS artifacts and .version, and no .node. Same for Orca-1.4.197-mac.zip.

This splits the PR's value unevenly, and the description above did not say so:

  • Desktop — the bulk of the value, and it is real. @vscode/[email protected] is a production dependency (package.json:283) and electron-builder auto-unpacks native modules, so the desktop app does load the addon and is running the PEB read today. (Inferred from packaging config; only the relay tree was extracted from the installer.)
  • SSH hosts — the removal is a no-op. The PEB read this patch deletes was never executing on a released relay.
  • SSH hosts — the D3 refusal guard protects a population that could not be demonstrated. See below.

Correction: the stale-addon scenario could not be constructed

An earlier revision of this section claimed a .node staged by a dev-channel client survives a later redeploy from a release client, because promoteWindowsRelayUploadStageCommand (ssh-relay-upload-stage-windows-commands.ts:177) merges rather than replaces. That was wrong and is retracted.

The remote relay directory is content-hash-keyed and immutable: resolveRelayBootstrapState → computeRemoteRelayDir(remoteHome, fullVersion, …) (ssh-relay-deploy.ts:231), and build-relay.mjs:219-236 hashes every required artifact plus the optional addon when present, with the comment "a relay carrying the native addon answers differently from one that falls back to the scan, so the two must not share an immutable directory." A bundle with the addon and one without therefore land in different directories. The merge-not-replace Copy-Item only merges within a single hash's directory, where it repairs a torn install (guarded by RELAY_INSTALL_COMPLETE_FILENAME) — correct behaviour, not a leak.

So the D3 guard should not be reviewed as protecting the population originally described. Under hash-keyed immutable directories the bundle and its addon always move together, and the merge-not-replace Copy-Item only merges within a single hash — where identical hash means identical bytes, so it repairs torn installs and nothing else.

One unguarded path does remain, and it is not the one the guard covers. loadWindowsProcessTree tries the npm package first, before the staged-addon branch:

:171   cachedModule = requireNative('@vscode/windows-process-tree')   <- no guard
:177   const addon = requireNative(RELAY_ADDON_FILENAME)
:186   if (stagedRelayAddonIsUnpatched()) { ... }                      <- guard is here only

requireNative is createRequire(__filename), and on a relay __filename is <home>/.orca-relay/<version>/relay.js. Node then walks upward — <version>/node_modules (which exists; installNativeDeps npm-installs into it), ~/.orca-relay/node_modules, ~/node_modules, and up. A @vscode/windows-process-tree anywhere on that chain is loaded unguarded, and the published prebuilt is the unpatched node-addon-api build that opens every process with PROCESS_VM_READ.

Reachability is low but real: neither relay dependency pulls it transitively (node-pty → {node-addon-api}; @parcel/watcher → {detect-libc, is-glob, node-addon-api, picomatch}), so it requires a pre-existing copy in the user's ~/node_modules or ~/.orca-relay/node_modules on a Windows SSH host — the "ran npm install in my home directory" accident.

Honest summary: a desktop fix; on SSH the removal is a no-op, and the guard is defence-in-depth that sits after the npm-package require — the one resolution path it does not cover. Extending the byte check to both branches is a small follow-up, not a merge condition.

Orca Worker added 2 commits September 1, 2026 00:53
MDE incident D scored Orca for suspicious memory activity: the vendored
`@vscode/windows-process-tree` recovered every process's command line by
opening it with `PROCESS_QUERY_INFORMATION | PROCESS_VM_READ` and chaining
three `ReadProcessMemory` calls through the PEB and
`RTL_USER_PROCESS_PARAMETERS`. On a 750ms/2s cadence over the whole table that
is the credential-dumping primitive, whatever the intent.

Windows 8.1 added `NtQueryInformationProcess`'s `ProcessCommandLineInformation`
class (60), which returns the same string as a kernel-built `UNICODE_STRING`
under `PROCESS_QUERY_LIMITED_INFORMATION` alone. Electron's floor is Windows
10, so every supported OS has it. The PEB reader stays behind a process-wide
latch that only `STATUS_INVALID_INFO_CLASS`/`NOT_SUPPORTED`/`NOT_IMPLEMENTED`
can set; a pid that merely denied a handle does not re-arm it, because
`PROCESS_QUERY_INFORMATION` implicitly grants the limited right and so cannot
be obtained where the weaker open already failed.

The same hunk drops `PROCESS_VM_READ` from `GetProcessMemoryUsage` and
`GetCpuUsage`, which acquired it and never read an address space.

Measured on Windows 11 (514 processes), counted in-process by swapping the
addon's import table entries for counting stubs, per CommandLine scan:
`ReadProcessMemory` 1128 -> 0, desired access 0x0410 -> 0x1000, p50 12.7ms ->
9.3ms. Command lines were byte-identical on every process both readers
recovered (376/376, 379/379 across runs), including a 24,068-character argv
with quotes, non-ASCII and trailing whitespace, and a WOW64 target. Three
processes that refused the old rights granted the new one; none went the other
way.
@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 27343e49-5a2f-43a2-b64c-ec59e57a8225

📥 Commits

Reviewing files that changed from the base of the PR and between aa601a1 and 9104d51.

📒 Files selected for processing (4)
  • .gitattributes
  • config/scripts/rebuild-native-deps-node-pty.test.mjs
  • config/scripts/rebuild-native-deps-test-fixtures.mjs
  • config/scripts/windows-process-tree-gyp-rebuild.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • .gitattributes

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


📝 Walkthrough

Walkthrough

The Windows process tree patch removes the 1,024-process limit, reduces process access rights, and replaces PEB command-line reads with NtQueryInformationProcess class 60. Rebuild and runtime scripts apply the patch, stage headers, inspect addon binaries, and reject unpatched artifacts. Process-table health reporting warns once when the querying process has no command line. Tests cover source reconstruction, binary validation, rebuild failures, command-line fidelity, enumeration, and staged addon loading. Documentation records the updated behavior.

Merge Risk: 🟡 Moderate · up to 9104d

The PR reduces Windows process-access privileges and removes repeated cross-process memory reads, but a native-addon inspection read failure can still accept an unverified binary instead of using the safer fallback path. This creates a bounded runtime/security readiness risk that needs owner follow-up before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 59.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 16 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary change: replacing PEB reads with kernel-based command-line retrieval on Windows.
Description check ✅ Passed The description is comprehensive, relevant, and documents the motivation, implementation, risks, testing, measurements, and follow-up findings. The template's Linked Issue and Visual Proof entries are…
Full details: Docstring Coverage

Explanation

Docstring coverage is 59.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 32 functions across 16 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ 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.

@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 critical issues — two minor diagnosability suggestions inline.

Reviewed changes

  • Kernel command-line read: GetProcessCommandLine now queries ProcessCommandLineInformation (class 60) via a dynamically-resolved NtQueryInformationProcess with only PROCESS_QUERY_LIMITED_INFORMATION, dropping the PEB walk and its ReadProcessMemory calls; the memory/CPU readers no longer acquire PROCESS_VM_READ.
  • Patch-enforcement guards: ensureWindowsProcessTreeCommandLinePatch() repairs an un-applied command-line hunk via git apply and throws if it cannot; both the relay build and the Electron app rebuild call it, and the relay build additionally repairs and asserts against PROCESS_VM_READ in process.cc.
  • Tests: a new test file asserts the patch post-image contract (class-60 preference, limited-information-only outside the fallback, dynamic ntdll resolution, size probe, single UTF-8 conversion) plus two win32-gated runtime cases; a fixture-driven rebuild test asserts the build fails when the patch is missing.
  • Docs/lockfile: docs/reference/windows-process-enumeration.md documents the reader change and measured access-right reduction; pnpm-lock.yaml refreshes the patch hash.

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

'config/patches/@[email protected]; run pnpm install.'
)
}
if (processCc.includes('OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ')) {

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.

This check runs after applyWindowsProcessTreeBuildFixes has already rewritten process.cc with replaceAll (lines 137–140), so an un-applied patch is repaired before this read and the check only fires when the replaceAll string stops matching upstream. That's a useful stale-repair canary, but the message (pnpm did not apply ... run pnpm install) points a maintainer at the wrong fix; the command-line hunk itself is enforced by ensureWindowsProcessTreeCommandLinePatch.

} catch (error) {
throw new Error(
`src/process_commandline.cc still reads the PEB with ReadProcessMemory, and repairing it from ` +
`${WINDOWS_PROCESS_TREE_PATCH_PATH} failed: ${error?.message ?? error}. Run pnpm install.`

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.

execFileSync puts git's actual diagnosis in error.stderr (patch does not apply, No such file), while error.message is just Command failed: git apply .... Surfacing error.stderr here would make the repair failure self-diagnosing.

Orca Worker added 2 commits September 1, 2026 01:38
Review of #17886 found three ways the reader could still perform, or silently
resume, the primitive it exists to remove.

The class-missing latch was a permanent, process-wide, one-way downgrade back
to the PEB read, and any single target returning STATUS_INVALID_INFO_CLASS /
NOT_SUPPORTED / NOT_IMPLEMENTED could trip it. On an EDR-hooked ntdll -- the
entire premise of this change -- a hook that does not recognise class 60 would
have restored PROCESS_VM_READ plus three ReadProcessMemory per pid per scan for
the life of the process, unobservably, on precisely the machines this was
written for. The fallback is deleted rather than guarded: GetProcessCommandLine
now returns false and leaves the command line empty, which callers already
handle, so the addon imports no ReadProcessMemory at all.

That absence is what makes the property checkable on the artifact. The
published 0.8.0 tarball ships a loadable prebuilt built from unpatched source;
it is node-addon-api, so a bare require() accepts it, allowBuilds is false and
CI installs with --ignore-scripts, and a rebuild that soft-exits on a Windows
file lock leaves it in place. Source-text guards could never see it.
windowsProcessTreeAddonReadsProcessMemory() checks the compiled binary instead,
and is wired into the install check, the rebuild, and the relay build.

The repair itself never worked: `git apply` run inside a work tree prefixes
patch paths with the cwd-relative prefix, skips what does not match, and exits
0, so the branch always fell through to its own post-check throw. The package
dir is always under the project root, while the fixture that covered it was in
%TEMP%, outside any repo. Blinding git with GIT_DIR fixes it, and the test now
runs inside a real work tree.

Also from review: bounds-check the returned UNICODE_STRING against the
allocation (not the size the second query clobbers) and cap the probe so a
bogus length cannot bad_alloc a whole scan; test NT_SUCCESS explicitly; value-
initialize ProcessInfo, which left `memory` as stack garbage -- measured, 82
processes reported the same bogus working set; and correct a comment in
windows-process-table.ts that still described the command line as a PEB read.

Re-measured on Windows 11 (543 processes): ReadProcessMemory 1128 -> 0, with
the symbol absent from the import table so the IAT hook finds no slot to
count; desired access 0x0410 -> 0x1000 on all 543 opens; p50 13.5 -> 12.3ms;
405/405 command lines byte-identical including a 24,087-character quoted
non-ASCII argv and a WOW64 target; 3 processes recovered only by the new path,
0 only by the old.

@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 in this delta — the two minor diagnosability suggestions from the prior review remain the only open threads and are unchanged by these commits.

Reviewed changes

  • Dropped the PEB fallback entirely: GetProcessCommandLine now returns empty on any non-class-60 outcome instead of latching back to PROCESS_VM_READ PEB reads; the returned UNICODE_STRING is bounds-checked against the allocation and the probe size is capped at header + 64 KiB.
  • Binary-level prebuilt detection: windowsProcessTreeAddonReadsProcessMemory() keys on the now-absent ReadProcessMemory import and is wired into ensure-native-runtime.mjs, the relay build artifact check, and a delete-on-sight repair.
  • Repaired the repair: git apply is blinded with a non-existent GIT_DIR so the command-line hunk actually applies inside a git work tree; a missing source file now throws.
  • Value-initialized ProcessInfo: memory is no longer stack garbage when the memory flag is unset.
  • Tests/docs/lockfile: fail-rather-than-skip win32 addon suite, work-tree repair fixture tests, updated docs, and a lockfile patch-hash refresh.

The no-fallback decision is sound for Orca's Windows 10 floor, and the bounds-checking plus size cap close the hooked-ntdll over-read path cleanly. The two open threads from the prior review — the relay assertPatchApplied stale-repair message pointing at pnpm install, and ensureWindowsProcessTreeCommandLinePatch rethrowing error?.message rather than error.stderr — are the only remaining items and are left open for the author.

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

Orca Worker added 6 commits September 1, 2026 17:54
… fixture

ensure-native-runtime.mjs gained an import of windows-process-tree-gyp-rebuild.mjs,
but the fixture copied only the script itself, so every case in the suite died
with ERR_MODULE_NOT_FOUND before reaching its own assertions. copyScriptWithLocalModules
already walks a script's co-located imports for exactly this reason -- its own doc
comment names this failure -- so use it rather than listing files by hand.

The two Windows cases still fail here, on a missing node-pty ConPTY runtime that
also fails on main; this only stops a resolution error from standing in front of
whatever they were meant to catch.
…sage

`pnpm install` with Orca running aborted with a raw EPERM stack. The stale-binary
guard -- which deletes an addon that still imports ReadProcessMemory so a skipped
rebuild cannot use it -- ran outside the try whose catch classifies Windows file
locks, and whose message is literally "Close running Orca/Electron/dev processes
for this worktree": exactly this situation.

Measured rather than assumed: rmSync against a loaded (memory-mapped) addon throws
EPERM, and `force: true` does not help, since it only swallows ENOENT. Cold copies
of the same file delete fine. So the delete threw a page before the handler that
knows what it means.

Moving the guard inside the try is the whole fix; the classifier already matches
the EPERM text. The new case runs the real script against a temp project whose
stale addon is held open by a live child process, and fails against the old
placement with the raw `syscall: 'rm'` stack the report described.
Removing the PEB fallback removed a total-defeat vector, but it left a cliff: if
NtQueryInformationProcess(ProcessCommandLineInformation) is refused -- a hooked
ntdll that does not know class 60 -- every command line comes back empty and
agent identity matching silently degrades to image names. The addon still loads
and still enumerates, so every health check the app has stays green. A cliff
nobody can see is the failure mode this area keeps producing.

The querying process is the unambiguous probe. A process can always open itself
with PROCESS_QUERY_LIMITED_INFORMATION, so its own command line coming back empty
means the query is refused for every process -- not that some target denied a
handle, which is normal for roughly a quarter of the table. Keying on our own row
rather than a fraction means no threshold to tune and no false positive on a
hardened box where most processes deny.

One warning per session, gated on the CommandLine flag actually being requested so
a future identity-only reader cannot trip it. The suite's own SELF fixture gains a
command line for the same reason: a self row without one is the alarm, not a
detail.
…state

Two gaps in the ReadProcessMemory check, both about what it does not see.

It only ever looked at node_modules/@vscode/windows-process-tree. A relay host
has no node_modules of ours: it loads ./windows-process-tree.node staged beside
the bundle. The relay build asserts the symbol on the artifact it produces, but a
bundle and the addon beside it redeploy independently, so a host that has not
taken a new bundle keeps whatever binary is already there -- and the published
prebuilt is node-addon-api, so it binds cleanly and then walks every process's
address space. loadWindowsProcessTree now checks that file too and refuses it,
falling back to the CIM scan: slower, but not the thing an EDR quarantines a host
for. The predicate is duplicated rather than imported, because the config-script
copy is install-time tooling that drags in node-gyp and child_process, and this
module is bundled into the app and the relay.

And it returned false for a binary that is not there. All three callers happened
to be safe, but the name read as a safety predicate, so a future caller would take
a missing binary as verified. inspectWindowsProcessTreeAddon() now answers
clean/unpatched/missing over an explicit binary path -- which is also what lets
the relay's staged addon be checked at all -- and each caller states which state
it acts on.

Both are covered by cases that fail against the old code: without the load-time
check the unpatched staged addon is bound and the CIM fallback never runs, and
with 'missing' folded back into 'clean' the absence case fails outright.
loadAddon() ran while the file was being collected, so on a Windows checkout with
no built addon the require threw before any case existed and took the seven
patch-text cases down with it -- cases that read only the patch file and need no
binary at all. Verified both ways against a deliberately unresolvable addon path:
at collection time vitest reports "no tests" for the file; from beforeAll the
seven text cases pass and only the three addon cases go.
…m own its hash

`pnpm install --frozen-lockfile` failed on this branch on every platform with
ERR_PNPM_LOCKFILE_CONFIG_MISMATCH, which breaks CI and the release build.

Two coupled defects. The patch file was committed with CRLF -- 174 CR bytes,
against zero on main -- and `.gitattributes` pins `/config/patches/*.patch -text`
precisely so checkout cannot convert it, so those bytes reached every runner. And
pnpm hashes a patch **LF-normalized**, so the raw sha256 of a CRLF file is a value
pnpm never computes:

  raw sha256      322965470c05f63d8527f7d8e892ee26ee444136b66b57fd64c362a9f2ff05d1
  LF-normalized   f8ea245391c94da5770045aeea01fa6de466c2199c6ef46b5b769b398aa9823e

The lockfile carried the raw one, at all three sites. It is the only one of the
seven patches where the two digests differ, which is why the other six passed.

Normalized the patch to LF and took pnpm's own value from
`pnpm install --no-frozen-lockfile`; nothing here is hand-computed. With the file
LF-only the two interpretations coincide, so the lockfile, the contract test's
no-CR assertion and its hash assertion all agree at one number -- and
`config/scripts/windows-process-tree-patch-contract.test.mjs`, which was red on
this branch for the same reason, is green again. The lockfile diff is exactly the
three hash lines.

The regression check is the installer, not a digest. Two separate reviews
"verified" the shipped hash by recomputing sha256(patchBytes) and matching the
lockfile; both were wrong, because both repeated the same wrong assumption about
which bytes pnpm hashes. A check that reproduces the original mistake is not
independent. So the new case runs `pnpm install --frozen-lockfile --lockfile-only
--ignore-scripts` against a copy of the manifest, lockfile and patches, and
asserts exit 0 -- verified by deletion: restoring the shipped hash fails it with
the exact ERR_PNPM_LOCKFILE_CONFIG_MISMATCH from the branch's package (windows)
job.

Also corrected the `.gitattributes` comment claiming pnpm hashes patches
byte-for-byte. The `-text` setting is right -- `git apply` needs the exact bytes --
but that sentence is the claim that produced the wrong hash twice.

@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: 5bce98a0-475a-49e1-9237-83fca9bbc332

📥 Commits

Reviewing files that changed from the base of the PR and between 3583c04 and b211283.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (16)
  • config/patches/@[email protected]
  • config/scripts/build-windows-process-tree-relay-addon.mjs
  • config/scripts/ensure-native-runtime.mjs
  • config/scripts/ensure-native-runtime.test.mjs
  • config/scripts/rebuild-native-deps-node-pty.test.mjs
  • config/scripts/rebuild-native-deps-test-fixtures.mjs
  • config/scripts/rebuild-native-deps-windows-process-tree.test.mjs
  • config/scripts/rebuild-native-deps.mjs
  • config/scripts/windows-process-tree-gyp-rebuild.mjs
  • config/scripts/windows-process-tree-gyp-rebuild.test.mjs
  • docs/reference/windows-process-enumeration.md
  • src/main/windows/windows-command-line-recovery-health.test.ts
  • src/main/windows/windows-command-line-recovery-health.ts
  • src/main/windows/windows-process-table.test.ts
  • src/main/windows/windows-process-table.ts
  • src/main/windows/windows-process-tree-command-line-patch.test.ts

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

try {
return readFileSync(addonPath).includes(FLAGGED_ADDON_IMPORT)
} catch {
return false

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- applicable repository knowledge files ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print
printf '%s\n' '--- target file ---'
sed -n '1,230p' src/main/windows/windows-process-table.ts
printf '%s\n' '--- direct symbols and callers ---'
rg -n -C 4 'stagedRelayAddonIsUnpatched|adaptAddon|getProcessList|ReadProcessMemory|windows-process-table' src test tests 2>/dev/null || true

Repository: stablyai/orca

Length of output: 41398


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- repository conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
printf '%s\n' '--- main conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src-main.md 2>/dev/null || true
printf '%s\n' '--- remaining target flow ---'
sed -n '200,430p' src/main/windows/windows-process-table.ts
printf '%s\n' '--- focused tests for staged addon loading ---'
sed -n '350,565p' src/main/windows/windows-process-table.test.ts

Repository: stablyai/orca

Length of output: 18054


Fail closed when addon inspection fails. If readFileSync(addonPath) throws, stagedRelayAddonIsUnpatched() returns false. loadWindowsProcessTree() then adapts the already loaded addon, so readNativeRows() can call addon.getProcessList without validating the binary. An unpatched addon can therefore bypass the ReadProcessMemory guard. Return a distinct uninspectable state and use the CIM fallback with a warning.

@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 in this delta — two minor diagnosability findings from the first review remain open and still block approval.

Reviewed changes

  • Tri-state addon inspection: inspectWindowsProcessTreeAddon now answers clean/unpatched/missing instead of a boolean, so an absent binary can never be misread as "verified clean"; the relay build, runtime load path, and repair path all route through it.
  • Relay load-time guard: windows-process-table.ts now refuses a staged relay addon that still imports ReadProcessMemory and falls back to the CIM scan, closing the gap where a bundle and its staged addon redeploy independently.
  • Host-wide refusal signal: reportWindowsCommandLineRecoveryHealth warns once per session when the querying process's own command line comes back empty — the unambiguous probe that class 60 is refused for every process, with no threshold to tune.
  • File-lock routing: the command-line patch repair moved inside rebuild-native-deps.mjs's try, so deleting a locked stale addon surfaces the "close running Orca" message rather than a raw EPERM stack.
  • Tests: tri-state inspection cases, staged-addon refusal, health-warning behavior, a win32 end-to-end stale-addon-under-lock case, and the addon load moved into beforeAll.

The two open threads are unchanged by these commits: the relay assertPatchApplied PROCESS_VM_READ canary still reports "run pnpm install" even though applyWindowsProcessTreeBuildFixes has already replaceAll'd the string it scans, and ensureWindowsProcessTreeCommandLinePatch still rethrows error?.message rather than error.stderr.

Pullfrog  | Fix it ➔ | 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.

ℹ️ The P0 frozen-lockfile fix is correct — no new issues in this delta. Approval remains withheld on the two prior open threads.

Reviewed changes

  • Patch normalized to LF: config/patches/@[email protected] is now LF-only (0 CR bytes), so pnpm's LF-normalized hash and the raw digest coincide.
  • Lockfile hash taken from pnpm: all three patch_hash sites now carry f8ea2453…, which I verified equals the LF-normalized sha256 of the on-disk patch — no hand-computed value.
  • Installer-level regression test: patched-dependencies-frozen-install.test.mjs runs pnpm install --frozen-lockfile --lockfile-only --ignore-scripts against a scratch copy, so the check keys on the command that actually consumes the hash rather than recomputing the wrong assumption.
  • .gitattributes comment corrected: the -text setting stays, but the misleading "byte-for-byte" claim that produced the bad digest twice is gone.

The two threads from the first review — the relay assertPatchApplied PROCESS_VM_READ canary still reporting "run pnpm install" after applyWindowsProcessTreeBuildFixes has already rewritten the string, and ensureWindowsProcessTreeCommandLinePatch rethrowing error?.message instead of error.stderr — are unchanged by this commit and remain the sole gate.

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

Both suites only self-skip off Windows, so the binary-level check that the
addon carries no ReadProcessMemory passed vacuously in every lane.

@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 in this delta — the two minor diagnosability threads from the first review remain open and unchanged.

Reviewed changes

  • Windows CI now runs both process-tree patch suites: the package_windows job's Test Windows-specific boundaries vitest step lists config/scripts/rebuild-native-deps-windows-process-tree.test.mjs and src/main/windows/windows-process-tree-command-line-patch.test.ts, so their win32-gated addon assertions — including the ReadProcessMemory-absent binary check — execute instead of self-skipping in every lane.
  • Code-change scope registers the same suites: both files were added to WINDOWS_PACKAGE_TESTS in config/scripts/pr-code-change-scope.mjs, so edits to either now trigger the Windows package job.

The coverage gap this closes is real: the was built from the patched source, not the published prebuild assertion and the locked-addon file-lock test previously ran nowhere, because both self-skip off Windows and neither was listed in the Windows job. The placement is sound — install-node-dependencies runs ensure-native-runtime.mjs --runtime=node first, which enforces the patch and rebuilds the addon before the vitest step, and the cache key already includes the patch file hash. The two threads from the first review — the relay assertPatchApplied PROCESS_VM_READ canary reporting run pnpm install after applyWindowsProcessTreeBuildFixes has already rewritten the string, and ensureWindowsProcessTreeCommandLinePatch rethrowing error?.message rather than error.stderr — are in files this commit does not touch and remain the sole gate.

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

Orca Worker added 2 commits September 1, 2026 18:59
My LF normalization of the windows-process-tree patch broke the `git apply`
repair path introduced in this PR. The two are coupled and I checked only one.

Those 174 CR bytes were not editor noise. They sat on exactly the pre-image
lines and nowhere else -- 107/107 in src/process.cc, 67/67 in
src/process_commandline.cc, 0 on every added or context line -- because
@vscode/[email protected] ships those two sources as CRLF. Normalizing
the patch made its pre-image stop matching the file it is applied against.

Measured, reconstructing the true CRLF pre-image from the pre-normalization
blob and applying the current LF patch:

  core.autocrlf   plain   -c core.autocrlf=input
  true            exit 0  exit 0
  input           exit 0  exit 0
  false           exit 1  exit 0

`false` is Git's own built-in default and what "checkout as-is" selects in the
Git for Windows installer -- on this box the `true` that hides it comes from the
installer's system gitconfig, not from anything in the repo. There the repair
throws, ensureWindowsProcessTreeCommandLinePatch reports "still reads the PEB,
and repairing it ... failed", isWindowsNativeLockError does not match that text,
and `pnpm install` dies with no path forward.

Forcing the mode rather than `--ignore-whitespace`: both fix every cell and both
leave the applied file fully LF, but `input` relaxes line endings only, so a hunk
whose real content drifted is still rejected. The repair rewrites a
security-relevant source file; it should stay strict about everything except the
thing that is legitimately ambiguous.

Not reverting the patch to CRLF: windows-process-tree-patch-contract.test.mjs
(pre-existing on main) forbids CR bytes in it, and pnpm computes the same hash
either way. LF plus the forced mode is the end state.

The suite could not have caught this. The fixture built its pre-image from the
patch itself and joined with '\n', so fixture and patch agreed by construction on
any encoding -- once again a test that passes without its fix. It now emits the
CRLF the real package ships, and the case runs under both autocrlf modes pinned
through a temp HOME gitconfig, because the repair blinds git to the repo and so
reads global config. Verified by deletion in both directions: with the flag
removed the autocrlf=false case fails with the exact "still reads the PEB" dead
end while autocrlf=true still passes, and with the fixture back on LF all eight
cases pass with no fix present at all.

Also corrected the .gitattributes comment I added last commit. It said `git
apply` needs the bytes the patch was written against, which is now false -- the
pinned bytes are LF and the bytes it was written against are CRLF. That is the
same class of confident-and-wrong claim that produced the bad hash twice.
…l in tests

Three follow-ups from review.

**The packaged binary had no check.** The relay build asserts its own artifact
and ensure-native-runtime asserts what it loads, but nothing looked at the addon
copied into the packaged app -- so a rebuild that silently produced the upstream
reader shipped. `rebuild-native-deps.mjs` now asserts `clean` on it after
`rebuild()`. This is also the caller D4's tri-state was missing: every existing
site branches on `=== 'unpatched'`, so `missing` still behaved exactly like
`clean` everywhere, which was the thing making it a state rather than a boolean.
Here both non-clean states fail, and they fail differently: after a rebuild that
reported success, an absent binary is a broken build, not an absence to shrug at.

The fake `rebuild()` had to start producing a binary for that to mean anything,
so it now emits stand-in bytes and takes `addon: 'clean' | 'unpatched' | 'none'`.
Verified by deletion: with the assertion removed both new cases pass.

**The frozen-install case could not see a patch at all.** `--lockfile-only`
resolves and never applies one, so its coverage stops at hash consistency. Added
a case that installs `@vscode/[email protected]` for real with the patch
and asserts the materialized `src/process_commandline.cc` carries the marker and
no longer carries `ReadProcessMemory` -- about 1.5s for the pair.

Correcting the brief on that one: it does **not** catch the `git apply` breakage
from the previous commit. Measured -- with `-c core.autocrlf=input` removed it
passes cleanly, because `pnpm install` uses pnpm's own patch applier and never
runs our repair script. What it does catch is a patch pnpm can no longer apply:
corrupting one pre-image line fails both cases. The repair path stays covered by
the CRLF fixture in rebuild-native-deps-node-pty.test.mjs.

Worth recording, since it decides whether the LF normalization was safe at all:
pnpm applies the LF patch to the CRLF tarball sources without complaint, and
materializes them as LF with the marker present and `ReadProcessMemory` absent.
The primary install path was never affected -- only the `git apply` fallback was.

**Dead timeout.** The frozen-install case passed `timeoutMs: 300_000` to the
spawn while vitest capped the case itself at 30s, so on a cold runner vitest
would have killed it first. Both cases now declare the budget they use.

@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 in this delta — the fix is correct, and the two minor diagnosability threads from the first review remain open and unchanged.

Reviewed changes

  • Forced core.autocrlf=input on the repair's git apply: the LF-stored patch's pre-image lines differ from upstream's CRLF process_commandline.cc by a CR, so under core.autocrlf=false (Git's built-in default) the hunk failed to match; -c core.autocrlf=input normalizes line endings for that comparison and nothing else, so a genuinely drifted hunk is still rejected.
  • Faithful CRLF test fixture: unpatchedWindowsProcessTreeCommandLineSource now reconstructs the pre-image as CRLF (what the package actually ships) instead of LF, and the repair test loops over autocrlf=false/true via a new gitLineEndingEnv helper that pins git to a temp HOME/USERPROFILE, so the case covers the host that breaks rather than whichever config happens to be present.
  • .gitattributes comment corrected: the patch files are now documented as LF with a git apply-must-force-input requirement, replacing the earlier wording that produced the wrong digest twice.

I verified the fix empirically against the real git behavior: git apply of the LF patch against the CRLF source exits 1 under core.autocrlf=false and 0 under -c core.autocrlf=input, and config/scripts/rebuild-native-deps-node-pty.test.mjs passes (2 repair cases).

The two threads from the first review — the relay assertPatchApplied PROCESS_VM_READ canary still reporting run pnpm install after applyWindowsProcessTreeBuildFixes has already rewritten the string, and ensureWindowsProcessTreeCommandLinePatch still rethrowing error?.message rather than error.stderr — are unchanged by this commit and remain the sole gate.

Pullfrog  | Fix it ➔ | 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 in this delta — the packaged-addon assertion and the real-install test are correct, and the two minor diagnosability threads from the first review remain open and unchanged.

Reviewed changes

  • Post-rebuild addon assertion: rebuild-native-deps.mjs now calls assertWindowsProcessTreeAddonIsPatched() after rebuild(), so the binary copied into the packaged node_modules is verified clean — a rebuild that reports success but leaves no addon, or an addon that still imports ReadProcessMemory, fails loudly rather than shipping the flagged reader.
  • Fixture emits stand-in addon bytes: writeFakeElectronRebuild takes an addon: 'clean' | 'unpatched' | 'none' mode and emits matching bytes so the assertion's missing and unpatched branches are each exercised end-to-end.
  • Real-install patch test: patched-dependencies-frozen-install.test.mjs gained a case that runs a genuine pnpm install --no-frozen-lockfile --ignore-scripts of the single dependency and asserts the materialized process_commandline.cc carries the marker and no longer carries ReadProcessMemory — covering what --lockfile-only never could.
  • Timeout fix: the frozen-install case's 300s spawn budget now reaches the spawn by declaring a matching it timeout, since config/vitest.config.ts otherwise caps the case at 30s.

I ran config/scripts/rebuild-native-deps-node-pty.test.mjs (10 passed, including both new unpatched/none cases) and config/scripts/patched-dependencies-frozen-install.test.mjs (2 passed).

The two threads from the first review — the relay assertPatchApplied PROCESS_VM_READ canary still reporting run pnpm install after applyWindowsProcessTreeBuildFixes has already rewritten the string, and ensureWindowsProcessTreeCommandLinePatch still rethrowing error?.message rather than error.stderr — are unchanged by this commit and remain the sole gate.

Pullfrog  | Fix it ➔ | 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 in this delta — a clean base-branch sync. The two prior diagnosability threads remain open and unchanged.

Reviewed changes

  • Merged main into the branch: a single merge commit (cbc5eecd29) brought main's perf(windows): stop asking the process table for memory (#18151) and refactor(process-table): extract the correlation indexes (#18246) into the PR's windows-process-table.ts.
  • Memory flag dropped from the table snapshot: readNativeRows now requests CommandLine | CreationTime only; the "Why CommandLine but not Memory" comment and the never memory test case came in from main and compose cleanly with the PR's kernel-read addon, which still drops PROCESS_VM_READ from the memory reader's own handle.
  • Snapshot-reader module rename: the process-table-snapshot → process-table-snapshot-reader import moved with it; the PR's createProcessTableSnapshotReader call site is intact.
  • Docs: main's windows-edr-posture.md rewrite now declares "The memory read is gone" and cites inspectWindowsProcessTreeAddon(); the PR's windows-process-enumeration.md "no PEB fallback" and "four checks" sections survived the merge untouched.

I verified the composition in windows-process-table.ts: the PR's stagedRelayAddonIsUnpatched, FLAGGED_ADDON_IMPORT, and reportWindowsCommandLineRecoveryHealth hook all survive alongside main's Memory-flag drop, and the SELF test fixture still carries a command line so the host-wide-refusal alarm stays exercisable. The two prior diagnosability threads — the relay assertPatchApplied stale-repair message and the error?.message vs error.stderr rethrow — are in files this merge does not touch and remain the sole gate.

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

…tion owner

The new patched-dependencies check hand-rolled a PATH walk naming 'pnpm.cmd',
which the windows batch shim spawn boundary ratchet rejects: pnpm-cli-invocation
already owns that decision for every other script, and its allowlist only
shrinks.

Reuse resolvePnpmCliInvocation for the command and prefixArgs, and the shared
resolveCliCommand for the presence check, so no shim name is spelled here. Its
`shell` flag is dropped because runProcessSync refuses it and already drives a
shim through the interpreter itself.

@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 in this delta — the frozen-install check now resolves pnpm through the shared invocation owner. The two diagnosability threads from the first review remain open and unchanged.

Reviewed changes

  • Delegated pnpm resolution to the owner module: patched-dependencies-frozen-install.test.mjs dropped its hand-rolled PATH scan for pnpm.exe/pnpm.cmd; resolvePnpmInvocation() now calls resolvePnpmCliInvocation() (which prefers npm_execpath when set) and falls back to resolveCliCommand for the bare-vitest case. This also removes the .cmd literal that windows-cmd-shim-spawn-boundary.test.mjs rejects, and runProcessSync still drives a shim through cmd.exe itself, so dropping the resolver's shell field is safe.

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

@OrcaWin
OrcaWin merged commit bfc6a26 into main Sep 6, 2026
31 checks passed
brennanb2025 pushed a commit that referenced this pull request Sep 6, 2026
windows-process-tree-patch-contract.test.mjs requires the patch file to
carry no CR bytes. Regenerating through pnpm patch-commit emitted 199 of
them, because the creation-time change is the first to touch files the
package ships as CRLF (src/process.h, src/process_worker.cc,
src/addon.cc, lib/index.js, lib/index.ts, the typings) -- and #17886's
own hunks over binding.gyp and src/process_commandline.cc carry the rest.

Stripping them is safe and changes nothing the lockfile records: pnpm
hashes patches CRLF-normalized, so the digest stays
e66202cc623996d02040c93449eb9ae353fddadf426cb53202a59ee710ee6fe7 and now
equals the file's plain sha256 too. It also still applies -- verified
against a deleted store entry, not a warm one -- and the precedent was
already there: the previous patch was LF-only and had been patching
those same CRLF files all along.

ensure-native-runtime.test.mjs stages the siblings the script loads at
module scope into its temp project. The import walk added by #17886 sees
`from './x.mjs'` only, so the createRequire'd .cjs siblings still have to
be named, and this PR adds a second one.
brennanb2025 added a commit that referenced this pull request Sep 6, 2026
…tion time (#18986)

* fix(windows): guard process creation times

* fix(windows): ask the relay's bare addon for creation times too

The relay addon build now emits creationTimeMs, but the runtime binding
for the bare addon still declared only CommandLine, so a Windows relay
host requested flag 2 and every row came back without a creation time.
That leaves captureWindowsDescendantSnapshot returning null and
verifyWindowsProcessIdentity false forever on those hosts -- the relay
half of the patch was unreachable.

Naming CreationTime in the adapter is safe because the bare addon is a
content-hashed relay artifact: it ships in the same immutable relay
directory as the bundle reading it, so it can never be older than the
code asking for the bit.

Also bound the win32 guard test on our own row, which the addon can
never fail to answer, so an unconverted FILETIME or a 1601-epoch stamp
fails instead of satisfying a bare count.

* fix(windows): make the compiled addon prove its own CreationTime support

CI caught the real defect: the win32 guard test read
isWindowsProcessStartTimeAvailable() as true and then found 0 rows
carrying creationTimeMs. Unlike node-pty, this package publishes a
prebuilt .node at the same build/Release path node-gyp writes to, so
pnpm patches the source tree and leaves that binary alone. A host then
holds a patched lib/index.js -- ProcessDataFlag.CreationTime and all --
over a binary that ignores flag 4, and neither a load check nor a path
check can see the difference.

So the binary now says so itself: addon.cc exports
supportedProcessDataFlags, lib/index.js re-exports it, and

  - windows-process-tree-creation-time.cjs asserts it during install,
    which is what forces a from-source rebuild. It is shared by the Node
    probe in ensure-native-runtime.mjs and the Electron probe in
    rebuild-native-deps.mjs, exactly as node-pty-job-ownership.cjs is --
    the Electron half matters because that probe decides onlyModules, so
    without it the packaged app would ship the stale prebuilt.
  - isWindowsProcessStartTimeAvailable() gates on the reported bit, not
    the enum. Believing the enum is worse than reporting false: the
    descendant snapshot returns null forever and the exit proof latches
    unverifiable while structured chat believes it has a reaper.

rebuildNodeRuntimeModules could not actually have rebuilt this package:
the patched binding.gyp includes deps/node-addon-api, which the tarball
does not ship, and node-gyp must run from the physical dir.

Also closes the relay repair path's divergence: repairCreationTimeSources
wrote the C++ but not the buildNode splat or the tree-node typing, and
assertPatchApplied checked neither, so a repaired tree passed as patched
with buildProcessTree silently dropping the field.

The guard test is unchanged.

* fix(windows): keep the process-tree patch LF-only

windows-process-tree-patch-contract.test.mjs requires the patch file to
carry no CR bytes. Regenerating through pnpm patch-commit emitted 199 of
them, because the creation-time change is the first to touch files the
package ships as CRLF (src/process.h, src/process_worker.cc,
src/addon.cc, lib/index.js, lib/index.ts, the typings) -- and #17886's
own hunks over binding.gyp and src/process_commandline.cc carry the rest.

Stripping them is safe and changes nothing the lockfile records: pnpm
hashes patches CRLF-normalized, so the digest stays
e66202cc623996d02040c93449eb9ae353fddadf426cb53202a59ee710ee6fe7 and now
equals the file's plain sha256 too. It also still applies -- verified
against a deleted store entry, not a warm one -- and the precedent was
already there: the previous patch was LF-only and had been patching
those same CRLF files all along.

ensure-native-runtime.test.mjs stages the siblings the script loads at
module scope into its temp project. The import walk added by #17886 sees
`from './x.mjs'` only, so the createRequire'd .cjs siblings still have to
be named, and this PR adds a second one.

---------

Co-authored-by: Merge Sim <sim@local>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…PEB (stablyai#17886)

* fix(windows): read command lines from the kernel, not each process's PEB

MDE incident D scored Orca for suspicious memory activity: the vendored
`@vscode/windows-process-tree` recovered every process's command line by
opening it with `PROCESS_QUERY_INFORMATION | PROCESS_VM_READ` and chaining
three `ReadProcessMemory` calls through the PEB and
`RTL_USER_PROCESS_PARAMETERS`. On a 750ms/2s cadence over the whole table that
is the credential-dumping primitive, whatever the intent.

Windows 8.1 added `NtQueryInformationProcess`'s `ProcessCommandLineInformation`
class (60), which returns the same string as a kernel-built `UNICODE_STRING`
under `PROCESS_QUERY_LIMITED_INFORMATION` alone. Electron's floor is Windows
10, so every supported OS has it. The PEB reader stays behind a process-wide
latch that only `STATUS_INVALID_INFO_CLASS`/`NOT_SUPPORTED`/`NOT_IMPLEMENTED`
can set; a pid that merely denied a handle does not re-arm it, because
`PROCESS_QUERY_INFORMATION` implicitly grants the limited right and so cannot
be obtained where the weaker open already failed.

The same hunk drops `PROCESS_VM_READ` from `GetProcessMemoryUsage` and
`GetCpuUsage`, which acquired it and never read an address space.

Measured on Windows 11 (514 processes), counted in-process by swapping the
addon's import table entries for counting stubs, per CommandLine scan:
`ReadProcessMemory` 1128 -> 0, desired access 0x0410 -> 0x1000, p50 12.7ms ->
9.3ms. Command lines were byte-identical on every process both readers
recovered (376/376, 379/379 across runs), including a 24,068-character argv
with quotes, non-ASCII and trailing whitespace, and a WOW64 target. Three
processes that refused the old rights granted the new one; none went the other
way.

* chore(deps): refresh the windows-process-tree patch hash in the lockfile

* fix(windows): drop the PEB fallback and detect the unpatched prebuilt

Review of stablyai#17886 found three ways the reader could still perform, or silently
resume, the primitive it exists to remove.

The class-missing latch was a permanent, process-wide, one-way downgrade back
to the PEB read, and any single target returning STATUS_INVALID_INFO_CLASS /
NOT_SUPPORTED / NOT_IMPLEMENTED could trip it. On an EDR-hooked ntdll -- the
entire premise of this change -- a hook that does not recognise class 60 would
have restored PROCESS_VM_READ plus three ReadProcessMemory per pid per scan for
the life of the process, unobservably, on precisely the machines this was
written for. The fallback is deleted rather than guarded: GetProcessCommandLine
now returns false and leaves the command line empty, which callers already
handle, so the addon imports no ReadProcessMemory at all.

That absence is what makes the property checkable on the artifact. The
published 0.8.0 tarball ships a loadable prebuilt built from unpatched source;
it is node-addon-api, so a bare require() accepts it, allowBuilds is false and
CI installs with --ignore-scripts, and a rebuild that soft-exits on a Windows
file lock leaves it in place. Source-text guards could never see it.
windowsProcessTreeAddonReadsProcessMemory() checks the compiled binary instead,
and is wired into the install check, the rebuild, and the relay build.

The repair itself never worked: `git apply` run inside a work tree prefixes
patch paths with the cwd-relative prefix, skips what does not match, and exits
0, so the branch always fell through to its own post-check throw. The package
dir is always under the project root, while the fixture that covered it was in
%TEMP%, outside any repo. Blinding git with GIT_DIR fixes it, and the test now
runs inside a real work tree.

Also from review: bounds-check the returned UNICODE_STRING against the
allocation (not the size the second query clobbers) and cap the probe so a
bogus length cannot bad_alloc a whole scan; test NT_SUCCESS explicitly; value-
initialize ProcessInfo, which left `memory` as stack garbage -- measured, 82
processes reported the same bogus working set; and correct a comment in
windows-process-table.ts that still described the command line as a PEB read.

Re-measured on Windows 11 (543 processes): ReadProcessMemory 1128 -> 0, with
the symbol absent from the import table so the IAT hook finds no slot to
count; desired access 0x0410 -> 0x1000 on all 543 opens; p50 13.5 -> 12.3ms;
405/405 command lines byte-identical including a 24,087-character quoted
non-ASCII argv and a WOW64 target; 3 processes recovered only by the new path,
0 only by the old.

* chore(deps): refresh the windows-process-tree patch hash in the lockfile

* test(scripts): stage a script's local imports into the native-runtime fixture

ensure-native-runtime.mjs gained an import of windows-process-tree-gyp-rebuild.mjs,
but the fixture copied only the script itself, so every case in the suite died
with ERR_MODULE_NOT_FOUND before reaching its own assertions. copyScriptWithLocalModules
already walks a script's co-located imports for exactly this reason -- its own doc
comment names this failure -- so use it rather than listing files by hand.

The two Windows cases still fail here, on a missing node-pty ConPTY runtime that
also fails on main; this only stops a resolution error from standing in front of
whatever they were meant to catch.

* fix(windows): route a locked stale addon to the Windows file-lock message

`pnpm install` with Orca running aborted with a raw EPERM stack. The stale-binary
guard -- which deletes an addon that still imports ReadProcessMemory so a skipped
rebuild cannot use it -- ran outside the try whose catch classifies Windows file
locks, and whose message is literally "Close running Orca/Electron/dev processes
for this worktree": exactly this situation.

Measured rather than assumed: rmSync against a loaded (memory-mapped) addon throws
EPERM, and `force: true` does not help, since it only swallows ENOENT. Cold copies
of the same file delete fine. So the delete threw a page before the handler that
knows what it means.

Moving the guard inside the try is the whole fix; the classifier already matches
the EPERM text. The new case runs the real script against a temp project whose
stale addon is held open by a live child process, and fails against the old
placement with the raw `syscall: 'rm'` stack the report described.

* feat(windows): warn once when command-line recovery is refused host-wide

Removing the PEB fallback removed a total-defeat vector, but it left a cliff: if
NtQueryInformationProcess(ProcessCommandLineInformation) is refused -- a hooked
ntdll that does not know class 60 -- every command line comes back empty and
agent identity matching silently degrades to image names. The addon still loads
and still enumerates, so every health check the app has stays green. A cliff
nobody can see is the failure mode this area keeps producing.

The querying process is the unambiguous probe. A process can always open itself
with PROCESS_QUERY_LIMITED_INFORMATION, so its own command line coming back empty
means the query is refused for every process -- not that some target denied a
handle, which is normal for roughly a quarter of the table. Keying on our own row
rather than a fraction means no threshold to tune and no false positive on a
hardened box where most processes deny.

One warning per session, gated on the CommandLine flag actually being requested so
a future identity-only reader cannot trip it. The suite's own SELF fixture gains a
command line for the same reason: a self row without one is the alarm, not a
detail.

* fix(windows): check the relay's staged addon at load, and answer tri-state

Two gaps in the ReadProcessMemory check, both about what it does not see.

It only ever looked at node_modules/@vscode/windows-process-tree. A relay host
has no node_modules of ours: it loads ./windows-process-tree.node staged beside
the bundle. The relay build asserts the symbol on the artifact it produces, but a
bundle and the addon beside it redeploy independently, so a host that has not
taken a new bundle keeps whatever binary is already there -- and the published
prebuilt is node-addon-api, so it binds cleanly and then walks every process's
address space. loadWindowsProcessTree now checks that file too and refuses it,
falling back to the CIM scan: slower, but not the thing an EDR quarantines a host
for. The predicate is duplicated rather than imported, because the config-script
copy is install-time tooling that drags in node-gyp and child_process, and this
module is bundled into the app and the relay.

And it returned false for a binary that is not there. All three callers happened
to be safe, but the name read as a safety predicate, so a future caller would take
a missing binary as verified. inspectWindowsProcessTreeAddon() now answers
clean/unpatched/missing over an explicit binary path -- which is also what lets
the relay's staged addon be checked at all -- and each caller states which state
it acts on.

Both are covered by cases that fail against the old code: without the load-time
check the unpatched staged addon is bound and the CIM fallback never runs, and
with 'missing' folded back into 'clean' the absence case fails outright.

* test(windows): load the addon in beforeAll, not at collection time

loadAddon() ran while the file was being collected, so on a Windows checkout with
no built addon the require threw before any case existed and took the seven
patch-text cases down with it -- cases that read only the patch file and need no
binary at all. Verified both ways against a deliberately unresolvable addon path:
at collection time vitest reports "no tests" for the file; from beforeAll the
seven text cases pass and only the three addon cases go.

* fix(deps): normalize the windows-process-tree patch to LF and let pnpm own its hash

`pnpm install --frozen-lockfile` failed on this branch on every platform with
ERR_PNPM_LOCKFILE_CONFIG_MISMATCH, which breaks CI and the release build.

Two coupled defects. The patch file was committed with CRLF -- 174 CR bytes,
against zero on main -- and `.gitattributes` pins `/config/patches/*.patch -text`
precisely so checkout cannot convert it, so those bytes reached every runner. And
pnpm hashes a patch **LF-normalized**, so the raw sha256 of a CRLF file is a value
pnpm never computes:

  raw sha256      322965470c05f63d8527f7d8e892ee26ee444136b66b57fd64c362a9f2ff05d1
  LF-normalized   f8ea245391c94da5770045aeea01fa6de466c2199c6ef46b5b769b398aa9823e

The lockfile carried the raw one, at all three sites. It is the only one of the
seven patches where the two digests differ, which is why the other six passed.

Normalized the patch to LF and took pnpm's own value from
`pnpm install --no-frozen-lockfile`; nothing here is hand-computed. With the file
LF-only the two interpretations coincide, so the lockfile, the contract test's
no-CR assertion and its hash assertion all agree at one number -- and
`config/scripts/windows-process-tree-patch-contract.test.mjs`, which was red on
this branch for the same reason, is green again. The lockfile diff is exactly the
three hash lines.

The regression check is the installer, not a digest. Two separate reviews
"verified" the shipped hash by recomputing sha256(patchBytes) and matching the
lockfile; both were wrong, because both repeated the same wrong assumption about
which bytes pnpm hashes. A check that reproduces the original mistake is not
independent. So the new case runs `pnpm install --frozen-lockfile --lockfile-only
--ignore-scripts` against a copy of the manifest, lockfile and patches, and
asserts exit 0 -- verified by deletion: restoring the shipped hash fails it with
the exact ERR_PNPM_LOCKFILE_CONFIG_MISMATCH from the branch's package (windows)
job.

Also corrected the `.gitattributes` comment claiming pnpm hashes patches
byte-for-byte. The `-text` setting is right -- `git apply` needs the exact bytes --
but that sentence is the claim that produced the wrong hash twice.

* ci(windows): run the process-tree patch suites in CI

Both suites only self-skip off Windows, so the binary-level check that the
addon carries no ReadProcessMemory passed vacuously in every lane.

* fix(windows): force core.autocrlf=input for the patch repair

My LF normalization of the windows-process-tree patch broke the `git apply`
repair path introduced in this PR. The two are coupled and I checked only one.

Those 174 CR bytes were not editor noise. They sat on exactly the pre-image
lines and nowhere else -- 107/107 in src/process.cc, 67/67 in
src/process_commandline.cc, 0 on every added or context line -- because
@vscode/[email protected] ships those two sources as CRLF. Normalizing
the patch made its pre-image stop matching the file it is applied against.

Measured, reconstructing the true CRLF pre-image from the pre-normalization
blob and applying the current LF patch:

  core.autocrlf   plain   -c core.autocrlf=input
  true            exit 0  exit 0
  input           exit 0  exit 0
  false           exit 1  exit 0

`false` is Git's own built-in default and what "checkout as-is" selects in the
Git for Windows installer -- on this box the `true` that hides it comes from the
installer's system gitconfig, not from anything in the repo. There the repair
throws, ensureWindowsProcessTreeCommandLinePatch reports "still reads the PEB,
and repairing it ... failed", isWindowsNativeLockError does not match that text,
and `pnpm install` dies with no path forward.

Forcing the mode rather than `--ignore-whitespace`: both fix every cell and both
leave the applied file fully LF, but `input` relaxes line endings only, so a hunk
whose real content drifted is still rejected. The repair rewrites a
security-relevant source file; it should stay strict about everything except the
thing that is legitimately ambiguous.

Not reverting the patch to CRLF: windows-process-tree-patch-contract.test.mjs
(pre-existing on main) forbids CR bytes in it, and pnpm computes the same hash
either way. LF plus the forced mode is the end state.

The suite could not have caught this. The fixture built its pre-image from the
patch itself and joined with '\n', so fixture and patch agreed by construction on
any encoding -- once again a test that passes without its fix. It now emits the
CRLF the real package ships, and the case runs under both autocrlf modes pinned
through a temp HOME gitconfig, because the repair blinds git to the repo and so
reads global config. Verified by deletion in both directions: with the flag
removed the autocrlf=false case fails with the exact "still reads the PEB" dead
end while autocrlf=true still passes, and with the fixture back on LF all eight
cases pass with no fix present at all.

Also corrected the .gitattributes comment I added last commit. It said `git
apply` needs the bytes the patch was written against, which is now false -- the
pinned bytes are LF and the bytes it was written against are CRLF. That is the
same class of confident-and-wrong claim that produced the bad hash twice.

* fix(windows): assert the rebuilt addon, and install the patch for real in tests

Three follow-ups from review.

**The packaged binary had no check.** The relay build asserts its own artifact
and ensure-native-runtime asserts what it loads, but nothing looked at the addon
copied into the packaged app -- so a rebuild that silently produced the upstream
reader shipped. `rebuild-native-deps.mjs` now asserts `clean` on it after
`rebuild()`. This is also the caller D4's tri-state was missing: every existing
site branches on `=== 'unpatched'`, so `missing` still behaved exactly like
`clean` everywhere, which was the thing making it a state rather than a boolean.
Here both non-clean states fail, and they fail differently: after a rebuild that
reported success, an absent binary is a broken build, not an absence to shrug at.

The fake `rebuild()` had to start producing a binary for that to mean anything,
so it now emits stand-in bytes and takes `addon: 'clean' | 'unpatched' | 'none'`.
Verified by deletion: with the assertion removed both new cases pass.

**The frozen-install case could not see a patch at all.** `--lockfile-only`
resolves and never applies one, so its coverage stops at hash consistency. Added
a case that installs `@vscode/[email protected]` for real with the patch
and asserts the materialized `src/process_commandline.cc` carries the marker and
no longer carries `ReadProcessMemory` -- about 1.5s for the pair.

Correcting the brief on that one: it does **not** catch the `git apply` breakage
from the previous commit. Measured -- with `-c core.autocrlf=input` removed it
passes cleanly, because `pnpm install` uses pnpm's own patch applier and never
runs our repair script. What it does catch is a patch pnpm can no longer apply:
corrupting one pre-image line fails both cases. The repair path stays covered by
the CRLF fixture in rebuild-native-deps-node-pty.test.mjs.

Worth recording, since it decides whether the LF normalization was safe at all:
pnpm applies the LF patch to the CRLF tarball sources without complaint, and
materializes them as LF with the marker present and `ReadProcessMemory` absent.
The primary install path was never affected -- only the `git apply` fallback was.

**Dead timeout.** The frozen-install case passed `timeoutMs: 300_000` to the
spawn while vitest capped the case itself at 30s, so on a cold runner vitest
would have killed it first. Both cases now declare the budget they use.

* test(windows): route the frozen-install check through the pnpm invocation owner

The new patched-dependencies check hand-rolled a PATH walk naming 'pnpm.cmd',
which the windows batch shim spawn boundary ratchet rejects: pnpm-cli-invocation
already owns that decision for every other script, and its allowlist only
shrinks.

Reuse resolvePnpmCliInvocation for the command and prefixArgs, and the shared
resolveCliCommand for the presence check, so no shim name is spelled here. Its
`shell` flag is dropped because runProcessSync refuses it and already drives a
shim through the interpreter itself.

---------

Co-authored-by: Orca Worker <orca-worker@localhost>
Co-authored-by: Neil <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tion time (stablyai#18986)

* fix(windows): guard process creation times

* fix(windows): ask the relay's bare addon for creation times too

The relay addon build now emits creationTimeMs, but the runtime binding
for the bare addon still declared only CommandLine, so a Windows relay
host requested flag 2 and every row came back without a creation time.
That leaves captureWindowsDescendantSnapshot returning null and
verifyWindowsProcessIdentity false forever on those hosts -- the relay
half of the patch was unreachable.

Naming CreationTime in the adapter is safe because the bare addon is a
content-hashed relay artifact: it ships in the same immutable relay
directory as the bundle reading it, so it can never be older than the
code asking for the bit.

Also bound the win32 guard test on our own row, which the addon can
never fail to answer, so an unconverted FILETIME or a 1601-epoch stamp
fails instead of satisfying a bare count.

* fix(windows): make the compiled addon prove its own CreationTime support

CI caught the real defect: the win32 guard test read
isWindowsProcessStartTimeAvailable() as true and then found 0 rows
carrying creationTimeMs. Unlike node-pty, this package publishes a
prebuilt .node at the same build/Release path node-gyp writes to, so
pnpm patches the source tree and leaves that binary alone. A host then
holds a patched lib/index.js -- ProcessDataFlag.CreationTime and all --
over a binary that ignores flag 4, and neither a load check nor a path
check can see the difference.

So the binary now says so itself: addon.cc exports
supportedProcessDataFlags, lib/index.js re-exports it, and

  - windows-process-tree-creation-time.cjs asserts it during install,
    which is what forces a from-source rebuild. It is shared by the Node
    probe in ensure-native-runtime.mjs and the Electron probe in
    rebuild-native-deps.mjs, exactly as node-pty-job-ownership.cjs is --
    the Electron half matters because that probe decides onlyModules, so
    without it the packaged app would ship the stale prebuilt.
  - isWindowsProcessStartTimeAvailable() gates on the reported bit, not
    the enum. Believing the enum is worse than reporting false: the
    descendant snapshot returns null forever and the exit proof latches
    unverifiable while structured chat believes it has a reaper.

rebuildNodeRuntimeModules could not actually have rebuilt this package:
the patched binding.gyp includes deps/node-addon-api, which the tarball
does not ship, and node-gyp must run from the physical dir.

Also closes the relay repair path's divergence: repairCreationTimeSources
wrote the C++ but not the buildNode splat or the tree-node typing, and
assertPatchApplied checked neither, so a repaired tree passed as patched
with buildProcessTree silently dropping the field.

The guard test is unchanged.

* fix(windows): keep the process-tree patch LF-only

windows-process-tree-patch-contract.test.mjs requires the patch file to
carry no CR bytes. Regenerating through pnpm patch-commit emitted 199 of
them, because the creation-time change is the first to touch files the
package ships as CRLF (src/process.h, src/process_worker.cc,
src/addon.cc, lib/index.js, lib/index.ts, the typings) -- and stablyai#17886's
own hunks over binding.gyp and src/process_commandline.cc carry the rest.

Stripping them is safe and changes nothing the lockfile records: pnpm
hashes patches CRLF-normalized, so the digest stays
e66202cc623996d02040c93449eb9ae353fddadf426cb53202a59ee710ee6fe7 and now
equals the file's plain sha256 too. It also still applies -- verified
against a deleted store entry, not a warm one -- and the precedent was
already there: the previous patch was LF-only and had been patching
those same CRLF files all along.

ensure-native-runtime.test.mjs stages the siblings the script loads at
module scope into its temp project. The import walk added by stablyai#17886 sees
`from './x.mjs'` only, so the createRequire'd .cjs siblings still have to
be named, and this PR adds a second one.

---------

Co-authored-by: Merge Sim <sim@local>
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.

2 participants