Skip to content

fix(hooks): register the Claude hook script directly on Windows (#18875) - #18905

Merged
OrcaWin merged 5 commits into
mainfrom
OrcaWin/windows-injected-claude-code-hook-powershell.exe
Sep 6, 2026
Merged

OrcaWin merged 5 commits into
mainfrom
OrcaWin/windows-injected-claude-code-hook-powershell.exe

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 5, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​370 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​355
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​100 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​92

Fixes #18875.

Reproduced first

Both halves of the report reproduce on Windows 11 / Git Bash, invoking the hook exactly as Claude Code does (printf payload | bash -c -l "<command>"), with the wrapper as installed in ~/.claude/settings.json (11 events, timeout: 10).

1. Per-event cost — ORCA_PANE_KEY unset, i.e. the non-Orca session case that was 70% of the reporter's ~6 900 fires:

shape idle median (n=12) 10-way concurrent (n=40) p95
baseline bash -l -c true 177 ms — —
before — powershell -NoProfile -EncodedCommand 471 ms 656 ms 696 ms
after — script path || echo {} 213 ms 296 ms 337 ms

PowerShell start-up is the entire difference, and it is paid before the .cmd can reach its first ORCA_PANE_KEY guard — so a session outside Orca pays it to do nothing.

2. The freeze — a Node harness that spawns the hook and reads stdout to EOF, as Claude Code does, then kills the hook at 150 ms the way the timeout kill does. The powershell.exe -EncodedCommand grandchild survives the kill and still holds the inherited stdout handle: EOF arrived 352 ms after the kill, only once that orphan exited on its own. So the orphan, not the killed hook, owns EOF. When it never exits — msys2 creates children CREATE_SUSPENDED and resumes them after, so a kill landing in that window strands one — EOF never arrives and the reader blocks forever. That is the reported frozen session.

The change

Register the managed script path itself, with || echo {} for the neutral-JSON-when-missing contract (#14818):

C:/Users/alice/.orca/agent-hooks/claude-hook.cmd || echo {}

bash -> powershell -> cmd -> curl becomes bash -> cmd -> curl, which is the shorten-the-interpreter-chain doctrine of #15520/#15595. The encoded launcher stays as the fallback for profile paths the shells cannot carry bare (space, %, ^, &, non-ASCII) and for hosts where Git Bash is not resolvable, since PowerShell 5.1 rejects || (measured: parse error). Every other agent's hook, and the remote/SSH path, are untouched.

Verdicts on the report's suggestions

  • Linux support #1 invoke the .cmd directly — adopted, but not as written. cmd.exe /d /c <path> is broken under Claude Code's real host: MSYS rewrites the /c, and the invocation fails ('laude-hook.cmd' is not recognized). AGENTS.md forbids that shape from a Git Bash pane for exactly this reason. The bare path works in Git Bash and cmd.exe, and is already the prior art in wrapRuntimeHomeHookCommand. A native hook client was rejected as a much larger change that would add its own binary to the profile.
  • Fix Ctrl+Backspace not deleting word in terminal #2 raise the timeout — rejected. The orphan survives the kill regardless, so a longer timeout only changes how often the kill fires; the fast path already puts the hook ~30x under the 10 s budget. Raising it would make a genuinely stuck hook block each tool call three times longer, and managed-hook-timeout.test.ts pins the value across every managed agent.
  • Add Shift+Enter to insert newline in terminal #3 register per-session / non-global — rejected. Claude Code has no env or session condition on hooks, settings scopes merge rather than override, and --settings is per-invocation argv Orca does not control. A per-workspace settings.local.json would drop an untracked file into every worktree and folder workspace, still fire for non-Orca sessions there, and leave the in-Orca cost untouched.
  • Add Ctrl+Click to open links in terminal #4 early-exit before starting anything — adopted in substance. The .cmd already prints {} and exits on its three env guards before spawning curl; that is the ~36 ms. The expensive thing was the interpreter that ran before those guards, and it is now gone. A wrapper-level env test cannot be one string valid in both hosts without adding an interpreter back.

Why not just reuse the POSIX shape?

The obvious smaller change is to set usesWindowsCompatLauncher: false for Claude, deleting getWindowsManagedLifecycleHook and reusing wrapRuntimeHomeHookCommand the way OpenClaude does. I generated that exact string (2165 chars) and ran it with a piped payload, ORCA_* unset:

host result
Git Bash (bash -c) {}, rc 0 — the nicest shape under bash: stdin drained, silent stderr, encoded fallback only for an unsafe $HOME
cmd.exe /d /c -z was unexpected at this time., rc 1, nothing on stdout

It is bash syntax, so it fails the cmd.exe leg deterministically. That leg exists because compat consumers import ~/.claude/settings.json and run command through their own launcher — #14825 defect 1 was precisely a shape that worked in only one host. Taking that route would mean deleting a #14825 regression contract and declaring cmd-hosted consumers unsupported for the Claude entry. It would also key on $HOME rather than the USERPROFILE Orca installed under, so a user with a custom HOME would get a silent {} forever with getStatus unable to see it.

The shipped shape is the one polyglot that execs the .cmd with no interpreter hop under both hosts, keeps neutral JSON and exit 0 when the script is gone under both, and spells no switch MSYS can rewrite.

Verification

  • Delivery contract proven end-to-end through both hosts (cmd.exe and Git Bash) against a live listener: exit 0, stdout exactly {}, stderr empty, exactly one POST, byte-exact 4 KB non-ASCII payload, paneKey and token intact.
  • New windows-direct-cmd-hook-command.test.ts: shape unit tests, live neutral-JSON legs (script present and absent) in both hosts, and a guard that no stray nul file is created — 2>nul writes a literal file named nul into the cwd under MSYS, so the missing-script line is deliberately left unredirected.
  • hook-service.test.ts: asserts the bare shape on all 11 events, both fallback conditions, createManagedCommandMatcher recognition of both shapes, and that a previously installed encoded launcher is swept on reinstall while user hooks survive.
  • pnpm tc:node clean, oxlint clean on all touched files.

Tradeoffs, stated

  • Portability. POSIX resolves the profile at runtime (${HOME-}, STA-3348); Windows now registers an absolute path, because no single token expands in both Git Bash and cmd.exe. This matches what Codex, Grok, Devin and Antigravity already do on Windows. A moved profile is caught by getStatus's exact match and rewritten on the next install pass, and || echo {} keeps a stale entry neutral in the meantime. The POSIX assertion is unchanged.
  • EDR. What is measured here is latency and hop count, nothing else. One powershell.exe -EncodedCommand per hook event — a first-class Defender alert title — leaves the default tree; cmd.exe remains, spelled by MSYS's own .cmd spawn rather than by us, carrying an absolute path and two literal tokens with no caret escaping, no encoding and no free text. No EDR verdict on either tree was measured, and windows-edr-posture.md is updated to say exactly that.
  • Known corner. If Orca resolves Git Bash but Claude Code does not, it hosts hooks in PowerShell, where || is a parse error. Both resolvers scan the same Git install, so this is unlikely; there is no mitigation in this change.
  • A regression test for the orphan/EOF race was written and then dropped: it passed on the old shape too (the orphan exits on its own in ~350 ms), so it guarded nothing. The durable guard is the static assertion that no interpreter appears in the registered command.

Note for reviewers on Windows

Three pre-existing test failures on a box with a cmd.exe AutoRun configured (HKCU\Software\Microsoft\Command Processor\AutoRun) are not caused by this change — they fail identically at HEAD, verified by checking out the unmodified files and re-running. AutoRun output contaminates hook stdout on the old shape in both hosts, and on the new shape only under Git Bash. Separately, three installer-utils.test.ts symlink tests fail with EPERM without Developer Mode.

Review round (Fable adversarial review + fixes)

The design was reviewed against the committed diff. Verdict: no blockers, no macOS/Linux regression path. Everything it raised is actioned below.

Build regression caught and fixed (104f1ee63b). pnpm tc runs three projects and I had only checked node. config/tsconfig.cli.json enumerates its files explicitly, so both new imports failed tc:cli with TS6307 — CI would have gone red. Added windows-direct-cmd-hook-command.ts and git-bash.ts to its include list. All three projects clean.

Cross-platform — nothing found, verified rather than assumed.

  • src/main/git-bash.ts imports only node:fs, node:path and a shared constant; no electron, no spawn, no module-load side effects. It was already in the relay graph before this PR, and the renderer never imports src/main/claude/*.
  • hook-settings.ts returns on the non-win32 branch before options is read, so getManagedLifecycleHook output is byte-identical off Windows. getRemoteManagedCommand / installRemote untouched.
  • Vitest does execute a skipped describe's factory, so the new test file's top-level body runs on Linux: findGitBash() throws and is caught → null, WINDOWS_CMD_SAFE_PATH.test('/tmp/...') is false, everything registers skipped. No collection-time throw.

Two of my earlier premises were wrong, and are corrected here.

  1. The old encoded shape was not immune to a broken cmd.exe AutoRun — it returned exit 1 on that box, which Claude Code surfaces as a per-event hook error. The new shape returns exit 0 with {}{}. Neither is clean; the new one is arguably quieter. Full matrix, measured:
box state old (bash / cmd) new (bash / cmd)
healthy, script present rc0 {} / rc0 {} rc0 {} / rc0 {}
healthy, script missing rc0 {} / rc0 {} rc0 {} / rc0 {}
broken AutoRun, script present rc1 {} / rc1 {} rc0 {}{} / rc0 {}
broken AutoRun, script missing rc0 {} / rc0 {} rc0 {} / rc0 {}

On a healthy box the two shapes are identical in every cell. The comments claiming || "never fires when the script ran" are corrected — it also fires when cmd.exe itself exits non-zero.

  1. The suite I called green was host-dependent. windows-hook-payload-delivery.test.ts and managed-hook-stdin-lifecycle.test.ts fail at HEAD on any box with a cmd.exe AutoRun configured: the tests redirect USERPROFILE, the AutoRun target vanishes, and MSYS spawns a .cmd without /d so AutoRun runs and lands on the hook's stderr. Both suites now seed an empty AutoRun target (including under the deliberately-absent profile), so they measure the launcher rather than the developer's shell configuration. This makes windows-hook-payload-delivery.test.ts green where it was red at origin/main.

Also actioned:

  • The direct shape is now gated on a drive-letter path. WINDOWS_CMD_SAFE_PATH admits a UNC profile, and //server/share/... is not a command cmd.exe reliably starts — those fall back to the encoded launcher.
  • New test for the contract that replaced runtime %USERPROFILE% resolution (STA-3348): a stale absolute path reports not_installed and is rewritten on install. That contract was previously asserted only in prose.
  • managed-hook-stdin-lifecycle's "missing managed script" case no longer exercises the fallback for the direct shape (an absolute path ignores a redirected profile). Documented in place, with a pointer to where it is covered live.
  • Launcher comments trimmed per AGENTS.md; the measurements live in windows-edr-posture.md.
  • Memoization: deliberately not doing it. isGitBashAvailable() measures 143 µs, and getStatus() computes expectedHook once outside the 11-event loop. Call sites are startup install, the settings toggle, paired-client reconciliation, and orca agent hooks status — no timer, no per-pane, no per-hook-event path (hooks run as a .cmd and never re-enter this code). A module-level cache would also be wrong, since Git Bash can be installed while Orca is running.

One standing assumption, recorded in the doc because it is not measured. || parses in Git Bash, cmd.exe and pwsh, but not Windows PowerShell 5.1. Claude Code is a Git Bash host on native Windows. What is unverified is which host a compat consumer uses — cursor-agent and Devin import ~/.claude/settings.json and run command through their own launcher. If one of them hosts hook strings in PowerShell 5.1, its imported Claude events would fail closed. The encoded launcher had no such assumption. windows-edr-posture.md now says so, and says to measure before widening this shape to another agent.

Regression evidence

Full src/main/agent-hooks + src/main/claude run, branch vs origin/main on the same box:

failing files failing tests total
origin/main 13 23 1431
this branch 12 21 1442

The branch's failing set is a strict subset of main's. The remaining 12 are environmental and unrelated (symlink EPERM without Developer Mode, real-CLI/real-binary integration, and one antigravity stdin assertion), all failing identically at origin/main.

Two defects CI caught that local runs could not

Both were found only after the change was pushed, and both are in the diff.

  1. The new Windows-gated test was registered in no CI lane. win32-test-lane-registration enforces that every Windows-gated spec appears in two places: WINDOWS_PACKAGE_TESTS in config/scripts/pr-code-change-scope.mjs (decides whether package_windows runs for a diff) and the vitest argv in .github/workflows/pr.yml (decides whether the file runs once that job starts). Without both, the file self-skips on ubuntu and reports success — so the live dual-host coverage added here would have run on no machine at all.

  2. Registering it then subjected it to a second guard. windows-lane-tree-removal-boundary scans exactly the specs in that lane and rejects raw recursive rm: cmd.exe and bash have just exited inside the temp tree, and rmSync(..., { recursive: true }) throws EPERM on Windows while their handles drain, turning a spec whose assertions all passed into a lane failure. Now uses removeTreeSync, which carries the repo's retry policy.

The root cause of missing both was scoping local runs to where the code changed rather than where the repo enforces rules about it. The structural guards under config/scripts and src/shared now pass locally too.

Rebased onto 5238a4d576 to pick up #18955, which fixed an unrelated repo-wide breakage (artifact share fixtures expired at the 2026-09-06 UTC calendar rollover and reddened three shards across multiple PRs). Full CI is green on the rebased head: all 8 shards, verify, typecheck, static analysis, package, package (windows), managed hooks on Node 18, and every contract job.

@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 8c261557-d759-4993-9288-e15862b3a8ca

📥 Commits

Reviewing files that changed from the base of the PR and between b5aea263cd378b0cd4b2e1da3605265fd4bbb094 and 808336d.

📒 Files selected for processing (1)
  • .github/workflows/pr.yml

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


📝 Walkthrough

Walkthrough

The change adds direct Windows hook execution for cmd-safe drive-letter paths. Hook settings select this command when Git Bash is available and retain the encoded PowerShell launcher for unsupported paths or environments. Tests cover command generation, shell execution, installation, fallback behavior, AutoRun isolation, and reinstall handling. Documentation records the launcher flow and compatibility conditions.

Merge Risk: 🟡 Moderate · up to 80833

Windows Claude hooks now use a direct managed script path for supported installations, but managed-script failures may be hidden as successful neutral responses, and valid UNC-based Windows test environments may not exercise the intended fallback reliably. These concerns should be resolved before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 8 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address issue #18875 by removing the unnecessary PowerShell launcher from the normal Windows Claude hook path, preserving neutral JSON behavior, supporting Git Bash and cmd.exe, retaining …
Out of Scope Changes check ✅ Passed The documentation, tests, build configuration, and workflow updates directly support the Windows hook change and its verification. No unrelated production changes are evident.
Title check ✅ Passed The title clearly and concisely describes the main change: direct registration of the Claude hook script on Windows.
Description check ✅ Passed The description is detailed and relevant. It explains the problem, implementation, fallback behavior, compatibility risks, linked issue, testing, performance measurements, and regression evidence. It …
Full details: Docstring Coverage

Explanation

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

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: cd0d6e42-6847-4d1a-a4ac-c4efe6ea02ea

📥 Commits

Reviewing files that changed from the base of the PR and between 51eed5a and 070b739.

📒 Files selected for processing (7)
  • docs/reference/windows-edr-posture.md
  • src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts
  • src/main/agent-hooks/windows-direct-cmd-hook-command.ts
  • src/main/agent-hooks/windows-hook-payload-delivery.test.ts
  • src/main/agent-hooks/windows-powershell-hook-launcher.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-settings.ts

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

// this shape on Git Bash being resolvable. The missing-script line stays on stderr
// unredirected: `2>nul` writes a literal `nul` file into the user's repo under MSYS, and
// no other sink parses in both hosts (measured).
return `${invocation} || echo {}`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve nonzero status from an existing managed hook script.

In both cmd.exe and Git Bash, || echo {} runs for every nonzero script exit. An existing .cmd script that exits with 1 therefore outputs {} and returns 0. Select the existing encoded PowerShell launcher for this path. It checks Test-Path, emits {} only when the script is unavailable, and preserves $LASTEXITCODE for existing scripts. Add a regression test for both hosts.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This PR replaces the Windows Claude lifecycle hook's powershell.exe -EncodedCommand launcher with the managed .cmd path itself (<path> || echo {}), keeping the encoded launcher as a fallback for non-cmd-safe profile paths and hosts where Git Bash is not resolvable. Reviewed all 7 files end to end.

  • New wrapWindowsDirectCmdHookCommand — gates on WINDOWS_CMD_SAFE_PATH, emits a forward-slash path plus || echo {} for the neutral-JSON-when-missing contract, with no interpreter spelled (so nothing MSYS can rewrite).
  • getWindowsManagedLifecycleHook rework — picks the direct shape only when Git Bash is resolvable and the path is cmd-safe, else falls back to the encoded launcher; getManagedLifecycleHook threads an injectable gitBashAvailable option for tests.
  • usesWindowsPowerShellLauncher → usesWindowsCompatLauncher — accurate rename; no dangling references remain.
  • Migration coverage — a reinstall sweeps a previously installed encoded launcher (both shapes are matched by createManagedCommandMatcher) while preserving user hooks; startup reconciliation runs install(), so upgraded profiles migrate automatically.
  • Tests — unit shape tests, live neutral-JSON legs through both cmd.exe and Git Bash, a no-stray-nul-file guard, and a payload-delivery regression assertion that no interpreter is reintroduced in front of a cmd-safe script. All assertions are exact (not tautological) and would fail if the interpreter chain regressed.

The acknowledged residual corner — Orca resolving Git Bash while Claude Code hosts hooks in PowerShell, where || is a 5.1 parse error — is documented with no mitigation, but both resolvers scan the same Git install, so it reads as a genuine low-probability tradeoff rather than a gap.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This follow-up addresses the prior review round: the direct Windows Claude hook launcher gained a drive-letter gate so UNC profiles fall back to the encoded launcher, the CLI tsconfig build break was fixed, the Windows test suites were made robust to a box's cmd.exe AutoRun, and the replaced STA-3348 stale-path contract gained a live test.

  • Fixed the CLI tsconfig build break — listed windows-direct-cmd-hook-command.ts and git-bash.ts in config/tsconfig.cli.json, so tc:cli no longer fails with TS6307.
  • Gated the direct shape on a drive-letter path — WINDOWS_DRIVE_LETTER_PATH rejects UNC profiles that WINDOWS_CMD_SAFE_PATH would otherwise admit, keeping them on the encoded launcher.
  • Corrected the || semantics comment — it now documents that || fires on any nonzero exit (including a failing AutoRun), accurate for a managed .cmd that always exit /b 0.
  • Made the Windows suites AutoRun-proof — seedCmdAutoRunTarget seeds an empty %USERPROFILE%\.cmd_aliases.cmd so the tests measure the launcher rather than the developer's shell configuration.
  • Added a live stale-path contract test — a stale absolute path reports not_installed and is rewritten on install, carrying the STA-3348 contract that runtime %USERPROFILE% resolution used to provide.
  • Expanded the EDR doc — UNC fallback, the measured PowerShell 5.1 || parse error, and the unverified compat-consumer host are now stated plainly.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 36a88cb3-2945-493f-996e-3a49598ec4b1

📥 Commits

Reviewing files that changed from the base of the PR and between 070b739 and 6209d0bc443a8500e2566dad76825f9ded35eed5.

📒 Files selected for processing (8)
  • config/tsconfig.cli.json
  • docs/reference/windows-edr-posture.md
  • src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
  • src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts
  • src/main/agent-hooks/windows-direct-cmd-hook-command.ts
  • src/main/agent-hooks/windows-hook-payload-delivery.test.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-settings.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts
  • docs/reference/windows-edr-posture.md
  • src/main/claude/hook-settings.ts

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

Comment on lines +538 to +541
if (!WINDOWS_CMD_SAFE_PATH.test(scriptPath)) {
vi.unstubAllEnvs()
rmSync(tmpHome, { recursive: true, force: true })
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep Windows test guards aligned with direct command selection.

Production selects the direct command only for cmd-safe drive-letter paths. Both tests currently guard only on WINDOWS_CMD_SAFE_PATH, so a safe UNC path can enter a direct-command assertion even though production selects the encoded fallback.

  • src/main/claude/hook-service.test.ts#L538-L541: include the drive-letter condition before expecting the direct command.
  • src/main/agent-hooks/windows-hook-payload-delivery.test.ts#L180-L184: include the same condition before rejecting the PowerShell fallback.
📍 Affects 2 files
  • src/main/claude/hook-service.test.ts#L538-L541 (this comment)
  • src/main/agent-hooks/windows-hook-payload-delivery.test.ts#L180-L184

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This delta registers the previously-added windows-direct-cmd-hook-command.test.ts in the Windows CI lane, closing the gap where the new suite was running on no machine.

  • Registered the new test in both Windows-lane lists — added to the Test Windows-specific boundaries vitest argv in .github/workflows/pr.yml and to WINDOWS_PACKAGE_TESTS in config/scripts/pr-code-change-scope.mjs, so the file actually executes on windows-2022 and a change to it triggers the package_windows job.

The file is genuinely Windows-gated (describe.skipIf(process.platform !== 'win32') for its live legs), so the win32-test-lane-registration.test.mjs ratchet now passes (verified locally: 31/31), while its cross-platform shape unit tests still run on ubuntu.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

This delta swaps the raw rmSync teardown in the new windows-direct-cmd-hook-command.test.ts for the shared removeTreeSync retrying helper, so the just-exited cmd.exe/bash children in the temp tree no longer surface an EPERM while their handles drain on Windows.

  • Reused the retrying tree-removal helper — rmSync(dir, { recursive: true, force: true }) became removeTreeSync(dir) (the now-unused rmSync import dropped), matching the sibling windows-hook-payload-delivery.test.ts and satisfying the windows-lane-tree-removal-boundary.test.ts ratchet that flags raw rmSync in Windows-lane teardowns.

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

Orca Worker added 5 commits September 5, 2026 17:41
The Windows Claude Code lifecycle hook was registered as
`powershell.exe -NoProfile -EncodedCommand <...>` whose entire decoded payload
was a `Test-Path` and a call to `~/.orca/agent-hooks/claude-hook.cmd`. Every
hook event paid a full PowerShell start-up to reach a script that exits at its
first `ORCA_PANE_KEY` guard, so sessions outside Orca paid it to do nothing.

Register the script path itself instead, with `|| echo {}` for the
neutral-JSON-when-missing contract (#14818). Measured on Windows 11, invoked as
Claude Code invokes it (`printf payload | bash -c -l "<command>"`):

  idle (n=12)          baseline 177ms | before 471ms | after 213ms
  10-way conc (n=40)            --    | before 656ms | after 296ms
  p95 under load                --    | before 696ms | after 337ms

It also drops an interpreter from the chain the hook's timeout kill must tear
down. Killing the hook does not kill its PowerShell grandchild, which still
holds the stdout handle the agent reads to EOF -- measured, EOF arrived 352ms
AFTER the kill, when the orphan exited by itself. msys2 creates children
suspended and resumes them after, so a kill landing in that window strands one
that never exits and EOF never comes; that is the reported frozen session.

The encoded launcher stays as the fallback for profile paths the shells cannot
carry bare (space, `%`, `^`, `&`, non-ASCII) and for hosts where Git Bash is not
resolvable, because PowerShell 5.1 rejects `||`. Every other agent's hook is
untouched, as is the remote/SSH path.

Not adopted from the report: `cmd.exe /d /c <path>` (MSYS rewrites the `/c`
under Git Bash -- measured, the invocation fails), and raising the 10s timeout
(the orphan survives the kill regardless; the fast path puts the hook 30x under
the budget so the kill effectively stops firing).
…oject

config/tsconfig.cli.json enumerates its files explicitly, so the two new
imports reached by src/main/claude/hook-settings.ts failed tc:cli with TS6307.
src/main/git-bash.ts pulls in only node:fs, node:path and a shared constant,
so it adds nothing heavy to the CLI project.
- Make the Windows hook suites host-independent. A box with a cmd.exe AutoRun
  (HKCU\...\Command Processor\AutoRun) failed them at HEAD too: the tests
  redirect USERPROFILE, the AutoRun target vanishes, and MSYS spawns a .cmd
  without /d so AutoRun runs and lands on the hook's stderr. Seed an empty
  target, including under the deliberately-absent profile.
- Note in managed-hook-stdin-lifecycle why the "missing managed script" case no
  longer exercises the fallback for the direct shape (it carries an absolute
  path, so a redirected profile changes nothing); that path is covered live in
  windows-direct-cmd-hook-command.test.ts.
- Keep the direct shape off UNC profiles: WINDOWS_CMD_SAFE_PATH admits them, but
  //server/share/... is not a command cmd.exe reliably starts.
- Correct the comments: `|| echo {}` also fires when cmd.exe itself exits
  non-zero (failing AutoRun), printing {} twice. The encoded launcher exited 1
  on that same box, so neither shape is clean there.
- Test the contract that replaced runtime %USERPROFILE% resolution (STA-3348): a
  stale absolute path reports not_installed and is rewritten on install.
- Record the standing unmeasured assumption in windows-edr-posture.md: `||` does
  not parse in Windows PowerShell 5.1, so a compat consumer that hosts hook
  strings there would fail closed. Measure before widening to another agent.
- Trim the launcher comments per AGENTS.md; the numbers live in the doc.
win32-test-lane-registration guards against exactly this: a Windows-gated file
that self-skips on ubuntu and reports success, so it runs on no machine. The new
windows-direct-cmd-hook-command.test.ts needs both entries — WINDOWS_PACKAGE_TESTS
decides whether package_windows runs for a diff, and the workflow argv decides
whether the file runs once that job started.
windows-lane-tree-removal-boundary scans exactly the specs in the Windows CI
lane, so registering windows-direct-cmd-hook-command.test.ts subjected it to the
rule: cmd.exe and bash have just exited in that tree, and a raw recursive rm
throws EPERM on Windows while their handles drain, turning a green spec into a
lane failure. Use removeTreeSync, which carries the repo's maxRetries policy.
@OrcaWin
OrcaWin force-pushed the OrcaWin/windows-injected-claude-code-hook-powershell.exe branch from b5aea26 to 808336d Compare September 6, 2026 00:42
@OrcaWin
OrcaWin merged commit b6ca8da into main Sep 6, 2026
27 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#18875) (stablyai#18905)

* fix(hooks): register the Claude hook script directly on Windows (stablyai#18875)

The Windows Claude Code lifecycle hook was registered as
`powershell.exe -NoProfile -EncodedCommand <...>` whose entire decoded payload
was a `Test-Path` and a call to `~/.orca/agent-hooks/claude-hook.cmd`. Every
hook event paid a full PowerShell start-up to reach a script that exits at its
first `ORCA_PANE_KEY` guard, so sessions outside Orca paid it to do nothing.

Register the script path itself instead, with `|| echo {}` for the
neutral-JSON-when-missing contract (stablyai#14818). Measured on Windows 11, invoked as
Claude Code invokes it (`printf payload | bash -c -l "<command>"`):

  idle (n=12)          baseline 177ms | before 471ms | after 213ms
  10-way conc (n=40)            --    | before 656ms | after 296ms
  p95 under load                --    | before 696ms | after 337ms

It also drops an interpreter from the chain the hook's timeout kill must tear
down. Killing the hook does not kill its PowerShell grandchild, which still
holds the stdout handle the agent reads to EOF -- measured, EOF arrived 352ms
AFTER the kill, when the orphan exited by itself. msys2 creates children
suspended and resumes them after, so a kill landing in that window strands one
that never exits and EOF never comes; that is the reported frozen session.

The encoded launcher stays as the fallback for profile paths the shells cannot
carry bare (space, `%`, `^`, `&`, non-ASCII) and for hosts where Git Bash is not
resolvable, because PowerShell 5.1 rejects `||`. Every other agent's hook is
untouched, as is the remote/SSH path.

Not adopted from the report: `cmd.exe /d /c <path>` (MSYS rewrites the `/c`
under Git Bash -- measured, the invocation fails), and raising the 10s timeout
(the orphan survives the kill regardless; the fast path puts the hook 30x under
the budget so the kill effectively stops firing).

* fix(build): list the new hook launcher modules in the CLI tsconfig project

config/tsconfig.cli.json enumerates its files explicitly, so the two new
imports reached by src/main/claude/hook-settings.ts failed tc:cli with TS6307.
src/main/git-bash.ts pulls in only node:fs, node:path and a shared constant,
so it adds nothing heavy to the CLI project.

* fix(hooks): address review of the direct Windows Claude hook launcher

- Make the Windows hook suites host-independent. A box with a cmd.exe AutoRun
  (HKCU\...\Command Processor\AutoRun) failed them at HEAD too: the tests
  redirect USERPROFILE, the AutoRun target vanishes, and MSYS spawns a .cmd
  without /d so AutoRun runs and lands on the hook's stderr. Seed an empty
  target, including under the deliberately-absent profile.
- Note in managed-hook-stdin-lifecycle why the "missing managed script" case no
  longer exercises the fallback for the direct shape (it carries an absolute
  path, so a redirected profile changes nothing); that path is covered live in
  windows-direct-cmd-hook-command.test.ts.
- Keep the direct shape off UNC profiles: WINDOWS_CMD_SAFE_PATH admits them, but
  //server/share/... is not a command cmd.exe reliably starts.
- Correct the comments: `|| echo {}` also fires when cmd.exe itself exits
  non-zero (failing AutoRun), printing {} twice. The encoded launcher exited 1
  on that same box, so neither shape is clean there.
- Test the contract that replaced runtime %USERPROFILE% resolution (STA-3348): a
  stale absolute path reports not_installed and is rewritten on install.
- Record the standing unmeasured assumption in windows-edr-posture.md: `||` does
  not parse in Windows PowerShell 5.1, so a compat consumer that hosts hook
  strings there would fail closed. Measure before widening to another agent.
- Trim the launcher comments per AGENTS.md; the numbers live in the doc.

* test(win32): register the new Windows-gated hook test in the CI lane

win32-test-lane-registration guards against exactly this: a Windows-gated file
that self-skips on ubuntu and reports success, so it runs on no machine. The new
windows-direct-cmd-hook-command.test.ts needs both entries — WINDOWS_PACKAGE_TESTS
decides whether package_windows runs for a diff, and the workflow argv decides
whether the file runs once that job started.

* test(win32): remove the hook temp tree through the retrying helper

windows-lane-tree-removal-boundary scans exactly the specs in the Windows CI
lane, so registering windows-direct-cmd-hook-command.test.ts subjected it to the
rule: cmd.exe and bash have just exited in that tree, and a raw recursive rm
throws EPERM on Windows while their handles drain, turning a green spec into a
lane failure. Use removeTreeSync, which carries the repo's maxRetries policy.

---------

Co-authored-by: Orca Worker <orca-worker@localhost>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant