Skip to content

fix(worktrees): stop silently switching existing Windows setup scripts to Git Bash - #12406

Merged
OrcaWin merged 3 commits into
mainfrom
fix/windows-setup-runner-shell-flip
Aug 4, 2026
Merged

OrcaWin merged 3 commits into
mainfrom
fix/windows-setup-runner-shell-flip

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Defect

resolveSetupRunnerShell (src/main/hooks.ts) derives the native-Windows setup-runner shell from the terminalWindowsShell terminal preference. When that preference resolves to Git Bash it returns { family: 'posix' }, and createWorktreeRunnerScript writes the project's setup script to a .sh file launched with bash.

That was applied retroactively to setup scripts that already existed. Before #6967 every native-Windows setup script ran under cmd.exe, so every pre-existing Windows setup script is cmd-authored.

Concrete failure scenario

A Windows user has terminalWindowsShell set to Git Bash — a perfectly reasonable terminal preference — and an orca.yaml setup hook written in batch:

scripts:
  setup: |
    copy .env.example .env
    set NODE_ENV=test
    if errorlevel 1 exit /b 1
    xcopy /E assets dist

They upgrade. The same script is now handed to bash: copy and xcopy do not exist, set NODE_ENV=test sets positional parameters instead of an env var, if errorlevel 1 is a syntax error, and assets dist backslash paths get eaten by bash escaping. Setup breaks with no migration and no warning, and it looks like Orca broke their project.

There is a second, steady-state half of the same defect: because the interpreter came from a per-user preference, two contributors on the same repo got different interpreters for the same orca.yaml. No project could write a Windows setup script that worked for all of its contributors.

The fix

The interpreter is a property of the script, not of the terminal the user likes, so the script declares it the standard way — a leading #! line.

  • Native Windows keeps the historical .cmd runner unless the script's first line is a #! naming a POSIX shell. No existing script changes behavior on upgrade.
  • resolveSetupRunnerShell keeps its existing role as the feasibility gate: a bash runner still requires the configured terminal to resolve to Git Bash, because the launch command is typed into that shell and the runner uses MSYS /c/... paths that Cygwin and the WSL shim reject. Its return value now means "a bash runner could launch here", and the per-script #! decides whether one is used.
  • buildWindowsRunnerScript drops a leading #! line instead of calling it. A declared-bash script that falls back to cmd (Git Bash not installed) now fails on a real setup line rather than aborting on errorlevel at line one.
  • New src/shared/setup-script-shebang.ts parses the interpreter line: #!/usr/bin/env bash, #!/bin/sh -e, #!/usr/bin/env -S bash -euo pipefail, and Windows bash.exe paths all count; node/python3 and comment-only first lines do not.

Issue-command runners go through the same code path and get the same rule, so an issue command authored for cmd is not flipped either.

Why this option

The alternatives were weighed:

  • Record the shell a script was authored against. Requires persistent per-repo state, can't distinguish "upgrading user" from "new user", and freezes a repo on whatever it was first run with — a user who later writes a bash script stays on cmd forever.
  • Detect batch-only idioms. A heuristic guessing user intent, which is the same class of silent-wrong-behavior this PR is fixing, and it still has to pick a side for the large majority of scripts that are ambiguous (pnpm install).
  • A #! line. Explicit, zero state, zero heuristics, standard, per-project, and identical for every contributor who checks the repo out. Chosen.

Unchanged: WSL worktrees, macOS/Linux (always bash), and SSH hosts (runner format follows the remote path format, never local Windows preferences).

Verification

All tests use runtime platform overrides, so they run on any host.

New/changed tests:

  • src/shared/setup-script-shebang.test.ts — interpreter-line parsing, including CRLF, env -S, non-shell interpreters, and a non-first-line #!.
  • src/main/hooks.test.ts — "keeps batch setup scripts on cmd.exe when the terminal is Git Bash" (the reported regression: { family: 'posix' } + copy/xcopy script still produces setup-runner.cmd), plus the issue-command equivalent, plus the existing POSIX-runner test updated to declare a shebang.
  • src/main/hooks-runner.test.ts — buildWindowsRunnerScript drops a leading shebang instead of calling it.

I reverted src/main/hooks.ts (git stash push src/main/hooks.ts), confirmed all three new regression tests fail without the fix, then restored it (git stash pop) and confirmed they pass.

npx vitest run --config config/vitest.config.ts \
  src/main/hooks.test.ts src/main/hooks-runner.test.ts \
  src/shared/setup-script-shebang.test.ts src/shared/setup-runner-command.test.ts \
  src/main/ipc/worktrees-windows.test.ts src/main/ipc/worktrees.test.ts
# 6 files, 379 tests passed

npx vitest run --config config/vitest.config.ts \
  src/shared/setup-agent-sequencing.test.ts src/shared/setup-agent-sequencing.windows.test.ts \
  src/main/ipc/worktree-logic.test.ts src/main/ipc/worktree-logic-wsl.test.ts \
  src/main/runtime/orchestration
# 32 files, 406 tests passed

npx tsc --noEmit -p config/tsconfig.node.json   # clean
npx oxlint <touched files>                       # clean
npm run check:max-lines-ratchet                  # OK, no new bypasses

…s to Git Bash

#6967 derived the Windows setup-runner shell from `terminalWindowsShell`. On
upgrade, any Windows user whose terminal preference resolved to Git Bash had
their existing `orca.yaml` setup script (and issue command) handed to bash
instead of cmd.exe. Scripts authored against the cmd runner — `copy`, `xcopy`,
`set VAR=value`, `if errorlevel 1`, `%VAR%`, backslash paths — broke with no
migration and no warning, and the failure looked like Orca broke the project.

The conflation is also wrong in the steady state: a terminal preference is
per-user, so two people on the same repo got different interpreters for the
same orca.yaml and no project could write a setup script that worked for all
of its Windows contributors.

The interpreter is now a property of the script, declared the standard way:
a leading `#!` line. Native Windows keeps the historical `.cmd` runner unless
the script declares a POSIX shell, so no existing script changes behavior.
`resolveSetupRunnerShell` keeps its role as the feasibility gate — a bash
runner still requires the terminal to resolve to Git Bash, since the launch
command is typed into that shell and uses MSYS `/c/...` paths.

`buildWindowsRunnerScript` now drops a leading `#!` line rather than `call`ing
it, so a declared-bash script that falls back to cmd (Git Bash missing) fails
on a real setup line instead of aborting on errorlevel at line one.

WSL worktrees, POSIX platforms, and SSH hosts are untouched.
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added shebang parsing for setup scripts, including POSIX shell detection, option replay, and leading-shebang removal. Native Windows runner selection now uses script shebangs independently from terminal shell settings. POSIX scripts receive POSIX runners, while batch runners reject POSIX scripts. Git Bash launches Windows batch runners through encoded PowerShell commands. Tests cover runner generation, command resolution, completion signaling, and shell metadata. Documentation describes Windows setup-shell behavior.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the defect, fix, rationale, and testing, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all missing template sections, state “No visual change,” document the AI review and cross-platform checks, provide a security audit, and note platform-specific risks or follow-up work.
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main fix: preventing existing Windows setup scripts from switching silently to Git Bash.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

…pane

Adversarial review of this PR found that pinning the runner format per script
reopened issue #6896 one layer down.

- `WorktreeSetupLaunch.shell` had been redefined to mean "the format the runner
  file was written in". `resolveSetupRunnerCommand` consumes it as "the shell
  that types the launch command", so a Git Bash terminal with a batch setup
  script produced `cmd.exe /c "C:\...\setup-runner.cmd"` typed into a bash pane,
  where MSYS rewrites the `/c` switch into a drive path: cmd opens interactively
  and setup never runs. `shell` is the terminal's family again; the runner file's
  .cmd/.sh extension carries the format, and a batch runner launched from a POSIX
  pane reuses the existing PowerShell ProcessStartInfo launcher.
- The cmd runner dropped a leading `#!` line and ran the rest as batch, so a bash
  script reaching cmd (PowerShell/cmd terminal, or any SSH-to-Windows host) got
  its interpreter-agnostic prefix executed before failing mid-way. It now prints
  why and exits 1 without running anything.
- A `#!` line's option flags were discarded: `#!/usr/bin/env -S bash -euo
  pipefail` lost pipefail because the runner is launched as `bash <path>`. The
  generated posix runner now replays declared flags via `set` and drops the
  duplicate interpreter line.
- Docs cover the per-user setup command in repository hook settings, which goes
  through the same `#!` rule, and describe what the `#!` line does and does not
  select.

Tests: composed launch command for a POSIX pane + cmd runner (hooks, shared
runner command, setup sequencing gate, observed-setup signal), the cmd runner's
shebang refusal, and shebang flag replay. Each fails with the source reverted.
@OrcaWin

OrcaWin commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Adversarial review found the fix was correct at the runner-generation layer but reopened issue #6896 at the launch layer. Addressed:

#1 (blocking) — cmd.exe /c from a Git Bash pane. The PR redefined WorktreeSetupLaunch.shell to mean "the format the runner file was written in", but resolveSetupRunnerCommand reads it as "the shell that types the launch command". A Git Bash terminal + batch setup script therefore produced cmd.exe /c "C:\...\setup-runner.cmd" typed into a bash pane, where MSYS rewrites /c into a drive path — cmd opens interactively and setup never runs. Root cause fixed by restoring the contract: shell is the terminal's family again (src/main/hooks.ts), the runner file's .cmd/.sh extension carries the format, and resolveSetupRunnerCommand now branches on both — a batch runner launched from a POSIX pane reuses the existing PowerShell ProcessStartInfo launcher (buildWindowsCmdRunnerDelayedLaunchCommand), which is already the repo's MSYS-safe shape. WSL, PowerShell/cmd panes, SSH remotes, and .sh runners keep their exact previous commands.

#2 (should-fix) — untested composition. Added coverage for the newly-possible "posix pane + cmd runner" combination at every layer that builds a launch string: setup-runner-command.test.ts (no bash, no bare cmd.exe /c, native path preserved), hooks.test.ts end-to-end from createSetupRunnerScript through buildSetupRunnerCommand, setup-agent-sequencing.test.ts (wait-for-setup gate), and setup-completion-signal.test.ts (observed setup).

#3 (should-fix) — declared shebang only used as a boolean. #!/usr/bin/env -S bash -euo pipefail lost pipefail because the runner is launched as bash <path>, which never parses the interpreter line. The generated posix runner now replays declared option flags through set and drops the duplicate interpreter line (all platforms). Docs state plainly what the #! line does and does not select — the interpreter name is only read as "is this a POSIX shell", and sh/zsh scripts run under bash exactly as they already did on macOS/Linux.

#4 (should-fix) — partial execution of a bash body under cmd. Dropping the #! line meant a bash script reaching the cmd runner (PowerShell/cmd terminal, or any SSH-to-Windows host, which always uses buildWindowsRunnerScript) executed its interpreter-agnostic prefix before dying mid-way. The generated .cmd now prints why and exit /b 1 without running anything, restoring the pre-PR "abort at line 1" with a message that says what to do.

#5 (nit) — partial. docs/reference/windows-setup-shell.md now covers the per-user setup command in repository hook settings (the exact configuration #6896 was filed against) and the launch-shell contract. The settings-UI hint is not included: it needs a new i18n key plus translations in 5 locale files, which is out of proportion for a nit — happy to add it separately.

Verification. Every new/updated test was proven to fail with only the source reverted (git checkout -- src/main/hooks.ts src/shared/setup-runner-command.ts src/shared/setup-script-shebang.ts, restored via patch — no stash). 16 failures without the fix, all green with it. Suites run: hooks, hooks-runner, setup-script-shebang, setup-runner-command, setup-agent-sequencing (+windows), orchestration, worktrees, worktrees-windows, worktree-activation, launch-worktree-background-terminals, orca-runtime (763 + 1016 pass). tsc -p config/tsconfig.node.json clean; tsconfig.web.json clean except pre-existing TS6307; oxlint and oxfmt --check clean on touched files. The original fix and its three regression tests are intact.

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9eee8f93-fa1f-4a17-abd7-ce58a6c04a8e

📥 Commits

Reviewing files that changed from the base of the PR and between c052ca1 and 2f05d46.

📒 Files selected for processing (12)
  • .gitignore
  • AGENTS.md
  • docs/reference/windows-setup-shell.md
  • src/main/hooks-runner.test.ts
  • src/main/hooks.test.ts
  • src/main/hooks.ts
  • src/main/runtime/orchestration/setup-completion-signal.test.ts
  • src/shared/setup-agent-sequencing.test.ts
  • src/shared/setup-runner-command.test.ts
  • src/shared/setup-runner-command.ts
  • src/shared/setup-script-shebang.test.ts
  • src/shared/setup-script-shebang.ts

Comment thread docs/reference/windows-setup-shell.md Resolved
Comment on lines +67 to +82
function parseShellOptions(tokens: string[]): string[] {
const options: string[] = []
for (let index = 0; index < tokens.length; index++) {
const token = tokens[index]
if (!SHELL_OPTION_FLAG_PATTERN.test(token)) {
continue
}
options.push(token)
// Why: `-o`/`-euo` take the option name as a separate argument (`pipefail`).
const optionName = tokens[index + 1]
if (token.endsWith('o') && optionName && SHELL_OPTION_NAME_PATTERN.test(optionName)) {
options.push(optionName)
index++
}
}
return options

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

bash -O extglob -c 'shopt -q extglob'

if bash -c 'set -O' >/dev/null 2>&1; then
  echo 'Expected bash to reject set -O' >&2
  exit 1
fi

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Bash version:\n'
bash --version | head -1

printf '\nPattern and function definitions:\n'
rg -n "SHELL_OPTION_FLAG_PATTERN|SHELL_OPTION_NAME_PATTERN|function parseShellOptions|escapeShellOptions|parseSetupScriptShebang" src/shared/setup-script-shebang.ts src/main/hooks.ts src/shared/setup-script-shebang.test.ts

printf '\nsetup-script-shebang.ts relevant lines:\n'
cat -n src/shared/setup-script-shebang.ts | sed -n '1,120p'

printf '\nhooks.ts relevant lines:\n'
cat -n src/main/hooks.ts | sed -n '470,510p'

printf '\ntest relevant lines:\n'
cat -n src/shared/setup-script-shebang.test.ts | sed -n '1,90p'

printf '\nBehavior probe with shell-parsed patterns (no repo code execution):\n'
python3 - <<'PY'
import re, subprocess, textwrap
src=open('src/shared/setup-script-shebang.ts','r').read()
m=re.search(r"const\s+([A-Z_]+_PATTERN)=/([^/]+)/;|\n\\s*function\s+parseShellOptions\\s*\\(",src)
print('found patterns/functions:', [x.group(1) for x in re.finditer(r"const\s+([A-Z_]+_PATTERN)=/([^/]+)/;/\n",src)])
# Extract function via first line after assignment? Use exact line numbers for robustness by reading file.
PY

python3 - <<'PY'
import re
src=open('src/shared/setup-script-shebang.ts','r').read()
lines=src.splitlines()
for i,l in enumerate(lines,1):
    if re.search(r"const\s+([A-Z_]+_PATTERN)=/",l):
        print(i,l)
PY

Repository: stablyai/orca

Length of output: 13050


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Bash version:\n'
bash --version | head -1

printf '\nPattern and function definitions:\n'
rg -n "SHELL_OPTION_FLAG_PATTERN|SHELL_OPTION_NAME_PATTERN|function parseShellOptions|escapeShellOptions|parseSetupScriptShebang" src/shared/setup-script-shebang.ts src/main/hooks.ts src/shared/setup-script-shebang.test.ts

printf '\nsetup-script-shebang.ts relevant lines:\n'
cat -n src/shared/setup-script-shebang.ts | sed -n '1,120p'

printf '\nhooks.ts relevant lines:\n'
cat -n src/main/hooks.ts | sed -n '470,510p'

printf '\ntest relevant lines:\n'
cat -n src/shared/setup-script-shebang.test.ts | sed -n '1,90p'

printf '\nBehavior probe with shell-parsed patterns (no repo code execution):\n'
python3 - <<'PY'
import re

src=open('src/shared/setup-script-shebang.ts','r').read()
lines=src.splitlines()
for i,l in enumerate(lines,1):
    if re.search(r"const\s+([A-Z_]+_PATTERN)=/",l):
        print(i,l)
PY

Repository: stablyai/orca

Length of output: 12227


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'shellOptions for -O extglob:\n'
node --input-type=module <<'JS'
const SHELL_OPTION_FLAG_PATTERN = /^[-+][a-zA-Z]+$/
const SHELL_OPTION_NAME_PATTERN = /^[a-z_]+$/

function parseSetupScriptShebang(script) {
  const firstLine = script.split('\n', 1)[0] ?? ''
  if (!firstLine.trimStart().startsWith('#!')) {
    return null
  }
  const tokens = firstLine.trim().slice(2).trim().split(/\s+/).filter(Boolean)
  const interpreterIndex = findInterpreterIndex(tokens)
  if (interpreterIndex === -1) {
    return null
  }
  return {
    interpreter: executableBasename(tokens[interpreterIndex]),
    shellOptions: parseShellOptions(tokens.slice(interpreterIndex + 1))
  }
}

function findInterpreterIndex(tokens) {
  for (let index = 0; index < tokens.length; index++) {
    const basename = executableBasename(tokens[index])
    if (basename === '' || basename === 'env' || basename.startsWith('-')) {
      continue
    }
    return index
  }
  return -1
}

function parseShellOptions(tokens) {
  const options = []
  for (let index = 0; index < tokens.length; index++) {
    const token = tokens[index]
    if (!SHELL_OPTION_FLAG_PATTERN.test(token)) {
      continue
    }
    options.push(token)
    const optionName = tokens[index + 1]
    if (token.endsWith('o') && optionName && SHELL_OPTION_NAME_PATTERN.test(optionName)) {
      options.push(optionName)
      index++
    }
  }
  return options
}

function executableBasename(token) {
  return (
    token
      .replaceAll('\\', '/')
      .split('/')
      .pop()
      ?.toLowerCase()
      .replace(/\.exe$/, '') ?? ''
  )
}

for (const script of [
  '#!/bin/bash -O extglob\nmake',
  '#!/usr/bin/env -S bash -O extglob\nmake',
  '#!/bin/bash -O extglob -e -x\nmake',
]) {
  console.log(script.replace('\n', '\\n'))
  console.log(parseSetupScriptShebang(script))
}
JS

printf '\nRunner emitted for -O extglob:\n'
node --input-type=module <<'JS'
const SHELL_OPTION_FLAG_PATTERN = /^[-+][a-zA-Z]+$/
const SHELL_OPTION_NAME_PATTERN = /^[a-z_]+$/

function parseSetupScriptShebang(script) {
  const firstLine = script.split('\n', 1)[0] ?? ''
  if (!firstLine.trimStart().startsWith('#!')) {
    return null
  }
  const tokens = firstLine.trim().slice(2).trim().split(/\s+/).filter(Boolean)
  const interpreterIndex = findInterpreterIndex(tokens)
  if (interpreterIndex === -1) {
    return null
  }
  return {
    interpreter: executableBasename(tokens[interpreterIndex]),
    shellOptions: parseShellOptions(tokens.slice(interpreterIndex + 1))
  }
}

function findInterpreterIndex(tokens) {
  for (let index = 0; index < tokens.length; index++) {
    const basename = executableBasename(tokens[index])
    if (basename === '' || basename === 'env' || basename.startsWith('-')) {
      continue
    }
    return index
  }
  return -1
}

function parseShellOptions(tokens) {
  const options = []
  for (let index = 0; index < tokens.length; index++) {
    const token = tokens[index]
    if (!SHELL_OPTION_FLAG_PATTERN.test(token)) {
      continue
    }
    options.push(token)
    const optionName = tokens[index + 1]
    if (token.endsWith('o') && optionName && SHELL_OPTION_NAME_PATTERN.test(optionName)) {
      options.push(optionName)
      index++
    }
  }
  return options
}

function executableBasename(token) {
  return (
    token
      .replaceAll('\\', '/')
      .split('/')
      .pop()
      ?.toLowerCase()
      .replace(/\.exe$/, '') ?? ''
  )
}

const script = '#!/bin/bash -O O pipefail -e\nmake'
const shebang = parseSetupScriptShebang(script)
const declaredOptions = shebang?.shellOptions.length ? `set ${shebang.shellOptions.join(' ')}\n` : ''
const body = shebang ? script.slice(script.indexOf('\n') + 1) : script
console.log(`#!/usr/bin/env bash\nset -e\n${declaredOptions}${body}\n`)
JS

Repository: stablyai/orca

Length of output: 515


Do not replay Bash -O startup options through set.

#!/bin/bash -O extglob is valid Bash syntax. parseShellOptions() keeps -O, drops extglob, and buildPosixRunnerScript() emits set -O; Bash rejects set -O, so setup fails before the script body runs.

  • src/shared/setup-script-shebang.ts#L67-L82: Parse Bash -O <shopt> separately from flags that set supports.
  • src/main/hooks.ts#L493-L498: Replay -O <shopt> with shopt -s <shopt>, not set.
  • src/shared/setup-script-shebang.test.ts: Add coverage for #!/usr/bin/env -S bash -O extglob.
📍 Affects 3 files
  • src/shared/setup-script-shebang.ts#L67-L82 (this comment)
  • src/main/hooks.ts#L493-L498
  • src/shared/setup-script-shebang.test.ts#L38-L65

… pane's shell

Two round-2 review findings:

- `#!/bin/bash -l` replayed `set -l`, which exits 2 and aborted the runner under
  its own `set -e` before a single setup line ran (all platforms). Only the flags
  `set` documents are replayed now; a bare `-o` with no option name is dropped
  instead of dumping the shell-option table.
- The wait-for-setup gate picked its language from the runner file, so a batch
  runner launched from a Git Bash pane got the PowerShell gate while the agent
  startup command was already POSIX-quoted — `Invoke-Expression` cannot parse
  `'\''`. The gate now follows the pane; the runner still launches through the
  ProcessStartInfo launcher, never through bash.
@OrcaWin

OrcaWin commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Round-2 findings addressed in def7374.

#1 — set replayed invocation-only shebang flags (should-fix, confirmed). Reproduced: #!/bin/bash -l produced a runner containing set -l, which exits 2 and — under the runner's own set -e — aborted setup before the first line. parseShellOptions now allowlists only the flags set documents ([--abefhkmnptuvxBCHP] [-o option]); -l/-s/-i/-r are dropped, and a trailing -o/-euo with no option name is dropped whole instead of dumping the shell-option table into the Setup terminal. Proof is an executable test (src/main/hooks-runner.test.ts) that writes the generated runner and runs it under bash.

#2 — sequencing gate language followed the runner file, not the pane (should-fix, confirmed). Reproduced: git-bash pane → quoteStartupArg posix → claude 'fix the user'\''s login', then a .cmd runner drove createSequencedSetupAgentCommands into the PowerShell branch, whose Invoke-Expression cannot parse that. Fix is one condition in setup-agent-sequencing.ts: the gate follows the pane's shell family, since the pane types the gate and already quoted the startup command for itself. The batch runner still launches through buildWindowsCmdRunnerDelayedLaunchCommand (the #6896 fix), now wrapped by the bash gate rather than the PowerShell one — so it is never handed to bash, and the marker is both written and read by bash (no PowerShell-CRLF vs IFS=: read mismatch).

No new timeouts, retries, or async paths. The not.toContain('bash -lc') assertion in the Git-Bash-pane test was replaced with the invariant it was actually protecting (not.toMatch(/bash\s+\S*setup-runner/)) plus new assertions that the gate is bash -lc and evals the POSIX startup command.

Verification: touched-area vitest (10 files, 229 passed / 1 skipped), tsc node + web, and check-changed-code-quality.mjs (0 new findings incl. react-doctor). Original defect re-confirmed: reverting only src/main/hooks.ts to main fails 7 tests, including keeps batch setup scripts on cmd.exe when the terminal is Git Bash. Each new test verified to fail with only its source change reverted.

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3a10d0db-f284-41e8-8f4a-411140a6c48d

📥 Commits

Reviewing files that changed from the base of the PR and between 2f05d46 and def7374.

📒 Files selected for processing (6)
  • docs/reference/windows-setup-shell.md
  • src/main/hooks-runner.test.ts
  • src/shared/setup-agent-sequencing.test.ts
  • src/shared/setup-agent-sequencing.ts
  • src/shared/setup-script-shebang.test.ts
  • src/shared/setup-script-shebang.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/reference/windows-setup-shell.md
  • src/shared/setup-script-shebang.ts

expect(result.setupCommand).toContain(
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand'
)
expect(result.setupCommand).not.toMatch(/bash\s+\S*setup-runner/)

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

Make the Bash-rejection assertion cover option-bearing invocations.

Line 236 only matches bash followed by a single token containing setup-runner. It misses a direct invocation such as bash -lc "C:\repo\.git\orca\setup-runner.cmd", so the test can pass while Bash still receives the batch runner. Assert that the raw runner path is absent from the generated command, or verify that the decoded PowerShell payload is the only runner invocation.

🧰 Tools
🪛 ast-grep (0.45.0)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { spawn } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment on lines +45 to +58
// Why: the gate is typed into the terminal pane and `startupCommand` is already quoted for that
// pane, so a batch runner launched from a Git Bash pane still needs the bash gate — PowerShell's
// `Invoke-Expression` cannot parse the POSIX `'\''` escaping the pane's quoting produces. The
// runner itself still launches through `resolution.command`, never through bash.
const posixGateForWindowsRunner = resolution.shell === 'windows' && args.shell?.family === 'posix'
const markerBasePath = posixGateForWindowsRunner
? nativeWindowsPathToPosixShellPath(resolution.runnerScriptPathForShell)
: resolution.runnerScriptPathForShell
// Why: overlapping gated launches of the same setup runner must not race on
// a shared completion marker.
const markerPath = `${resolution.runnerScriptPathForShell}.${nonce}.done`
const markerPath = `${markerBasePath}.${nonce}.done`
const waitTimeoutSeconds = args.waitTimeoutSeconds ?? DEFAULT_WAIT_TIMEOUT_SECONDS

if (resolution.shell === 'windows') {
if (resolution.shell === 'windows' && !posixGateForWindowsRunner) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Preserve WSL marker-path handling.

Line 49 treats every POSIX pane as Git Bash. nativeWindowsPathToPosixShellPath converts C:\repo\... to /c/repo/..., but WSL uses its configured Windows-drive mount path, commonly /mnt/c.

When a .cmd runner launches from wsl.exe, the POSIX gate can write or poll a different marker path. The agent then waits until timeout. Apply the /c conversion only for the MSYS/Git Bash environment. Resolve the marker path through WSL for wsl.exe, and add coverage for a Windows .cmd runner from WSL.

As per coding guidelines, keep platform-dependent behavior behind runtime checks for macOS, Linux, and Windows.

Source: Coding guidelines

@OrcaWin
OrcaWin merged commit ed7849e into main Aug 4, 2026
42 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…s to Git Bash (stablyai#12406)

* fix(worktrees): stop silently switching existing Windows setup scripts to Git Bash

stablyai#6967 derived the Windows setup-runner shell from `terminalWindowsShell`. On
upgrade, any Windows user whose terminal preference resolved to Git Bash had
their existing `orca.yaml` setup script (and issue command) handed to bash
instead of cmd.exe. Scripts authored against the cmd runner — `copy`, `xcopy`,
`set VAR=value`, `if errorlevel 1`, `%VAR%`, backslash paths — broke with no
migration and no warning, and the failure looked like Orca broke the project.

The conflation is also wrong in the steady state: a terminal preference is
per-user, so two people on the same repo got different interpreters for the
same orca.yaml and no project could write a setup script that worked for all
of its Windows contributors.

The interpreter is now a property of the script, declared the standard way:
a leading `#!` line. Native Windows keeps the historical `.cmd` runner unless
the script declares a POSIX shell, so no existing script changes behavior.
`resolveSetupRunnerShell` keeps its role as the feasibility gate — a bash
runner still requires the terminal to resolve to Git Bash, since the launch
command is typed into that shell and uses MSYS `/c/...` paths.

`buildWindowsRunnerScript` now drops a leading `#!` line rather than `call`ing
it, so a declared-bash script that falls back to cmd (Git Bash missing) fails
on a real setup line instead of aborting on errorlevel at line one.

WSL worktrees, POSIX platforms, and SSH hosts are untouched.

* fix(worktrees): keep the cmd setup runner launchable from a Git Bash pane

Adversarial review of this PR found that pinning the runner format per script
reopened issue stablyai#6896 one layer down.

- `WorktreeSetupLaunch.shell` had been redefined to mean "the format the runner
  file was written in". `resolveSetupRunnerCommand` consumes it as "the shell
  that types the launch command", so a Git Bash terminal with a batch setup
  script produced `cmd.exe /c "C:\...\setup-runner.cmd"` typed into a bash pane,
  where MSYS rewrites the `/c` switch into a drive path: cmd opens interactively
  and setup never runs. `shell` is the terminal's family again; the runner file's
  .cmd/.sh extension carries the format, and a batch runner launched from a POSIX
  pane reuses the existing PowerShell ProcessStartInfo launcher.
- The cmd runner dropped a leading `#!` line and ran the rest as batch, so a bash
  script reaching cmd (PowerShell/cmd terminal, or any SSH-to-Windows host) got
  its interpreter-agnostic prefix executed before failing mid-way. It now prints
  why and exits 1 without running anything.
- A `#!` line's option flags were discarded: `#!/usr/bin/env -S bash -euo
  pipefail` lost pipefail because the runner is launched as `bash <path>`. The
  generated posix runner now replays declared flags via `set` and drops the
  duplicate interpreter line.
- Docs cover the per-user setup command in repository hook settings, which goes
  through the same `#!` rule, and describe what the `#!` line does and does not
  select.

Tests: composed launch command for a POSIX pane + cmd runner (hooks, shared
runner command, setup sequencing gate, observed-setup signal), the cmd runner's
shebang refusal, and shebang flag replay. Each fails with the source reverted.

* fix(worktrees): replay only real `set` flags and keep the gate in the pane's shell

Two round-2 review findings:

- `#!/bin/bash -l` replayed `set -l`, which exits 2 and aborted the runner under
  its own `set -e` before a single setup line ran (all platforms). Only the flags
  `set` documents are replayed now; a bare `-o` with no option name is dropped
  instead of dumping the shell-option table.
- The wait-for-setup gate picked its language from the runner file, so a batch
  runner launched from a Git Bash pane got the PowerShell gate while the agent
  startup command was already POSIX-quoted — `Invoke-Expression` cannot parse
  `'\''`. The gate now follows the pane; the runner still launches through the
  ProcessStartInfo launcher, never through bash.

---------

Co-authored-by: OrcaWin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant