Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,15 @@ type HookRun = {
function runHookProcess(
executable: string,
args: string[],
env: NodeJS.ProcessEnv
env: NodeJS.ProcessEnv,
options: { shell?: boolean } = {}
): Promise<HookRun> {
return new Promise((resolve, reject) => {
const child = spawn(executable, args, { env, stdio: ['pipe', 'pipe', 'pipe'] })
const child = spawn(executable, args, {
env,
stdio: ['pipe', 'pipe', 'pipe'],
shell: options.shell ?? false
})
const stdinErrors: NodeJS.ErrnoException[] = []
let stderr = ''
let stdout = ''
Expand Down Expand Up @@ -425,9 +430,16 @@ describe('Windows managed hook stdin structure', () => {

// Why: MSYS rewrites switches and paths, so the command must survive both shells (#14815).
const gitBash = findGitBash()
// Why (#19187): the cmd leg used to be `spawn('cmd.exe', ['/d','/c', entry.command])`.
// Node MSVCRT-quotes an args array, escaping any `"` in the command as `\"`; cmd.exe does
// not decode backslash escapes, so a quoted command trips its "old behaviour" quote strip
// and dispatches a token beginning with a backslash. That fails, and the launcher's own
// `|| echo {}` still prints `{}` and exits 0 — so the leg reports a pass for a command
// that never ran. `shell: true` spawns it as a shell-spawning consumer does
// (`%ComSpec% /d /s /c "<command>"`, verbatim), which cannot drift from the consumer.
const shells = [
{ name: 'cmd.exe', executable: 'cmd.exe', args: ['/d', '/c', entry.command] },
{ name: 'Git Bash', executable: gitBash, args: ['-c', entry.command] }
{ name: 'cmd.exe', executable: entry.command, args: [] as string[], shell: true },
{ name: 'Git Bash', executable: gitBash, args: ['-c', entry.command], shell: false }
]
// Why: cover guard exit, reached curl, and the launcher's missing-script fallback.
const environments = [
Expand All @@ -453,7 +465,9 @@ describe('Windows managed hook stdin structure', () => {
for (const shell of shells) {
for (const environment of environments) {
const label = `${shell.name} / ${environment.name}`
const result = await runHookProcess(shell.executable, shell.args, environment.env)
const result = await runHookProcess(shell.executable, shell.args, environment.env, {
shell: shell.shell
})
expect(result.exitCode, `${label} exit code`).toBe(0)
expect(result.stderr, `${label} stderr`).toBe('')
expect(() => JSON.parse(result.stdout.trim()), `${label} stdout is JSON`).not.toThrow()
Expand Down
163 changes: 112 additions & 51 deletions src/main/agent-hooks/windows-direct-cmd-hook-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,73 @@
// pins the two things that make that safe — the shape carries nothing MSYS or cmd.exe rewrites,
// and it still answers with neutral JSON when the script is gone. The live legs run the string
// through BOTH hosts Claude Code can pick, because the shape has to parse in either.
//
// Why (#19187): two defects in those live legs let a spaced profile through. (a) `canRunLive`
// gated on the temp path being cmd-safe, so on `C:\Users\First Last` the legs skipped entirely
// and nothing exercised a spaced path through a real host. (b) They asserted only that stdout
// was `{}` — which is exactly what `|| echo {}` prints when dispatch FAILS, so a hook that never
// ran passed. Both are fixed below: a dedicated spaced-path directory, and a marker the fallback
// cannot fake.
import { describe, expect, it } from 'vitest'
import { execFileSync } from 'node:child_process'
import { execFileSync, spawnSync } from 'node:child_process'
import { existsSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { removeTreeSync } from '../../shared/windows-transient-lock-removal'
import { WINDOWS_CMD_SAFE_PATH } from './installer-utils'
import { wrapWindowsDirectCmdHookCommand } from './windows-direct-cmd-hook-command'
import { findGitBash } from './windows-git-bash-path.test-fixture'

const SAFE_PATH = 'C:\\Users\\alice\\.orca\\agent-hooks\\claude-hook.cmd'
const SPACED_PATH = 'C:\\Users\\Bob Smith\\.orca\\agent-hooks\\claude-hook.cmd'

describe('wrapWindowsDirectCmdHookCommand', () => {
it('emits the script path with forward slashes and a neutral-JSON fallback', () => {
expect(wrapWindowsDirectCmdHookCommand(SAFE_PATH)).toBe(
'C:/Users/alice/.orca/agent-hooks/claude-hook.cmd || echo {}'
'"C:/Users/alice/.orca/agent-hooks/claude-hook.cmd" || echo {}'
)
})

// Why (#19187): a spaced profile is the case #18875 could not serve. It is quoted, not declined.
it('carries a spaced path instead of declining it', () => {
expect(wrapWindowsDirectCmdHookCommand(SPACED_PATH)).toBe(
'"C:/Users/Bob Smith/.orca/agent-hooks/claude-hook.cmd" || echo {}'
)
})

it('spells nothing either shell would rewrite or reinterpret', () => {
const command = wrapWindowsDirectCmdHookCommand(SAFE_PATH)!

// Why: MSYS rewrites `/c`-shaped tokens into drive paths — a literal `cmd.exe /d /c <path>`
// does not survive Git Bash (measured), which is why no interpreter is spelled at all.
expect(command).not.toMatch(/ \/[a-zA-Z]+( |$)/)
expect(command).not.toMatch(/\\/)
expect(command).not.toMatch(/["']/)
expect(command).not.toMatch(/powershell|cmd\.exe|conhost/i)
// Why: `2>nul` writes a literal file named `nul` into the cwd under MSYS (measured), and no
// stderr sink parses in both hosts. The missing-script line is left on stderr deliberately.
expect(command).not.toContain('2>')
for (const command of [
wrapWindowsDirectCmdHookCommand(SAFE_PATH)!,
wrapWindowsDirectCmdHookCommand(SPACED_PATH)!
]) {
// Why: MSYS rewrites `/c`-shaped tokens into drive paths — a literal `cmd.exe /d /c <path>`
// does not survive Git Bash (measured), which is why no interpreter is spelled at all.
expect(command).not.toMatch(/ \/[a-zA-Z]+( |$)/)
expect(command).not.toMatch(/\\/)
expect(command).not.toMatch(/powershell|cmd\.exe|conhost/i)
// Why (#19187): this used to forbid quoting outright. Double quotes around the whole path
// are the one form both hosts agree on, so what is actually hazardous is narrower — a
// single quote (cmd treats `'` as a literal filename character), a backslash-escaped space
// (bash-only), and a caret (cmd-only). Forbid those, and require the command to open with
// exactly one token that is either fully double-quoted or bare.
expect(command).not.toMatch(/'/)
expect(command).not.toMatch(/\\ |\^/)
expect(command).toMatch(/^(?:"[^"]+"|[^\s"]+) \|\| echo \{\}$/)
// Why: `2>nul` writes a literal file named `nul` into the cwd under MSYS (measured), and no
// stderr sink parses in both hosts. The missing-script line is left on stderr deliberately.
expect(command).not.toContain('2>')
}
})

it('declines any path the shells cannot carry bare', () => {
it('declines any path the shells cannot carry', () => {
for (const path of [
'C:\\Users\\Bob Smith\\.orca\\agent-hooks\\claude-hook.cmd',
// Why (#19187): quoting cannot save these. cmd expands `%VAR%` inside double quotes, and
// `!VAR!` too under delayed expansion, so they must stay on the encoded launcher.
'C:\\Users\\%name%\\.orca\\agent-hooks\\claude-hook.cmd',
'C:\\Users\\a!b\\.orca\\agent-hooks\\claude-hook.cmd',
'C:\\Users\\a^b\\.orca\\agent-hooks\\claude-hook.cmd',
'C:\\Users\\a&b\\.orca\\agent-hooks\\claude-hook.cmd',
'C:\\Users\\a(b)\\.orca\\agent-hooks\\claude-hook.cmd',
'C:\\Users\\a"b\\.orca\\agent-hooks\\claude-hook.cmd',
'C:\\Users\\rené\\.orca\\agent-hooks\\claude-hook.cmd',
'/home/alice/.orca/agent-hooks/claude-hook.sh',
// Why: WINDOWS_CMD_SAFE_PATH admits a UNC profile, but `//server/share/...` is not a
Expand All @@ -64,17 +91,28 @@ describe.skipIf(process.platform !== 'win32')('direct hook command, run by both
}
})()

// Why (#19187): the previous cmd leg was `execFileSync('cmd.exe', ['/d','/c', command])`.
// libuv applies MSVCRT quoting to that argument, turning the command's own `"` into `\"`;
// cmd.exe does not decode backslash escapes, so with four quotes on the line its `/C` rule
// falls to "old behaviour" (strip the leading quote and the last quote) and the command token
// ends up starting with a backslash. Dispatch then fails and `|| echo {}` reports exit 0 — a
// false FAIL for any quoted command. No real consumer invokes cmd that way: Node's own
// `shell: true` emits `cmd.exe /d /s /c "<command>"` with a verbatim command line, which is
// what this uses. `/s` makes the outer-quote strip unconditional; `/c` alone only tolerates a
// single quoted token and breaks the moment a second one appears.
function runInCmd(command: string, cwd: string): { stdout: string; status: number } {
return runCapture('cmd.exe', ['/d', '/c', command], cwd)
const result = spawnSync(process.env.COMSPEC ?? 'cmd.exe', ['/d', '/s', '/c', `"${command}"`], {
cwd,
input: '{"hook_event_name":"PreToolUse"}',
encoding: 'utf8',
windowsVerbatimArguments: true
})
return { stdout: result.stdout ?? '', status: result.status ?? 1 }
}

function runInBash(command: string, cwd: string): { stdout: string; status: number } {
return runCapture(gitBash!, ['-c', command], cwd)
}

function runCapture(file: string, args: string[], cwd: string) {
try {
const stdout = execFileSync(file, args, {
const stdout = execFileSync(gitBash!, ['-c', command], {
cwd,
input: '{"hook_event_name":"PreToolUse"}',
encoding: 'utf8',
Expand All @@ -87,17 +125,28 @@ describe.skipIf(process.platform !== 'win32')('direct hook command, run by both
}
}

// Why: a runner whose TEMP sits under a profile with a space is the encoded-launcher case,
// so these legs skip rather than assert a contract that shape never claimed.
const tempIsCmdSafe = WINDOWS_CMD_SAFE_PATH.test(join(tmpdir(), 'orca-direct-hook-x', 'x.cmd'))
const canRunLive = Boolean(gitBash) && tempIsCmdSafe
// Why (#19187): this used to require the temp path to be cmd-safe, which skipped every
// spaced-profile runner — the exact configuration that was broken, so a space must no longer
// disqualify. A TEMP carrying something outside the quotable class (`%`, a caret, non-ASCII)
// genuinely is the encoded-launcher case and this shape never claimed to serve it, so that
// still skips — but per prefix, and visibly, rather than by asserting inside the body.
const canRunLive = Boolean(gitBash)

function prefixIsSupported(prefix: string): boolean {
return (
wrapWindowsDirectCmdHookCommand(join(tmpdir(), `${prefix}probe`, 'claude-hook.cmd')) !== null
)
}

function withTempDir(run: (dir: string, scriptPath: string, command: string) => void): void {
const dir = mkdtempSync(join(tmpdir(), 'orca-direct-hook-'))
function withTempDir(
prefix: string,
run: (dir: string, scriptPath: string, command: string) => void
): void {
const dir = mkdtempSync(join(tmpdir(), prefix))
try {
const scriptPath = join(dir, 'claude-hook.cmd')
const command = wrapWindowsDirectCmdHookCommand(scriptPath)
expect(command, 'precondition: temp path must be cmd-safe').not.toBeNull()
expect(command, `precondition: ${scriptPath} must be supported`).not.toBeNull()
run(dir, scriptPath, command!)
} finally {
// Why: cmd.exe/bash have just exited in this tree; a raw recursive rm throws EPERM on
Expand All @@ -106,38 +155,50 @@ describe.skipIf(process.platform !== 'win32')('direct hook command, run by both
}
}

it.skipIf(!canRunLive)('answers {} and exit 0 in both hosts when the script exists', () => {
withTempDir((dir, scriptPath, command) => {
writeFileSync(scriptPath, '@echo off\r\necho {}\r\nexit /b 0\r\n', 'utf8')
for (const result of [runInCmd(command, dir), runInBash(command, dir)]) {
expect(result.stdout.trim()).toBe('{}')
expect(result.status).toBe(0)
}
// Why (#19187): `ORCA_RAN`, not `{}`. Asserting `{}` cannot tell "the script ran and printed
// neutral JSON" from "dispatch failed and the fallback fired" — which is how a spaced path
// passed this suite while the hook never executed.
const MARKER_SCRIPT = '@echo off\r\necho ORCA_RAN\r\nexit /b 0\r\n'

for (const [label, prefix] of [
['a cmd-safe path', 'orca-direct-hook-'],
['a path with a space', 'orca direct hook ']
] as const) {
const skipPrefix = !canRunLive || !prefixIsSupported(prefix)

it.skipIf(skipPrefix)(`runs the script in both hosts, on ${label}`, () => {
withTempDir(prefix, (dir, scriptPath, command) => {
writeFileSync(scriptPath, MARKER_SCRIPT, 'utf8')
for (const result of [runInCmd(command, dir), runInBash(command, dir)]) {
expect(result.stdout.trim()).toBe('ORCA_RAN')
expect(result.status).toBe(0)
}
})
})
})

it.skipIf(!canRunLive)(
'still answers {} and exit 0 in both hosts when the script is gone',
() => {
it.skipIf(skipPrefix)(`answers {} in both hosts when the script is gone, on ${label}`, () => {
// Why: compat consumers require neutral JSON even with no managed script (#14818). The
// encoded launcher did this with a Test-Path; `|| echo {}` does it with no interpreter.
withTempDir((dir, scriptPath, command) => {
withTempDir(prefix, (dir, scriptPath, command) => {
expect(existsSync(scriptPath)).toBe(false)
for (const result of [runInCmd(command, dir), runInBash(command, dir)]) {
expect(result.stdout.trim()).toBe('{}')
expect(result.status).toBe(0)
}
})
})
}

it.skipIf(!canRunLive || !prefixIsSupported('orca direct hook '))(
'leaves no stray `nul` file behind in the working directory',
() => {
// Why this is worth a test: adding `2>nul` to silence the missing-script line looks like
// tidy-up, but under MSYS it creates a real file named `nul` in the cwd — which is the
// user's repo. Measured on Windows 11. Keep stderr unredirected.
withTempDir('orca direct hook ', (dir, _scriptPath, command) => {
runInBash(command, dir)
expect(readdirSync(dir)).not.toContain('nul')
})
}
)

it.skipIf(!canRunLive)('leaves no stray `nul` file behind in the working directory', () => {
// Why this is worth a test: adding `2>nul` to silence the missing-script line looks like
// tidy-up, but under MSYS it creates a real file named `nul` in the cwd — which is the
// user's repo. Measured on Windows 11. Keep stderr unredirected.
withTempDir((dir, _scriptPath, command) => {
runInBash(command, dir)
expect(readdirSync(dir)).not.toContain('nul')
})
})
})
35 changes: 31 additions & 4 deletions src/main/agent-hooks/windows-direct-cmd-hook-command.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { WINDOWS_CMD_SAFE_PATH } from './installer-utils'

// Why: a drive-letter path only. WINDOWS_CMD_SAFE_PATH also admits a UNC profile, and
// `//server/share/...` is not a command cmd.exe reliably starts.
const WINDOWS_DRIVE_LETTER_PATH = /^[A-Za-z]:\\/

// Why (#19187): WINDOWS_CMD_SAFE_PATH excludes the space, so `C:\Users\First Last` — an ordinary
// profile shape — returned null and kept the encoded launcher #18875 removed, with none of that
// fix's benefit. A space is the one character a surrounding pair of double quotes fixes in both
// hosts; everything the shared class already excluded (`%`, `!`, `^`, `&`, `(`, `)`, quotes,
// non-ASCII) stays excluded, because quoting cannot save those — cmd expands `%VAR%` inside
// double quotes, and `!VAR!` too under delayed expansion. Local to this file rather than a
// widening of the shared class, which has other callers.
// Precedent: `runtime-home-hook-command.ts` already spells its Windows script path
// always-quoted, and its hazard list (`& ^ ( ) ; , = % !`) likewise does not include the space.
const WINDOWS_CMD_QUOTABLE_PATH = /^[A-Za-z0-9_.:\\~ -]+$/

/**
* Shortest launcher for a managed Windows `.cmd` hook: the script path itself (#18875).
*
Expand All @@ -15,16 +24,34 @@ const WINDOWS_DRIVE_LETTER_PATH = /^[A-Za-z]:\\/
* Returns null when the caller must keep the encoded launcher: a path either shell would mangle.
*/
export function wrapWindowsDirectCmdHookCommand(scriptPath: string): string | null {
if (!WINDOWS_CMD_SAFE_PATH.test(scriptPath) || !WINDOWS_DRIVE_LETTER_PATH.test(scriptPath)) {
if (!WINDOWS_DRIVE_LETTER_PATH.test(scriptPath) || !WINDOWS_CMD_QUOTABLE_PATH.test(scriptPath)) {
return null
}
// Why: forward slashes are the one separator both hosts read, and no token here is a switch
// MSYS can rewrite — a literal `cmd.exe /d /c <path>` does not survive Git Bash (measured).
const invocation = scriptPath.replaceAll('\\', '/')
// Why (#19187): quote unconditionally rather than only when a space is present. One emitted
// shape means the harnesses and the tests see the same string on every machine; quoting only
// spaced paths makes the emitted shape depend on whether the runner's own profile has a space
// (TEMP is profile-scoped), which turns a deterministic contract into a per-box coin flip.
//
// Double quotes are inert here for a path this class admits: bash expands `$`, a backtick or a
// `\` inside double quotes and the class permits none of them by this line (the backslashes it
// does permit are forward slashes above), and cmd needs the quotes precisely to keep a spaced
// path one token.
//
// One measured exception, so this is not overclaimed: the quoted form does NOT survive
// `execFileSync('cmd.exe', ['/d','/c', command])`. libuv MSVCRT-quotes that argument (`"` ->
// `\"`), cmd.exe does not decode backslash escapes, and with four quotes on the line its `/C`
// rule falls to "old behaviour" — strip the leading quote and the last quote — leaving a
// command token that starts with a backslash. Dispatch then fails and `|| echo {}` reports
// exit 0. No consumer spawns cmd that way: a shell (`shell: true` -> `%ComSpec% /d /s /c
// "<cmd>"`, verbatim) and `bash -c` both run it correctly, and both are measured green.
const invocationToken = `"${invocation}"`
// Why: neutral JSON when the script is missing (#14818), with no interpreter to Test-Path with.
// Valid in bash and cmd.exe; PowerShell 5.1 rejects `||`, which is what gates this on Git Bash.
// It also fires when cmd.exe itself exits non-zero (a failing AutoRun), printing `{}` twice —
// on that same box the encoded launcher exited 1 instead, so neither shape is clean there.
// Stderr stays unredirected: `2>nul` writes a literal `nul` file into the cwd under MSYS.
return `${invocation} || echo {}`
return `${invocationToken} || echo {}`
}
Loading
Loading