Preserve native exit codes in Windows PowerShell hooks (#64013)

## Why

PowerShell's `-Command` can report a native command's exit code `2` as
`1`, so a `PreToolUse` hook can fail to block a tool call.

## What changed

Use `$?` to preserve successful hook results and forward
`$LASTEXITCODE` on failure when available. Pass scripts with named
blocks through as written because PowerShell forbids trailing
top-level statements after those blocks.

## Testing

Add Windows regression coverage for a native command and a PowerShell
`end` block that each exit with code `2`. Both cases check that
`PreToolUse` denies `apply_patch` before approval, reports the denial
reason, and leaves the target file uncreated.

GitOrigin-RevId: 9668b1382bb56f168794dd8d4d2fecac13d2f649
This commit is contained in:
Eric Traut
2026-11-25 22:53:41 +00:00
committed by copyberry
parent e54baff042
commit 653def34fb
2 changed files with 77 additions and 0 deletions
@@ -748,6 +748,46 @@ async fn apply_patch_cli_reports_missing_context() -> Result<()> {
Ok(())
}
#[cfg(windows)]
#[test_case("cmd.exe /c 'echo patch denied 1>&2 & exit /b 2'"; "native")]
#[test_case("end { [Console]::Error.WriteLine('patch denied'); exit 2 }"; "named block")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn powershell_hook_denies_patch_before_approval(command: &'static str) -> Result<()> {
skip_if_no_network!(Ok(()));
let harness = apply_patch_harness_with(|builder| {
builder
.with_pre_build_hook(move |home| {
let hooks = json!({"hooks": {"PreToolUse": [{
"matcher": "^apply_patch$",
"hooks": [{"type": "command", "command": command}]
}]}});
fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hook");
})
.with_config(core_test_support::hooks::trust_discovered_hooks)
})
.await?;
let call_id = "denied-patch";
let patch = "*** Begin Patch\n*** Add File: denied.txt\n+blocked\n*** End Patch";
mount_apply_patch(&harness, call_id, patch, "done").await;
harness
.test()
.submit_turn_with_policies(
"apply the patch",
AskForApproval::OnRequest,
SandboxPolicy::new_read_only_policy(),
)
.await?;
let output = harness.apply_patch_output(call_id).await;
assert!(
output.contains("Command blocked by PreToolUse hook: patch denied"),
"{output}"
);
assert!(!harness.path_exists("denied.txt").await?);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_cli_reports_missing_target_file() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -469,6 +469,43 @@ fn build_command(
#[cfg(windows)]
if shell.program.is_empty() || shell.args.iter().any(|arg| arg.eq_ignore_ascii_case("/c")) {
command.raw_arg(format!(r#""{command_line}""#));
} else if shell
.args
.last()
.is_some_and(|arg| arg.eq_ignore_ascii_case("-Command"))
{
// PowerShell forbids top-level statements after named blocks. Look past
// leading comments and declarations, but not into native command arguments.
let mut script = command_line.trim_start();
while let Some((_, rest)) = if script.starts_with('#') {
script.split_once('\n')
} else if script.starts_with("<#") {
script.split_once("#>")
} else {
None
} {
script = rest.trim_start();
}
let mut words = script
.split(|c: char| c.is_whitespace() || matches!(c, '{' | '(' | ')' | ';' | '<' | '>'));
let first = words.next().unwrap_or_default();
let named_block = |word: &str| {
["begin", "process", "end", "clean", "dynamicparam"]
.iter()
.any(|name| word.eq_ignore_ascii_case(name))
};
let declaration = first.eq_ignore_ascii_case("param")
|| first.eq_ignore_ascii_case("using")
|| script.starts_with('[');
if script.contains('{') && (named_block(first) || (declaration && words.any(named_block))) {
command.arg(command_line);
} else {
// PowerShell -Command reduces native failures to 1. Check $? first so a
// successful hook doesn't inherit an earlier command's failure.
command.arg(format!(
"{command_line}\nif ($?) {{ exit 0 }}\nif ($LASTEXITCODE) {{ exit $LASTEXITCODE }}\nexit 1"
));
}
} else {
command.arg(command_line);
}