diff --git a/.workflow/tasks/WB-62.json b/.workflow/tasks/WB-62.json new file mode 100644 index 0000000..50793cf --- /dev/null +++ b/.workflow/tasks/WB-62.json @@ -0,0 +1,11 @@ +{ + "key": "WB-62", + "title": "Make the Gemini CLI adapters work on a real session", + "type": "bug", + "status": "done", + "desc": "Found testing WB-61 against Gemini CLI 0.61.0: (1) wb hooks install gemini writes \"python\" \"wb_hook.py\" ...; Gemini runs hooks through PowerShell on Windows, where a quoted command needs the & call operator, so the hook fails and the edit is allowed. (2) wb run --agent gemini exits 55 in a folder Gemini has not trusted, and in an untrusted folder Gemini ignores project hooks; GEMINI_CLI_TRUST_WORKSPACE=true fixes both. (3) headless Gemini throws on any tool that needs confirmation, and auto_edit leaves the shell needing it, so a session cannot run wb; allow exactly the wb invocation through a --policy file instead of yolo. (4) parse_gemini ignores the session_id Gemini reports.", + "created": "2026-09-28T19:40:36Z", + "updated": "2026-09-28T20:12:01Z", + "comments": [], + "linked": [] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index bce89b3..9af74ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,25 @@ same skills, the same scope guard and the same headless runner. cost:** none in Claude Code, which puts the plugin's `bin/` on its shell's PATH; elsewhere, put `bin/` on PATH. +### Fixed + +Found running the Gemini adapters against Gemini CLI 0.61.0 (WB-62). + +- **`wb hooks install gemini` on Windows** writes the command with + PowerShell's `&` call operator. Gemini runs Windows hooks in PowerShell, + where a quoted program is a string, so the guard never ran and every edit + went through. **Upgrade cost:** rerun `wb hooks install gemini --write`. +- **`wb run --agent gemini` runs at all.** It exited 55 in any folder Gemini + had not trusted; the session now runs with `GEMINI_CLI_TRUST_WORKSPACE=true`. + **Upgrade cost:** none. +- **A Gemini session can run `wb`.** Headless Gemini refuses a tool that would + ask, and `auto_edit` leaves the shell asking; a policy file now allows the + `wb` invocation and nothing else. **Upgrade cost:** none. +- **A multi-line prompt reaches Gemini and Codex whole on Windows.** It now + goes on stdin; as an argument, cmd.exe cut it at the first newline. + **Upgrade cost:** none. +- The Gemini report carries its `session_id`. + ## 1.2.0 Work in a critical zone is planned from the start, not after a finished fix, diff --git a/README.md b/README.md index c50762e..b3863ce 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,10 @@ wb hooks install gemini --write # or: cursor -- merges into .gemini/setti key it did not write, and a rerun replaces its own entries. The command it writes names this clone's `lib/wb_hook.py`, so run it again after moving the clone. Cursor's stop hook cannot block, so `"hooks": "strict"` there submits one -follow-up message instead. +follow-up message instead. Gemini loads project hooks only in a folder it +trusts: trust the repo once in an interactive `gemini`, or set +`GEMINI_CLI_TRUST_WORKSPACE=true`. On Windows it runs them through PowerShell, +so the command is written with the `&` call operator. **`wb` on PATH.** Skills call `wb`, falling back to `lib/wb.py` relative to the skill's own directory. Put the plugin's `bin/` directory on PATH: it holds `wb` diff --git a/docs/execution.md b/docs/execution.md index fe06f9b..dbfebaf 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -241,8 +241,17 @@ when neither is set: | Agent | Invocation | Report | |---|---|---| | `claude-code` | `claude -p --output-format json --permission-mode ...` | one JSON object | -| `codex` | `codex exec --json --sandbox workspace-write` | JSON lines: `thread.started`, `turn.completed` usage, `turn.failed` | -| `gemini` | `gemini -p --output-format json --approval-mode auto_edit` | one JSON object; tokens summed over `stats.models` | +| `codex` | `codex exec --json --sandbox workspace-write -`, prompt on stdin | JSON lines: `thread.started`, `turn.completed` usage, `turn.failed` | +| `gemini` | `gemini -p ... --output-format json --approval-mode auto_edit --policy `, prompt on stdin | one JSON object: `session_id`; tokens summed over `stats.models` | + +Codex and Gemini get the prompt on stdin: npm installs both as `.cmd` shims on +Windows, and cmd.exe cuts an argument at its first newline. A Gemini session +runs with `GEMINI_CLI_TRUST_WORKSPACE=true`, without which headless Gemini +exits 55 and ignores project hooks, and with a policy +(`.workflow/gemini-policy.toml`) that allows the shell to run the session's +`python ""` and nothing else: headless Gemini refuses any tool that would +ask, and `auto_edit` leaves the shell asking. `yolo` would allow every command. + | `cursor` | `agent -p --output-format json --force --workspace ` | one JSON object | Each report is normalised to the same keys (`session_id`, `num_turns`, diff --git a/lib/workbench/agent.py b/lib/workbench/agent.py index b5e2887..c3c6720 100644 --- a/lib/workbench/agent.py +++ b/lib/workbench/agent.py @@ -16,6 +16,7 @@ from __future__ import annotations import json +import os import shutil import subprocess from dataclasses import dataclass, field @@ -104,37 +105,78 @@ class Codex: def missing(self) -> str | None: return None if shutil.which("codex") else "codex is not on PATH" - def argv(self, prompt: str) -> list[str]: + def argv(self) -> list[str]: + """The prompt is read from stdin (``-``); see ``_session``.""" codex = shutil.which("codex") or "codex" argv = [codex, "exec", "--json", "--sandbox", "workspace-write"] if self.model: argv += ["--model", self.model] - return argv + [prompt] + return argv + ["-"] def session(self, prompt: str, root: Path, timeout_s: int) -> Session: - return _session("codex", self.argv(prompt), root, timeout_s, parse_codex) + return _session("codex", self.argv(), root, timeout_s, parse_codex, prompt=prompt) @dataclass class Gemini: - """``gemini -p --output-format json``: one headless session, edits auto-approved.""" + """``gemini -p --output-format json``: one headless session, edits auto-approved. + + Headless Gemini refuses any tool that would ask for confirmation, and + ``auto_edit`` leaves the shell asking -- so a session could edit files but + never run ``wb``. A policy file allows exactly the ``wb`` invocation the + prompt names, rather than ``yolo``, which would allow every command. Gemini + also runs headless only in a folder it trusts, and loads project hooks only + there; the session is told to trust the checkout ``wb run`` was started in. + """ model: str = "" + # The ``python "/wb.py"`` prefix the session prompt tells the agent to use. + wb: str = "" name: str = "gemini" install: str = "install Gemini CLI: npm i -g @google/gemini-cli" def missing(self) -> str | None: return None if shutil.which("gemini") else "gemini is not on PATH" - def argv(self, prompt: str) -> list[str]: + def argv(self, policy: Path | None = None) -> list[str]: + """The prompt is read from stdin, and ``-p`` is appended to it; see ``_session``.""" gemini = shutil.which("gemini") or "gemini" - argv = [gemini, "-p", prompt, "--output-format", "json", "--approval-mode", "auto_edit"] + argv = [gemini, "-p", GEMINI_FOLLOW, "--output-format", "json", "--approval-mode", "auto_edit"] + if policy is not None: + argv += ["--policy", str(policy)] if self.model: argv += ["--model", self.model] return argv def session(self, prompt: str, root: Path, timeout_s: int) -> Session: - return _session("gemini", self.argv(prompt), root, timeout_s, parse_gemini) + policy = None + if self.wb: + policy = root / ".workflow" / GEMINI_POLICY + policy.parent.mkdir(parents=True, exist_ok=True) + policy.write_text(gemini_policy(self.wb), encoding="utf-8") + env = {**os.environ, "GEMINI_CLI_TRUST_WORKSPACE": "true"} + return _session("gemini", self.argv(policy), root, timeout_s, parse_gemini, env, prompt=prompt) + + +GEMINI_POLICY = "gemini-policy.toml" +# Gemini appends -p to what stdin carries; -p also keeps the run headless. +GEMINI_FOLLOW = "Follow the instructions above." + + +def gemini_policy(wb: str) -> str: + """A Gemini policy allowing the shell to run ``wb`` and nothing else. + + Gemini checks each command of a chain on its own, so ``wb ... && rm -rf`` is + still refused at ``rm``. + """ + return ( + "# Written by wb run for each Gemini session: the shell may run workbench's CLI.\n" + "[[rule]]\n" + 'toolName = "run_shell_command"\n' + f"commandPrefix = {json.dumps(wb)}\n" + 'decision = "allow"\n' + "priority = 100\n" + ) @dataclass @@ -177,16 +219,29 @@ def select(name: str, **settings: str) -> Adapter: return adapter -def _session(program: str, argv: list[str], root: Path, timeout_s: int, reader: Callable[[str], dict]) -> Session: +def _session( + program: str, + argv: list[str], + root: Path, + timeout_s: int, + reader: Callable[[str], dict], + env: dict | None = None, + prompt: str = "", +) -> Session: + """Run one session. ``prompt``, when given, goes on stdin: on Windows npm + installs gemini and codex as ``.cmd`` shims, and cmd.exe cuts an argument + at its first newline, so a multi-line prompt in argv reaches the agent + truncated. Otherwise stdin is empty, never the caller's.""" try: done = subprocess.run( argv, cwd=str(root), + env=env, capture_output=True, text=True, encoding="utf-8", errors="replace", - stdin=subprocess.DEVNULL, + input=prompt, timeout=timeout_s, check=False, ) @@ -244,12 +299,14 @@ def parse_gemini(stdout: str) -> dict: """The report in ``gemini --output-format json``, or ``{}``. Token counts are summed over every model in ``stats.models``; Gemini reports - no session id and no cost, so those keys stay absent. + no cost, so that key stays absent. """ payload = parse(stdout) if not payload: return {} report: dict = {} + if payload.get("session_id"): + report["session_id"] = payload["session_id"] if payload.get("error"): report["is_error"] = True usage: dict = {} diff --git a/lib/workbench/cli/hooks.py b/lib/workbench/cli/hooks.py index 3ce9c04..51143c9 100644 --- a/lib/workbench/cli/hooks.py +++ b/lib/workbench/cli/hooks.py @@ -15,6 +15,7 @@ import argparse import json +import os import sys from pathlib import Path @@ -47,8 +48,11 @@ def run(args: argparse.Namespace) -> int: return _install(args) -def command(agent: str, event: str) -> str: - return f'"{Path(sys.executable).as_posix()}" "{ENTRY.as_posix()}" --agent {agent} {event}' +def command(agent: str, event: str, windows: bool = os.name == "nt") -> str: + line = f'"{Path(sys.executable).as_posix()}" "{ENTRY.as_posix()}" --agent {agent} {event}' + # Gemini runs hooks through PowerShell on Windows, where a quoted program + # is a string, not a command, until the call operator runs it. + return f"& {line}" if agent == "gemini" and windows else line def entries(agent: str) -> dict[str, list[dict]]: diff --git a/lib/workbench/cli/run.py b/lib/workbench/cli/run.py index c888bf9..5562966 100644 --- a/lib/workbench/cli/run.py +++ b/lib/workbench/cli/run.py @@ -96,6 +96,7 @@ def run(args: argparse.Namespace) -> int: permission_mode=args.permission_mode or _config(root).get("permission_mode") or "acceptEdits", plugin_dir=args.plugin_dir, setting_sources=args.setting_sources, + wb=f'python "{WB}"', ) except ValueError as exc: raise ConfigError(f"wb run: {exc}", fix=[f'set "run": {{"agent": "{agent.DEFAULT}"}} in .workflow/config.json']) from exc diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py index 37a3ed1..cb36f7b 100644 --- a/tests/test_hooks_cli.py +++ b/tests/test_hooks_cli.py @@ -83,6 +83,13 @@ def test_a_config_it_cannot_read_is_refused_not_overwritten(self) -> None: self.assertIn("not valid JSON", err) self.assertEqual("{not json", target.read_text(encoding="utf-8")) + def test_gemini_on_windows_calls_the_hook_through_powershell_s_call_operator(self) -> None: + """WB-62: Gemini runs Windows hooks in PowerShell, where a bare quoted + program is a string and the hook never runs.""" + self.assertTrue(hooks_cli.command("gemini", "stop", windows=True).startswith('& "')) + self.assertTrue(hooks_cli.command("gemini", "stop", windows=False).startswith('"')) + self.assertTrue(hooks_cli.command("cursor", "stop", windows=True).startswith('"')) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_run.py b/tests/test_run.py index 3ca0c8b..9d952fa 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -4,7 +4,9 @@ import json import os +import subprocess import sys +import tempfile import unittest from pathlib import Path from unittest import mock @@ -247,14 +249,32 @@ def test_select_hands_each_agent_only_the_settings_it_takes(self) -> None: def test_the_codex_command_runs_exec_with_json_and_workspace_writes(self) -> None: with mock.patch("shutil.which", return_value="/bin/codex"): - argv = agent.Codex(model="gpt-5").argv("go") - plain = agent.Codex().argv("go") + argv = agent.Codex(model="gpt-5").argv() + plain = agent.Codex().argv() self.assertEqual(["/bin/codex", "exec", "--json"], argv[:3]) self.assertEqual("workspace-write", argv[argv.index("--sandbox") + 1]) self.assertEqual("gpt-5", argv[argv.index("--model") + 1]) - self.assertEqual("go", argv[-1]) + self.assertEqual("-", argv[-1], "the prompt comes on stdin") self.assertNotIn("--model", plain) + def test_a_multi_line_prompt_reaches_gemini_and_codex_on_stdin_not_argv(self) -> None: + """WB-62: npm installs both as .cmd shims on Windows, and cmd.exe cuts an + argument at its first newline -- the real run got no JSON back.""" + prompt = "Pick up ticket ABC-1." + chr(10) + chr(10) + "Do not push." + done = subprocess.CompletedProcess([], 0, stdout="{}", stderr="") + for adapter in (agent.Gemini(), agent.Codex()): + with self.subTest(agent=adapter.name), tempfile.TemporaryDirectory() as tmp, mock.patch("shutil.which", return_value="/bin/x"), mock.patch("subprocess.run", return_value=done) as started: + adapter.session(prompt, Path(tmp), 5) + self.assertEqual(prompt, started.call_args.kwargs["input"]) + self.assertFalse(any(chr(10) in part for part in started.call_args.args[0])) + + def test_the_other_agents_get_an_empty_stdin_never_the_caller_s(self) -> None: + done = subprocess.CompletedProcess([], 0, stdout="{}", stderr="") + for adapter in (agent.ClaudeCode(), agent.Cursor()): + with self.subTest(agent=adapter.name), tempfile.TemporaryDirectory() as tmp, mock.patch("shutil.which", return_value="/bin/x"), mock.patch("subprocess.run", return_value=done) as started: + adapter.session("go", Path(tmp), 5) + self.assertEqual("", started.call_args.kwargs["input"]) + def test_the_codex_event_stream_becomes_the_same_report(self) -> None: stream = chr(10).join([ '{"type":"thread.started","thread_id":"t-1"}', @@ -276,8 +296,8 @@ def test_a_failed_codex_turn_is_not_ok(self) -> None: def test_the_gemini_command_is_headless_json_with_edits_approved(self) -> None: with mock.patch("shutil.which", return_value="/bin/gemini"): - argv = agent.Gemini(model="gemini-3-pro").argv("go") - self.assertEqual(["/bin/gemini", "-p", "go", "--output-format", "json"], argv[:5]) + argv = agent.Gemini(model="gemini-3-pro").argv() + self.assertEqual(["/bin/gemini", "-p", agent.GEMINI_FOLLOW, "--output-format", "json"], argv[:5]) self.assertEqual("auto_edit", argv[argv.index("--approval-mode") + 1]) self.assertEqual("gemini-3-pro", argv[argv.index("--model") + 1]) @@ -292,6 +312,31 @@ def test_gemini_token_counts_are_summed_over_its_models(self) -> None: self.assertFalse(agent.Session(0, report=agent.parse_gemini('{"error": {"message": "quota"}}')).ok) self.assertEqual({}, agent.parse_gemini("oops")) + def test_a_gemini_session_trusts_the_checkout_and_may_run_only_wb(self) -> None: + """WB-62: untrusted, Gemini exits 55 and ignores project hooks; with + auto_edit alone, headless Gemini refuses the shell, so wb never runs.""" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + done = subprocess.CompletedProcess([], 0, stdout='{"session_id": "g-1", "response": "ok"}', stderr="") + with mock.patch("shutil.which", return_value="/bin/gemini"), mock.patch("subprocess.run", return_value=done) as started: + session = agent.select("gemini", wb='python "/w/lib/wb.py"').session("go", root, 5) + argv = started.call_args.args[0] + env = started.call_args.kwargs["env"] + policy = root / ".workflow" / agent.GEMINI_POLICY + self.assertEqual("true", env["GEMINI_CLI_TRUST_WORKSPACE"]) + self.assertEqual(str(policy), argv[argv.index("--policy") + 1]) + self.assertEqual("auto_edit", argv[argv.index("--approval-mode") + 1]) + self.assertNotIn("yolo", argv) + text = policy.read_text(encoding="utf-8") + self.assertIn('toolName = "run_shell_command"', text) + self.assertIn('commandPrefix = "python \\"/w/lib/wb.py\\""', text) + self.assertIn('decision = "allow"', text) + self.assertEqual("g-1", session.report["session_id"]) + + def test_only_gemini_is_handed_the_wb_prefix(self) -> None: + self.assertEqual('python "/w"', agent.select("gemini", wb='python "/w"').wb) + self.assertFalse(hasattr(agent.select("codex", wb='python "/w"'), "wb")) + def test_the_cursor_command_prints_json_and_may_write(self) -> None: with mock.patch("shutil.which", return_value="/bin/agent"): argv = agent.Cursor().argv("go", Path("/repo"))