Repository navigation
fix(windows): read command lines from the kernel, not each process's PEB - #17886
Conversation
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.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review. 📝 WalkthroughWalkthroughThe Windows process tree patch removes the 1,024-process limit, reduces process access rights, and replaces PEB command-line reads with Merge Risk: 🟡 Moderate · up to 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)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
ℹ️ No critical issues — two minor diagnosability suggestions inline.
Reviewed changes
- Kernel command-line read:
GetProcessCommandLinenow queriesProcessCommandLineInformation(class 60) via a dynamically-resolvedNtQueryInformationProcesswith onlyPROCESS_QUERY_LIMITED_INFORMATION, dropping the PEB walk and itsReadProcessMemorycalls; the memory/CPU readers no longer acquirePROCESS_VM_READ. - Patch-enforcement guards:
ensureWindowsProcessTreeCommandLinePatch()repairs an un-applied command-line hunk viagit applyand throws if it cannot; both the relay build and the Electron app rebuild call it, and the relay build additionally repairs and asserts againstPROCESS_VM_READinprocess.cc. - Tests: a new test file asserts the patch post-image contract (class-60 preference, limited-information-only outside the fallback, dynamic
ntdllresolution, 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.mddocuments the reader change and measured access-right reduction;pnpm-lock.yamlrefreshes the patch hash.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| 'config/patches/@[email protected]; run pnpm install.' | ||
| ) | ||
| } | ||
| if (processCc.includes('OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ')) { |
There was a problem hiding this comment.
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.` |
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
ℹ️ 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:
GetProcessCommandLinenow returns empty on any non-class-60 outcome instead of latching back toPROCESS_VM_READPEB reads; the returnedUNICODE_STRINGis bounds-checked against the allocation and the probe size is capped at header + 64 KiB. - Binary-level prebuilt detection:
windowsProcessTreeAddonReadsProcessMemory()keys on the now-absentReadProcessMemoryimport and is wired intoensure-native-runtime.mjs, the relay build artifact check, and a delete-on-sight repair. - Repaired the repair:
git applyis blinded with a non-existentGIT_DIRso the command-line hunk actually applies inside a git work tree; a missing source file now throws. - Value-initialized
ProcessInfo:memoryis 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… 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.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 5bce98a0-475a-49e1-9237-83fca9bbc332
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (16)
config/patches/@[email protected]config/scripts/build-windows-process-tree-relay-addon.mjsconfig/scripts/ensure-native-runtime.mjsconfig/scripts/ensure-native-runtime.test.mjsconfig/scripts/rebuild-native-deps-node-pty.test.mjsconfig/scripts/rebuild-native-deps-test-fixtures.mjsconfig/scripts/rebuild-native-deps-windows-process-tree.test.mjsconfig/scripts/rebuild-native-deps.mjsconfig/scripts/windows-process-tree-gyp-rebuild.mjsconfig/scripts/windows-process-tree-gyp-rebuild.test.mjsdocs/reference/windows-process-enumeration.mdsrc/main/windows/windows-command-line-recovery-health.test.tssrc/main/windows/windows-command-line-recovery-health.tssrc/main/windows/windows-process-table.test.tssrc/main/windows/windows-process-table.tssrc/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 |
There was a problem hiding this comment.
🩺 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 || trueRepository: 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.tsRepository: 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.
There was a problem hiding this comment.
ℹ️ 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:
inspectWindowsProcessTreeAddonnow answersclean/unpatched/missinginstead 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.tsnow refuses a staged relay addon that still importsReadProcessMemoryand falls back to the CIM scan, closing the gap where a bundle and its staged addon redeploy independently. - Host-wide refusal signal:
reportWindowsCommandLineRecoveryHealthwarns 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'stry, so deleting a locked stale addon surfaces the "close running Orca" message rather than a rawEPERMstack. - 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ 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_hashsites now carryf8ea2453…, which I verified equals the LF-normalizedsha256of the on-disk patch — no hand-computed value. - Installer-level regression test:
patched-dependencies-frozen-install.test.mjsrunspnpm install --frozen-lockfile --lockfile-only --ignore-scriptsagainst a scratch copy, so the check keys on the command that actually consumes the hash rather than recomputing the wrong assumption. .gitattributescomment corrected: the-textsetting 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.
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.
There was a problem hiding this comment.
ℹ️ 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_windowsjob'sTest Windows-specific boundariesvitest step listsconfig/scripts/rebuild-native-deps-windows-process-tree.test.mjsandsrc/main/windows/windows-process-tree-command-line-patch.test.ts, so their win32-gated addon assertions — including theReadProcessMemory-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_TESTSinconfig/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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
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.
There was a problem hiding this comment.
ℹ️ 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=inputon the repair'sgit apply: the LF-stored patch's pre-image lines differ from upstream's CRLFprocess_commandline.ccby a CR, so undercore.autocrlf=false(Git's built-in default) the hunk failed to match;-c core.autocrlf=inputnormalizes line endings for that comparison and nothing else, so a genuinely drifted hunk is still rejected. - Faithful CRLF test fixture:
unpatchedWindowsProcessTreeCommandLineSourcenow reconstructs the pre-image as CRLF (what the package actually ships) instead of LF, and the repair test loops overautocrlf=false/truevia a newgitLineEndingEnvhelper that pins git to a tempHOME/USERPROFILE, so the case covers the host that breaks rather than whichever config happens to be present. .gitattributescomment corrected: the patch files are now documented as LF with agit apply-must-force-inputrequirement, 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ 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.mjsnow callsassertWindowsProcessTreeAddonIsPatched()afterrebuild(), so the binary copied into the packagednode_modulesis verifiedclean— a rebuild that reports success but leaves no addon, or an addon that still importsReadProcessMemory, fails loudly rather than shipping the flagged reader. - Fixture emits stand-in addon bytes:
writeFakeElectronRebuildtakes anaddon: 'clean' | 'unpatched' | 'none'mode and emits matching bytes so the assertion'smissingandunpatchedbranches are each exercised end-to-end. - Real-install patch test:
patched-dependencies-frozen-install.test.mjsgained a case that runs a genuinepnpm install --no-frozen-lockfile --ignore-scriptsof the single dependency and asserts the materializedprocess_commandline.cccarries the marker and no longer carriesReadProcessMemory— covering what--lockfile-onlynever could. - Timeout fix: the frozen-install case's 300s spawn budget now reaches the spawn by declaring a matching
ittimeout, sinceconfig/vitest.config.tsotherwise 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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta — a clean base-branch sync. The two prior diagnosability threads remain open and unchanged.
Reviewed changes
- Merged
maininto the branch: a single merge commit (cbc5eecd29) brought main'sperf(windows): stop asking the process table for memory(#18151) andrefactor(process-table): extract the correlation indexes(#18246) into the PR'swindows-process-table.ts. - Memory flag dropped from the table snapshot:
readNativeRowsnow requestsCommandLine | CreationTimeonly; the "Why CommandLine but not Memory" comment and thenever memorytest case came in from main and compose cleanly with the PR's kernel-read addon, which still dropsPROCESS_VM_READfrom the memory reader's own handle. - Snapshot-reader module rename: the
process-table-snapshot→process-table-snapshot-readerimport moved with it; the PR'screateProcessTableSnapshotReadercall site is intact. - Docs: main's
windows-edr-posture.mdrewrite now declares "The memory read is gone" and citesinspectWindowsProcessTreeAddon(); the PR'swindows-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.
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.
There was a problem hiding this comment.
ℹ️ 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.mjsdropped its hand-rolledPATHscan forpnpm.exe/pnpm.cmd;resolvePnpmInvocation()now callsresolvePnpmCliInvocation()(which prefersnpm_execpathwhen set) and falls back toresolveCliCommandfor the bare-vitestcase. This also removes the.cmdliteral thatwindows-cmd-shim-spawn-boundary.test.mjsrejects, andrunProcessSyncstill drives a shim throughcmd.exeitself, so dropping the resolver'sshellfield is safe.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
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.
…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>
…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]>
…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>

The primitive being replaced
MDE incident D flagged Orca for "suspicious memory activity". The addon's
CommandLineflag (src/process_commandline.ccin@vscode/[email protected]) recovered each process's command line by:OpenProcess(…VM_READ)+ReadProcessMemoryacross every pid on a repeating timer is behaviourally identical to a credential dumper. #17866 halves the handle count by dropping the uselessMemoryflag but, as it says itself, leaves the PEB read on the hot path.Windows 8.1 added
NtQueryInformationProcess'sProcessCommandLineInformationclass (0x3C= 60). It returns the same string as aUNICODE_STRINGthe kernel builds, needing onlyPROCESS_QUERY_LIMITED_INFORMATION. Electron 43's floor is Windows 10, so every OS Orca supports has it. The entry point is resolved withGetProcAddressonntdll.dll(no import library), and the buffer size comes from a null-buffer probe answeringSTATUS_INFO_LENGTH_MISMATCH.The same hunk drops
PROCESS_VM_READfromGetProcessMemoryUsageandGetCpuUsage, which acquired it and never read an address space —GetProcessMemoryInfoandGetProcessTimesare satisfied byPROCESS_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:
ClassifyQueryFailuremappedSTATUS_INVALID_INFO_CLASS/NOT_SUPPORTED/NOT_IMPLEMENTEDfrom any one target onto a process-wide, one-way, never-cleared switch back toPROCESS_VM_READplus threeReadProcessMemoryper 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 returningSTATUS_INVALID_INFO_CLASSfor 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 instrumentedntdll.So the fallback is deleted, not guarded.
GetProcessCommandLinereturns false and leaves the command line empty — already a documented, tolerated outcome (WindowsProcessRow.commandis "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_STRINGcrosses that same hookable boundary,Buffer/Lengthare now bounds-checked against the allocation — againstbuffer.size(), notsize, which the second query clobbers — and the probe size is capped at the header plus 64 KiB (Lengthis aUSHORT) so a bogus size cannotbad_allocan entire scan instead of one process.NT_SUCCESSis tested explicitly rather than as an inequality.Access-right reduction, measured in-process
Counted by replacing the loaded
.node's import-address-table entries forOpenProcessandReadProcessMemorywith counting stubs — observed calls from the real binary. Windows 11, 543 processes, unelevated.CommandLinescan0.8.0as vendored)OpenProcesscalls0x0410—PROCESS_VM_READ | PROCESS_QUERY_INFORMATION(×543)0x1000—PROCESS_QUERY_LIMITED_INFORMATION(×543)ReadProcessMemorycallsStronger 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_INFORMATIONimplicitly grantsPROCESS_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
The three the old path could not reach (
GCC.exe,ctfmon.exe,ChsIME.exe) refusedPROCESS_QUERY_INFORMATION | PROCESS_VM_READwithERROR_ACCESS_DENIEDand grantedPROCESS_QUERY_LIMITED_INFORMATION. ~132 SYSTEM/protected processes deny both identically.Targeted string-identity cases, all byte-identical: a 24,087-character
argvwith 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:NoneCommandLineMemory | CommandLineThe 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]publishesbuild/Release/windows_process_tree.nodein the tarball. It is node-addon-api, so it loads under Node and Electron;allowBuildsisfalseand CI installs with--ignore-scripts;ensure-native-runtime.mjs's health check was a barerequire(), 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_modulescurrently carries the upstream prebuilt, withReadProcessMemoryin 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.nodeand 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.mjstreats it as a load failure, which is what triggers a rebuild — andrebuildNodeRuntimeModules()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 repair never worked
git applyrun 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 becausemkTempProject()builds in%TEMP%, outside any repo — where the identical command works.Fixed by blinding git to the repo (
GIT_DIRpointed at a non-existent path;GIT_CEILING_DIRECTORIESdoes not work). Verified inside the repo work tree: repairs correctly, and is idempotent. The test now callsinitGitWorkTree()first, and the fixture writes the real pristine source reconstructed from the patch's own pre-image — verified byte-identical to the upstream file — sogit applyhas genuine bytes to match rather than a placeholder.Also from review
ProcessInfo pinfo{}—memorywas uninitialized stack garbage. Measured before: 538/538 processes reported non-zero working sets with the value458repeated 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:194no longer describesCommandLineas "a PEB read".patchedFile()in the test no longer drops truly-empty context lines; its reconstruction is verified byte-identical togit applyoutput for both files.How the patched addon ships
pnpm-workspace.yaml→patchedDependencies['@vscode/[email protected]'].rebuild-native-deps.mjsrebuilds against Electron's ABI (x64 + arm64) withforce: true;build-windows-process-tree-relay-addon.mjscompiles the relay artifact against Node headers. Verified by reconstructing pristine 0.8.0, applying this patch (all three files clean) and building withnode-gyp rebuild --arch=x64; every measurement above is from that binary.Lockfile: the patch hash appears in three places —
patchedDependencies, the importer'sversion:key, and the snapshot key (patch_hash=…). All three are updated; missing the latter two would break--frozen-lockfile.Conflicts with #17866
git merge-treeshowed zero conflicts at review time. This revision adds an edit tosrc/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=8192here),tsc -p config/tsconfig.tc.cli.json✅oxlint✅ — 5 warnings, all pre-existingreact-hooks/exhaustive-depsinsrc/renderer, none in changed filesconfig/scripts/rebuild-native-deps-node-pty.test.mjs✅ all pass, including the two new repair casesvitest src/main/windows/— 59 passed, 2 failed:windows-host-job.win32.test.ts— fails identically on a stashed tree, genuinely pre-existing.Correction to my earlier claims. I previously reported 4 pre-existing failures in
src/main/windows/and 2 inpackage-electron-runtime-contract.test.mjs. Re-measured on a repairednode_modules: the threewindows-pty-job.win32failures are gone — they were the broken install, exactly as flagged. Thepackage-electron-runtime-contractfailures are environment, not product:Could not resolve package serve-sim, whose symlink in the sharednode_modulespoints into a different agent's worktree. The reviewer's 22/22 pass is correct; my "pre-existing" label was wrong.Risks for a reviewer
ntdllrefuses 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.pnpm testthis self-heals (ensure-native-runtime.mjsrepairs and rebuilds first); under barenpx vitestin a worktree whose sharednode_modulespredates this patch, it fails. That is the intended signal, and it matches the existingisPtyJobOwnershipAvailable()precedent, but it will surface for anyone on a stale install.node_modules. Consistent withapplyWindowsProcessTreeBuildFixes(), but in a multi-worktree setup that store is shared.winternl.h, so the class travels as aULONGandUNICODE_STRINGis read from a raw buffer — now bounds-checked and size-capped.gitmust be onPATHfor the repair; failure is a loud throw, not a silent unpatched build.node_modulesother worktrees share.P0:
pnpm install --frozen-lockfilewas failing on this branchCommit
0b0c9d4b7e. This broke every CI job and the release build (the branch's ownpackage (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 onmain— and.gitattributespins/config/patches/*.patch -textprecisely so checkout cannot convert it, so those bytes reached every runner on every platform. And pnpm hashes a patch LF-normalized, so the rawsha256of a CRLF file is a number pnpm never produces:sha256(patchBytes)322965470c05f63d8527f7d8e892ee26ee444136b66b57fd64c362a9f2ff05d1f8ea245391c94da5770045aeea01fa6de466c2199c6ef46b5b769b398aa9823eThe 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/:ERR_PNPM_LOCKFILE_CONFIG_MISMATCH, exit 1git archivefrom the commit to simulate a CI checkout → exit 0The 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. Soconfig/scripts/patched-dependencies-frozen-install.test.mjsrunspnpm install --frozen-lockfile --lockfile-only --ignore-scriptsagainst a copy of the real files and asserts exit 0 — verified by deletion: restoring the shipped hash fails it with the exactERR_PNPM_LOCKFILE_CONFIG_MISMATCHfrom the failed CI job.Also corrected the
.gitattributescomment claiming pnpm hashes patches byte-for-byte — the claim that produced the wrong hash twice. The-textsetting stays, so a patch reads and diffs identically everywhere.Follow-up 1: normalizing the patch broke the
git applyrepairCommit
9104d51582. The LF normalization above and thegit applyrepair 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:-lines+linessrc/process.ccsrc/process_commandline.ccbinding.gypSo 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-c core.autocrlf=inputtrueinputfalsefalseis Git's own built-in default and what "checkout as-is" selects in the Git for Windows installer. (On this box thetruethat hid it comes from the installer's system gitconfig atC:/Program Files/Git/etc/gitconfig— nothing in the repo.) There the repair throws,ensureWindowsProcessTreeCommandLinePatchreports "still reads the PEB, and repairing it … failed",isWindowsNativeLockErrordoes not match that text, andpnpm installfails with no path forward. That repair path is new in this PR, so this is introduced here, not inherited.Fix: force
-c core.autocrlf=inputon the repair'sgit apply. Chosen over--ignore-whitespace— both fix every cell and both leave the applied file fully LF, butinputrelaxes 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.mjsbuilt 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 tempHOMEgitconfig (the repair blinds git to the repo withGIT_DIR, so it reads global config, which outranks the system file).Verified by deletion, both directions:
-c core.autocrlf=inputautocrlf=falsecaseBoth halves are load-bearing: the flag fixes the defect, the CRLF fixture is what lets the case see it.
autocrlf=truepasses 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 installapplies the LF patch to the CRLF tarball sources without complaint and materializes them as LF, marker present,ReadProcessMemoryabsent. pnpm uses its own applier, so the primary install path was never affected — only thegit applyfallback 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.mjsasserts 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.mjsnow assertscleanon it afterrebuild().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 fakerebuild()now emits stand-in bytes and takesaddon: 'clean' | 'unpatched' | 'none'; verified by deletion — with the assertion removed, both new cases pass.--lockfile-onlynever 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 materializedsrc/process_commandline.cccarries the marker and no longer carriesReadProcessMemory. ~1.5s for the pair.One correction to the brief I was given: that case does not catch the
git applybreakage from Follow-up 1. Measured — with-c core.autocrlf=inputremoved it passes cleanly, becausepnpm installuses 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_000to the spawn whileconfig/vitest.config.tscapped 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-259and rewrites around. Expect a hand-reconciled conflict onloadWindowsProcessTreeand 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 installwhile Orca is running aborted with a raw EPERM stack. The stale-binary guard inrebuild-native-deps.mjssat outside thetrywhose catch classifies Windows file locks and prints "Close running Orca/Electron/dev processes for this worktree". Reproduced empirically first:rmSyncagainst a loaded (memory-mapped) addon throwsEPERM, Permission denied,force: truedoes not help (it only swallows ENOENT), and a cold copy of the same file deletes fine. Moving the guard inside thetryis 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 rawsyscall: '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 theCommandLineflag actually being requested so a future identity-only reader cannot trip it. The suite'sSELFfixture 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.
loadWindowsProcessTreechecks./windows-process-tree.nodebeside 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 andchild_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 intobeforeAll. 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; frombeforeAllthe seven text cases pass and only the three addon cases go.Also fixed:
ensure-native-runtime.test.mjsstaged only the script, not thewindows-process-tree-gyp-rebuild.mjsimport this PR added, so every case in that suite died withERR_MODULE_NOT_FOUND. Now usescopyScriptWithLocalModules, 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_READplus anNtQueryInformationProcessfor the PEB address), anddocs/reference/windows-process-enumeration.md:62/:179-180— do not exist on this branch. They are entirely #17866's to own; grepping this tree forPEBreturns 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 newstagedRelayAddonIsUnpatched()helper andFLAGGED_ADDON_IMPORTconstant afterRELAY_ADDON_FILENAME; the relay branch ofloadWindowsProcessTree()restructured from a ternary into early returns; a 3-line health call added inside thegetAllProcessescallback right after the self-presence guard;__setWindowsProcessTreeRequireForTestssignature widened toNativeRequire.docs/reference/windows-process-enumeration.md— thewindowsProcessTreeAddonReadsProcessMemory()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.mjsandbuild-windows-process-tree-relay-addon.mjs(import plus one call each),rebuild-native-deps.mjs(the win32 block moved inside thetry)..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 0oxlint --config .oxlintrc.json src config tests✅ exit 0 (same 5 pre-existingreact-hooks/exhaustive-depswarnings insrc/renderer, none in changed files);check-max-lines-ratchet.mjs✅;oxfmt --check✅ on the touched fileswindows-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.mjspnpm-lock.yamldiff is exactly the three patch-hash lines.Failures I did not fix, stated plainly. This worktree borrows
node_modulesfrom another worktree on a different branch (pnpm installcannot run in long paths on this box —LongPathsEnabledis 0), so its@vscode/windows-process-treeis built from that branch's unpatched source and itsnode-ptyis likewise foreign. Each was confirmed identical on the pristine PR head, or onorigin/main:windows-pty-job.win32.test.ts(3) andwindows-host-job.win32.test.ts(1) — borrowednode-ptyreports no job ownership. Identical on the pristine head.ensure-native-runtime.test.mjs(2) — not the borrowednode_modules, which is what I first said. The cause is inside the%TEMP%fixture:conpty.dllis never staged for these two cases. On Windows the only cases that run are the two that skipwritePatchedNodePtyBuildArtifacts; the ones that call it areskipIf(win32). Verified by reading the fixture and by the failure naming a path under%TEMP%, and confirmed failing onorigin/mainwith 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.mjsas 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 borrowednode_modulescarrying main's patch, and that thedumpbinresult 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
ReadProcessMemorybyte check and the live command-line recovery scan. The addon was confirmed to be a build of this PR's patched source — its stagedsrc/process_commandline.ccis byte-identical to the current patch's post-image modulo line endings — and it is clean ofReadProcessMemorywhile carryingNtQueryInformationProcess. Package resolution was shadowed for the run and the shadows removed afterwards; the patch touches onlybinding.gypand the two.ccfiles, 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
aa601a1a38closes a lane gap found alongside this work:src/main/windows/windows-process-tree-command-line-patch.test.tsandconfig/scripts/rebuild-native-deps-windows-process-tree.test.mjsran in no CI lane — the onewindows-2022job runs a curated file list, and the full suite runs only on ubuntu, where both self-skip. Both are now in theTest Windows-specific boundariesstep in.github/workflows/pr.ymland inWINDOWS_PACKAGE_TESTSinconfig/scripts/pr-code-change-scope.mjs, with a comment recording that the step invokesvitestdirectly rather than throughpnpm test, so the addon assertions hold only onceinstall-node-dependencieshas rebuilt natives.classifyPrJobsreturnspackage_windows: truefor both paths.Worth noting that this lane could not have worked before the P0 above:
install-node-dependenciesrunspnpm 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.mjsappears only in.github/workflows/dev-channel-win-build.yml:240-241, never inrelease-cut.yml, andsrc/shared/relay-artifacts.ts:57marks the artifactoptional: trueso its absence is not a build failure. Confirmed by extracting the realorca-windows-setup.exefrom v1.4.197 (NSIS →$PLUGINSDIR/app-64.7z):resources\relay\win32-x64\andwin32-arm64\contain the seven JS artifacts and.version, and no.node. Same forOrca-1.4.197-mac.zip.This splits the PR's value unevenly, and the description above did not say so:
@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.)Correction: the stale-addon scenario could not be constructed
An earlier revision of this section claimed a
.nodestaged by a dev-channel client survives a later redeploy from a release client, becausepromoteWindowsRelayUploadStageCommand(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), andbuild-relay.mjs:219-236hashes 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-replaceCopy-Itemonly merges within a single hash's directory, where it repairs a torn install (guarded byRELAY_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-Itemonly 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.
loadWindowsProcessTreetries the npm package first, before the staged-addon branch:requireNativeiscreateRequire(__filename), and on a relay__filenameis<home>/.orca-relay/<version>/relay.js. Node then walks upward —<version>/node_modules(which exists;installNativeDepsnpm-installs into it),~/.orca-relay/node_modules,~/node_modules, and up. A@vscode/windows-process-treeanywhere on that chain is loaded unguarded, and the published prebuilt is the unpatched node-addon-api build that opens every process withPROCESS_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_modulesor~/.orca-relay/node_moduleson a Windows SSH host — the "rannpm installin 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.