The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.
fix(hooks): never run .sh hooks through the WSL bash launcher on Windows
montjeffreyc6b2c55b8702
diff --git a/scripts/hooks/observe-runner.js b/scripts/hooks/observe-runner.jsindex c046d75f0..5213eb1e2 100644--- a/scripts/hooks/observe-runner.js+++ b/scripts/hooks/observe-runner.js@@ -4,6 +4,7 @@const fs = require('fs');const path = require('path');const { spawnSync } = require('child_process');+const { resolveWindowsBashCandidates } = require('../lib/windows-bash');const OBSERVE_RELATIVE_PATH = path.join('skills', 'continuous-learning-v2', 'hooks', 'observe.sh');const DEFAULT_TIMEOUT_MS = 9000;@@ -51,7 +52,9 @@ function findShellBinary() {}if (process.platform === 'win32') {- candidates.push('bash.exe', 'bash', 'sh');+ // Absolute paths, skipping WSL launchers: WSL cannot open the /c/... path+ // toShellPath() hands the shell, so observe.sh would fail on every call.+ candidates.push(...resolveWindowsBashCandidates(['bash.exe', 'bash', 'sh']));} else {candidates.push('bash', 'sh');}diff --git a/scripts/hooks/plugin-hook-bootstrap.js b/scripts/hooks/plugin-hook-bootstrap.jsindex 233e32980..e8738dcc4 100644--- a/scripts/hooks/plugin-hook-bootstrap.js+++ b/scripts/hooks/plugin-hook-bootstrap.js@@ -5,6 +5,7 @@ const path = require('path');const { spawnSync } = require('child_process');const { ensureAgentDataHomeEnv } = require('../lib/agent-data-home');const { normalizePluginRootForPlatform } = require('../lib/resolve-ecc-root');+const { resolveWindowsBashCandidates } = require('../lib/windows-bash');const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input');const SHELL_PROBE_TIMEOUT_MS = 2000;@@ -108,7 +109,8 @@ function findShellBinary() {// bash.exe / conhost.exe processes the way MSYS2/Git Bash does.// Note: PowerShell is only suitable for .ps1 scripts; callers that need// to run .sh scripts (e.g. observe-runner.js) must not use this function.- candidates.push('pwsh.exe', 'powershell.exe', 'bash.exe', 'bash');+ // Bash is named by absolute path so a WSL launcher earlier on PATH is skipped.+ candidates.push('pwsh.exe', 'powershell.exe', ...resolveWindowsBashCandidates(['bash.exe', 'bash']));} else {candidates.push('bash', 'sh');}@@ -142,7 +144,9 @@ function findBashBinary() {if (process.env.BASH && process.env.BASH.trim() && !isPowerShellBin(process.env.BASH.trim())) {candidates.push(process.env.BASH.trim());}- candidates.push('bash.exe', 'bash');+ // On Windows these resolve to absolute paths that exclude WSL launchers;+ // elsewhere they stay bare names.+ candidates.push(...resolveWindowsBashCandidates(['bash.exe', 'bash']));for (const candidate of candidates) {const probe = spawnSync(candidate, ['-c', ':'], {diff --git a/scripts/lib/windows-bash.js b/scripts/lib/windows-bash.jsnew file mode 100644index 000000000..3c4e3ddd9--- /dev/null+++ b/scripts/lib/windows-bash.js@@ -0,0 +1,87 @@+'use strict';++/**+ * Resolve bash on Windows without landing on a WSL launcher.+ *+ * %SystemRoot%\System32\bash.exe and the %LOCALAPPDATA%\Microsoft\WindowsApps+ * alias start a WSL distro. With a distro installed they pass a `bash -c :`+ * probe, then cannot open a hook script named by a Windows (C:\...) or Git+ * Bash (/c/...) path, so the hook fails (exit 127) instead of being skipped.+ * Spawning a bare `bash.exe` takes the first match on PATH, and System32 is+ * normally ahead of Git's bin directory.+ *+ * Tests live at tests/lib/windows-bash.test.js.+ */++const fs = require('fs');+const path = require('path');++const WSL_LAUNCHER_SYSTEM_DIRS = ['System32', 'SysWOW64', 'Sysnative'];++// Windows environment names are case-insensitive; a plain env object is not.+function readEnv(env, name) {+ if (env[name] !== undefined) return env[name];+ const key = Object.keys(env).find(candidate => candidate.toUpperCase() === name.toUpperCase());+ return key === undefined ? undefined : env[key];+}++function normalizeDir(dir) {+ return path.resolve(dir).replace(/[\\/]+$/, '').toLowerCase();+}++function wslLauncherDirs(env) {+ const systemRoot = readEnv(env, 'SystemRoot') || readEnv(env, 'windir') || 'C:\\Windows';+ const dirs = WSL_LAUNCHER_SYSTEM_DIRS.map(name => path.join(systemRoot, name));+ const localAppData = readEnv(env, 'LOCALAPPDATA');+ if (localAppData) dirs.push(path.join(localAppData, 'Microsoft', 'WindowsApps'));+ return new Set(dirs.map(normalizeDir));+}++/**+ * True when filePath is a bash.exe that starts WSL rather than a native bash.+ */+function isWslBashLauncher(filePath, env = process.env) {+ return path.basename(filePath).toLowerCase() === 'bash.exe'+ && wslLauncherDirs(env).has(normalizeDir(path.dirname(filePath)));+}++function isFile(filePath) {+ try {+ return fs.statSync(filePath).isFile();+ } catch {+ return false;+ }+}++/**+ * Absolute paths of `names` found on PATH, minus WSL bash launchers.+ *+ * Earlier names win over later ones, then PATH order decides, so `bash` is+ * preferred to `sh` wherever each sits. A name without an extension matches+ * .com/.exe, as a bare spawn would. Off Windows the names are returned as+ * given, leaving lookup to the platform.+ */+function resolveWindowsBashCandidates(names, options = {}) {+ const env = options.env || process.env;+ const platform = options.platform || process.platform;+ if (platform !== 'win32') return [...names];++ const dirs = String(readEnv(env, 'PATH') || '').split(';').filter(Boolean);+ const found = [];+ const seen = new Set();+ for (const name of names) {+ const fileNames = path.extname(name) ? [name] : [`${name}.com`, `${name}.exe`];+ for (const dir of dirs) {+ for (const fileName of fileNames) {+ const candidate = path.join(dir, fileName);+ const key = candidate.toLowerCase();+ if (seen.has(key) || !isFile(candidate) || isWslBashLauncher(candidate, env)) continue;+ seen.add(key);+ found.push(candidate);+ }+ }+ }+ return found;+}++module.exports = { isWslBashLauncher, resolveWindowsBashCandidates };diff --git a/tests/hooks/plugin-hook-bootstrap.test.js b/tests/hooks/plugin-hook-bootstrap.test.jsindex e1ec6529d..3b3153efb 100644--- a/tests/hooks/plugin-hook-bootstrap.test.js+++ b/tests/hooks/plugin-hook-bootstrap.test.js@@ -14,6 +14,7 @@ const SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'plugin-hookconst LIFECYCLE_SCRIPT = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'lifecycle-hook-bootstrap.js');const { normalizePluginRootForPlatform, withComparisonInput } = require(SCRIPT);const { resolveTimeout } = require(LIFECYCLE_SCRIPT);+const { resolveWindowsBashCandidates } = require('../../scripts/lib/windows-bash');function createTempDir() {return fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-hook-bootstrap-'));@@ -464,6 +465,43 @@ process.exit(7);cleanup(root);}})) passed++; else failed++;++ const [nativeBash] = resolveWindowsBashCandidates(['bash.exe']);+ if (nativeBash && process.env.SystemRoot) {+ if (test('shell mode runs .sh with native bash when the System32 WSL launcher is earlier on PATH', () => {+ const root = createTempDir();+ try {+ writeFile(root, path.join('scripts', 'hook.sh'), [+ 'input=$(cat)',+ 'printf "sh:%s:%s" "$1" "$input"',+ '',+ ].join('\n'));++ // A bare `bash.exe` resolves to System32\bash.exe here, which starts+ // WSL and cannot open the Windows script path (exit 127).+ const result = run(['shell', path.join('scripts', 'hook.sh'), 'arg'], {+ root,+ input: 'payload',+ env: {+ BASH: '',+ PATH: [+ `${process.env.SystemRoot}\\System32\\WindowsPowerShell\\v1.0`,+ `${process.env.SystemRoot}\\System32`,+ path.dirname(nativeBash),+ ].join(';'),+ },+ });++ assert.strictEqual(result.status, 0, result.stderr);+ assert.strictEqual(result.stdout, 'sh:arg:payload');+ } finally {+ cleanup(root);+ }+ })) passed++; else failed++;+ } else {+ skipped += 1;+ console.log(' SKIP 1 Windows WSL-launcher test: no native bash.exe on PATH');+ }}}diff --git a/tests/lib/windows-bash.test.js b/tests/lib/windows-bash.test.jsnew file mode 100644index 000000000..ae1cd7315--- /dev/null+++ b/tests/lib/windows-bash.test.js@@ -0,0 +1,115 @@+/**+ * Tests for scripts/lib/windows-bash.js+ *+ * Platform-independent: the Windows lookup is driven by an injected platform+ * and env over a temp tree laid out like a Windows install.+ *+ * Run with: node tests/lib/windows-bash.test.js+ */++'use strict';++const assert = require('assert');+const fs = require('fs');+const os = require('os');+const path = require('path');++const { isWslBashLauncher, resolveWindowsBashCandidates } = require('../../scripts/lib/windows-bash');++let passed = 0;+let failed = 0;++function test(name, fn) {+ try {+ fn();+ console.log(` ✓ ${name}`);+ passed++;+ } catch (error) {+ console.log(` ✗ ${name}`);+ console.log(` Error: ${error.message}`);+ failed++;+ }+}++function touch(dir, name) {+ fs.mkdirSync(dir, { recursive: true });+ const filePath = path.join(dir, name);+ fs.writeFileSync(filePath, '');+ return filePath;+}++console.log('\n=== Testing windows-bash ===\n');++const root = fs.mkdtempSync(path.join(os.tmpdir(), 'windows-bash-'));+const windowsDir = path.join(root, 'Windows');+const localAppData = path.join(root, 'Local');+const system32 = path.join(windowsDir, 'System32');+const windowsApps = path.join(localAppData, 'Microsoft', 'WindowsApps');+const gitBin = path.join(root, 'Git', 'usr', 'bin');+const toolsBin = path.join(root, 'tools');++touch(system32, 'bash.exe');+touch(windowsApps, 'bash.exe');+const gitBash = touch(gitBin, 'bash.exe');+const gitSh = touch(gitBin, 'sh.exe');+const toolsSh = touch(toolsBin, 'sh.exe');++// The WSL launchers sit ahead of Git on PATH, as on a default install.+const env = {+ PATH: [system32, windowsApps, toolsBin, gitBin].join(';'),+ SystemRoot: windowsDir,+ LOCALAPPDATA: localAppData,+};+const win32 = { env, platform: 'win32' };++try {+ test('skips System32 and WindowsApps launchers for a native bash later on PATH', () => {+ assert.deepStrictEqual(resolveWindowsBashCandidates(['bash.exe', 'bash'], win32), [gitBash]);+ });++ test('prefers earlier names over PATH order, so bash beats an earlier sh', () => {+ assert.deepStrictEqual(+ resolveWindowsBashCandidates(['bash.exe', 'bash', 'sh'], win32),+ [gitBash, toolsSh, gitSh]+ );+ });++ test('reads Windows environment names case-insensitively', () => {+ const mixedCaseEnv = {+ Path: env.PATH,+ SYSTEMROOT: windowsDir,+ LocalAppData: localAppData,+ };+ assert.deepStrictEqual(+ resolveWindowsBashCandidates(['bash'], { env: mixedCaseEnv, platform: 'win32' }),+ [gitBash]+ );+ });++ test('returns nothing when only WSL launchers or no PATH are present', () => {+ const launchersOnly = { ...env, PATH: [system32, windowsApps].join(';') };+ assert.deepStrictEqual(resolveWindowsBashCandidates(['bash'], { env: launchersOnly, platform: 'win32' }), []);+ assert.deepStrictEqual(resolveWindowsBashCandidates(['bash'], { env: {}, platform: 'win32' }), []);+ });++ test('leaves names untouched off Windows', () => {+ assert.deepStrictEqual(resolveWindowsBashCandidates(['bash', 'sh'], { env, platform: 'linux' }), ['bash', 'sh']);+ });++ test('recognises launchers in System32, SysWOW64, and Sysnative regardless of case', () => {+ for (const dir of ['SYSTEM32', 'SysWOW64', 'sysnative']) {+ assert.ok(isWslBashLauncher(path.join(windowsDir, dir, 'BASH.EXE'), env), dir);+ }+ assert.ok(isWslBashLauncher(path.join(windowsApps, 'bash.exe'), env));+ });++ test('does not flag a native bash or a non-bash binary in System32', () => {+ assert.ok(!isWslBashLauncher(gitBash, env));+ assert.ok(!isWslBashLauncher(path.join(system32, 'sh.exe'), env));+ });+} finally {+ fs.rmSync(root, { recursive: true, force: true });+}++console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);+process.exit(failed > 0 ? 1 : 0);