From 640a6bb40c4071ac0d89e50568412b23d182fee7 Mon Sep 17 00:00:00 2001 From: matheusPavaneli Date: Mon, 28 Sep 2026 15:30:50 -0300 Subject: [PATCH 1/2] feat: run under Codex, Gemini CLI and Cursor, not only Claude Code workbench's core was already agent-neutral; its edges were not. Skills called ${CLAUDE_PLUGIN_ROOT}/lib/wb.py, which only Claude Code substitutes, the hooks spoke only Claude Code's protocol, and wb run could only start claude -p (WB-61). Skills now call wb, falling back to lib/wb.py relative to the skill. The scope guard decides once in hooks.py and each agent's payload and answer shape lives in hook_agents.py: Codex's apply_patch is checked path by path, Gemini denies with decision: deny, Cursor with permission: deny. Claude Code's hook output is unchanged. wb run --agent (or run.agent) picks claude-code, codex, gemini or cursor, claude-code by default, and normalises each report into the same run.json keys. wb hooks install gemini|cursor proposes the project hook config and merges it with --write. A Codex plugin manifest and marketplace ship alongside the Claude Code one, with its own hooks/codex.json so Codex never loads the Claude-format file. --- .agents/plugins/marketplace.json | 20 +++ .codex-plugin/plugin.json | 15 +++ .workflow/tasks/WB-61.json | 11 ++ CHANGELOG.md | 29 +++++ README.md | 57 +++++++-- docs/configuration.md | 2 +- docs/execution.md | 37 +++++- hooks/codex.json | 28 +++++ lib/wb.py | 5 +- lib/wb_hook.py | 39 ++++-- lib/workbench/agent.py | 205 +++++++++++++++++++++++++++---- lib/workbench/cli/hooks.py | 132 ++++++++++++++++++++ lib/workbench/cli/run.py | 26 ++-- lib/workbench/hook_agents.py | 160 ++++++++++++++++++++++++ lib/workbench/hooks.py | 89 +++++++++----- skills/address-review/SKILL.md | 4 +- skills/draft-pr/SKILL.md | 2 +- skills/frame-product/SKILL.md | 4 +- skills/implement-change/SKILL.md | 2 +- skills/plan-change/SKILL.md | 4 +- skills/review-diff/SKILL.md | 4 +- skills/trace-incident/SKILL.md | 6 +- skills/triage-task/SKILL.md | 2 +- skills/write-commit/SKILL.md | 2 +- skills/write-handover/SKILL.md | 2 +- tests/test_hook_agents.py | 174 ++++++++++++++++++++++++++ tests/test_hooks.py | 15 +++ tests/test_hooks_cli.py | 88 +++++++++++++ tests/test_plugin.py | 35 +++++- tests/test_run.py | 125 +++++++++++++++++++ 30 files changed, 1211 insertions(+), 113 deletions(-) create mode 100644 .agents/plugins/marketplace.json create mode 100644 .codex-plugin/plugin.json create mode 100644 .workflow/tasks/WB-61.json create mode 100644 hooks/codex.json create mode 100644 lib/workbench/cli/hooks.py create mode 100644 lib/workbench/hook_agents.py create mode 100644 tests/test_hook_agents.py create mode 100644 tests/test_hooks_cli.py diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 0000000..ad21a50 --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,20 @@ +{ + "name": "workbench", + "interface": { + "displayName": "workbench" + }, + "plugins": [ + { + "name": "workbench", + "source": { + "source": "local", + "path": "./" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Productivity" + } + ] +} diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json new file mode 100644 index 0000000..7c4464a --- /dev/null +++ b/.codex-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "workbench", + "version": "1.2.0", + "description": "Ticket-to-PR development workflow: triage, plan with verified citations, implement inside the plan, review, commit, PR. Pluggable issue trackers (Jira, Azure DevOps, GitHub Issues) or a backlog in the repo, so it works with no tracker at all.", + "author": { + "name": "matheusPavaneli", + "url": "https://github.com/matheusPavaneli" + }, + "homepage": "https://github.com/matheusPavaneli/workbench", + "repository": "https://github.com/matheusPavaneli/workbench", + "license": "MIT", + "keywords": ["codex", "codex-plugin", "ai-agents", "agentic-coding", "developer-tools", "workflow", "planning", "code-review"], + "skills": "./skills/", + "hooks": "./hooks/codex.json" +} diff --git a/.workflow/tasks/WB-61.json b/.workflow/tasks/WB-61.json new file mode 100644 index 0000000..f4e98cb --- /dev/null +++ b/.workflow/tasks/WB-61.json @@ -0,0 +1,11 @@ +{ + "key": "WB-61", + "title": "Make workbench agent-agnostic, not Claude Code only", + "type": "feature", + "status": "open", + "desc": "Decouple the edges from Claude Code so skills, hooks and wb run work with other coding agents (Codex, Cursor, Gemini CLI). Coupling today: (1) skills/*/SKILL.md call ${CLAUDE_PLUGIN_ROOT}/lib/wb.py and ${CLAUDE_PLUGIN_ROOT}/shared/*; (2) hooks/hooks.json + lib/wb_hook.py + lib/workbench/hooks.py speak only the Claude Code hook protocol; (3) lib/workbench/agent.py has claude -p as the only Agent, cli/run.py hardcodes --permission-mode and the claude install hint; (4) README/docs describe it as Claude Code only. Acceptance: skills resolve wb without CLAUDE_PLUGIN_ROOT (fallback to wb on PATH / WB_ROOT) and still work in Claude Code; hook logic behind an agent-neutral interface with Claude Code as one adapter; wb run selects an agent by config (run.agent), claude-code default, at least one second adapter or a documented seam; README install section per agent; all existing tests pass, new tests for path resolution and agent selection. Non-goals: dropping Claude Code support.", + "created": "2026-09-28T17:51:08Z", + "updated": "2026-09-28T17:51:08Z", + "comments": [], + "linked": [] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 21ed7b9..bce89b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,35 @@ command's own output, and one that removes it. A `--json` payload that loses or renames a key raises its `schema` number in the same release, and `contract.VERSIONS` is asserted against the real output so it cannot drift. +## Unreleased + +workbench runs under Claude Code, OpenAI Codex, Gemini CLI and Cursor: the +same skills, the same scope guard and the same headless runner. + +### Added + +- **`wb run --agent claude-code|codex|gemini|cursor`**, or `"run": {"agent": + ...}` in the repo config. Each agent's report is normalised to the same + `run.json` keys; one it does not report is absent. **Upgrade cost:** none, + `claude-code` is the default. +- **`wb hooks install gemini|cursor [--write]`** proposes the scope guard's + entries for `.gemini/settings.json` or `.cursor/hooks.json` and, with + `--write`, merges them in, keeping every key it did not write. **Upgrade + cost:** none. +- **A Codex plugin**: `.codex-plugin/plugin.json`, `.agents/plugins/marketplace.json` + and `hooks/codex.json`, whose `PreToolUse` reads the paths out of an + `apply_patch`. **Upgrade cost:** none. +- `lib/wb_hook.py --agent NAME`; with no agent it answers as Claude Code, as + before. + +### Changed + +- **Skills call `wb`**, falling back to `../../lib/wb.py` relative to the + skill, instead of `${CLAUDE_PLUGIN_ROOT}/lib/wb.py`, which only Claude Code + substitutes. Shared references are relative to the skill too. **Upgrade + cost:** none in Claude Code, which puts the plugin's `bin/` on its shell's + PATH; elsewhere, put `bin/` on PATH. + ## 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 43eea65..181a182 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ # workbench -Ticket-to-PR development workflow skills for Claude Code, with pluggable issue -trackers (Jira Cloud, Azure DevOps, GitHub Issues, GitLab Issues, Linear, or a backlog in the repo). +Ticket-to-PR development workflow skills for coding agents -- Claude Code, +OpenAI Codex, Gemini CLI and Cursor -- with pluggable issue trackers (Jira +Cloud, Azure DevOps, GitHub Issues, GitLab Issues, Linear, or a backlog in the repo). -Ten skills, one CLI, two hooks, 1206 tests, no third-party dependencies. +Ten skills, one CLI, two hooks, four agents, 1244 tests, no third-party dependencies. ## Quickstart @@ -16,7 +17,7 @@ wb next # the one command to run now wb status # everything in flight ``` -In a Claude Code session the skills call `wb` themselves. In a terminal, put +In an agent session the skills call `wb` themselves. In a terminal, put the plugin's `bin/` on your PATH first (see [Install](#install)). ## Two design rules @@ -41,22 +42,52 @@ off standing. ## Install +Requires Python 3.9+. The same skills, CLI and scope guard serve every agent; +what differs is how each one loads them. + +| Agent | Skills | Scope guard (hooks) | `wb run` | +|---|---|---|---| +| Claude Code | plugin | plugin (`hooks/hooks.json`) | `--agent claude-code` (default) | +| Codex | plugin | plugin (`hooks/codex.json`) | `--agent codex` | +| Gemini CLI | `.agents/skills/` | `wb hooks install gemini --write` | `--agent gemini` | +| Cursor | `.agents/skills/` | `wb hooks install cursor --write` | `--agent cursor` | + +**Claude Code** + ``` /plugin marketplace add matheusPavaneli/workbench /plugin install workbench@workbench ``` -`wb` is `python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py"`. Requires Python 3.9+. +**Codex** reads the repo's `.agents/plugins/marketplace.json` and the +`.codex-plugin/plugin.json` manifest: add this repo as a plugin marketplace +in Codex and install `workbench` from it. Its hooks are `hooks/codex.json`, so +Codex never loads the Claude-format `hooks/hooks.json`. + +**Gemini CLI and Cursor** load skills from `.agents/skills/` (one repo) or +`~/.agents/skills/` (every repo), and hooks from the project. From a clone: + +```sh +cp -r skills/* ~/.agents/skills/ # or link them, to follow upgrades +wb hooks install gemini --write # or: cursor -- merges into .gemini/settings.json / .cursor/hooks.json +``` + +`wb hooks install` proposes first and writes only with `--write`; it keeps every +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. -Skills call it by that path. To type `wb` in a terminal, put the plugin's `bin/` -directory on PATH: it holds `wb` (sh) and `wb.cmd` (Windows), both running the -same `lib/wb.py`. From a clone: +**`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` +(sh) and `wb.cmd` (Windows), both running the same `lib/wb.py`. Claude Code puts +it there for its shell tool on its own. From a clone: ```sh export PATH="$PWD/bin:$PATH" # PowerShell: $env:Path = "$PWD\bin;$env:Path" ``` -For the installed plugin, use the directory Claude Code installed it into. +For an installed plugin, use the directory the agent installed it into. ### One pass to a working setup @@ -384,6 +415,11 @@ being written, both stay silent. `"hooks": "strict"` makes `Stop` block instead of report. `WB_NO_HOOKS=1` or `"hooks": false` turns both off. +The decision is made once, in `lib/workbench/hooks.py`; each agent's protocol +-- which tool writes a file, how a refusal is spelled -- is an adapter in +`lib/workbench/hook_agents.py`. Codex's `apply_patch` is held to the plan path +by path, and a patch touching one unplanned file is refused whole. + ## Quality presets The preset sets the bar a plan must clear. It never lowers the floor: a unit test @@ -453,7 +489,8 @@ wb doctor everything that has to be true, in one pass wb start KEY [--refresh] read the ticket, branch for it, route it: one command to pick up work wb finish KEY -m MESSAGE [--commit] light path: every check against the real change, then the commit (or its command) wb approve [KEY] [TOKEN] show the one decision waiting on you, or approve exactly it by its token -wb run KEY [--until commit|pr] drive it headless through Claude Code, stopping at every decision (off by default) +wb run KEY [--until commit|pr] [--agent NAME] drive it headless, stopping at every decision (off by default) +wb hooks install gemini|cursor [--write] put the scope guard into an agent's project config wb route [KEY] the steps this change actually needs wb next [KEY] the single command to run now wb status [KEY] | --stats where work stands, and what to run next diff --git a/docs/configuration.md b/docs/configuration.md index 5b8d4e2..2cfeb1f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -91,7 +91,7 @@ drops another. | `execute` | by hand | `false` refuses every `--execute`, standing | | `light_max_lines` | by hand | the most estimated lines changed a plan may have and stay on the light tier; 100 when absent | | `light_path` | by hand | `false` puts every ticket on the standard route: `wb start` stops offering the light path, and `wb finish` moves a ticket already on it to the standard route; on when absent | -| `run` | by hand | `{"enabled": true}` turns `wb run` on for this repo (`WB_RUN=1` does for one call); `"permission_mode"` is passed to each `claude` session, `acceptEdits` when absent; off when absent | +| `run` | by hand | `{"enabled": true}` turns `wb run` on for this repo (`WB_RUN=1` does for one call); `"agent"` picks the agent it drives (`claude-code`, `codex`, `gemini`, `cursor`; `claude-code` when absent, `--agent` overrides it); `"permission_mode"` is passed to each Claude Code session, `acceptEdits` when absent; off when absent | | `hooks` | by hand | `false` turns the plugin's hooks off; `"strict"` makes the stop hook block | | `field_map` | by hand | custom tracker fields this repo wants read, by destination | | `generated` | by hand | globs of generated code (`["src/gen/**"]`) that follow a planned change through the scope guard unlisted; none when absent | diff --git a/docs/execution.md b/docs/execution.md index 3fe8a42..fe06f9b 100644 --- a/docs/execution.md +++ b/docs/execution.md @@ -234,9 +234,22 @@ time are appended to `.workflow/KEY/run.json`. At most `--max-sessions` (default 4) per call, each within `--timeout` seconds (default 1800). The agent sits behind one interface (`workbench.agent`): run a session on a -prompt in a checkout, within a time limit, and report how it ended. Claude -Code (`claude -p --output-format json`) is the only implementation; `--model`, -`--permission-mode`, `--plugin-dir` and `--setting-sources` pass through to it. It is off by +prompt in a checkout, within a time limit, and report how it ended. +`--agent` (or `"run": {"agent": ...}`) picks the implementation, `claude-code` +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` | +| `cursor` | `agent -p --output-format json --force --workspace ` | one JSON object | + +Each report is normalised to the same keys (`session_id`, `num_turns`, +`usage`, `total_cost_usd`, `is_error`); one an agent does not report is absent, +never guessed. `--model` goes to every agent; `--permission-mode`, +`--plugin-dir` and `--setting-sources` are Claude Code's and are not passed to +another. It is off by default: `"run": {"enabled": true}` in `.workflow/config.json`, or `WB_RUN=1` for one call. An autopilot over an expensive flow spends faster, and a headless session is where a stop nobody sees would hide. @@ -341,11 +354,23 @@ Forward slashes work everywhere and are the simpler choice. ## Hooks -`hooks/hooks.json` registers two Claude Code hooks. The decisions live in -`lib/workbench/hooks.py`; `lib/wb_hook.py` only reads the event from stdin -(1 MiB at most) and prints the answer. It is kept out of `wb` so that a hook +Two hooks, one decision. `lib/workbench/hooks.py` decides (`guard_edit`, +`check_stop`) in terms of paths and messages; `lib/workbench/hook_agents.py` +reads each agent's payload and spells its answer; `lib/wb_hook.py +[--agent NAME] ` only reads the event from stdin (1 MiB at +most) and prints the answer, Claude Code's when no agent is named. It is kept out of `wb` so that a hook firing on every edit does not fill the command history `--stats` reads. +| Agent | Registered by | Edit tools | Refusal | Stop, strict | +|---|---|---|---|---| +| Claude Code | `hooks/hooks.json` | `Edit`, `Write`, `MultiEdit`, `NotebookEdit` | `hookSpecificOutput` deny | `decision: block`, once | +| Codex | `hooks/codex.json` | `apply_patch` (paths read from the patch), `Edit`, `Write` | `hookSpecificOutput` deny | `decision: block`, once | +| Gemini CLI | `wb hooks install gemini` | `write_file`, `replace` | `decision: deny` | `AfterAgent` deny, once | +| Cursor | `wb hooks install cursor` | `Write` | `permission: deny` | one `followup_message`; Cursor's stop cannot block | + +Cursor refuses a tool call whose hook answer does not match its schema, so on +an internal error the Cursor adapter prints nothing and reports on stderr. + **The active ticket is the one the branch names**, among tickets with artifacts. `wb next` falls back to the most recently touched ticket; a hook that refuses edits must not, or a checkout on `main` would be held to last diff --git a/hooks/codex.json b/hooks/codex.json new file mode 100644 index 0000000..7082ab5 --- /dev/null +++ b/hooks/codex.json @@ -0,0 +1,28 @@ +{ + "description": "workbench for Codex: refuse edits outside the active ticket's audited plan, and report unverified work at stop", + "hooks": { + "PreToolUse": [ + { + "matcher": "apply_patch|Edit|Write", + "hooks": [ + { + "type": "command", + "command": "python \"${PLUGIN_ROOT}/lib/wb_hook.py\" --agent codex pre-tool-use", + "timeout": 15 + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "python \"${PLUGIN_ROOT}/lib/wb_hook.py\" --agent codex stop", + "timeout": 60 + } + ] + } + ] + } +} diff --git a/lib/wb.py b/lib/wb.py index f54408f..ac20715 100644 --- a/lib/wb.py +++ b/lib/wb.py @@ -3,7 +3,8 @@ Invoked as: - python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" [flags] + wb [flags] # bin/ on PATH + python "/lib/wb.py" [flags] The surface is deliberately closed. There is no free-text query flag -- no --jql, no --wiql, no --fields, no --url -- because a free-text flag is an @@ -34,6 +35,7 @@ from workbench.cli import finish as finish_cli # noqa: E402 from workbench.cli import flow as flow_cli # noqa: E402 from workbench.cli import git as git_cli # noqa: E402 +from workbench.cli import hooks as hooks_cli # noqa: E402 from workbench.cli import impl as impl_cli # noqa: E402 from workbench.cli import init as init_cli # noqa: E402 from workbench.cli import next as next_cli # noqa: E402 @@ -57,6 +59,7 @@ "finish": finish_cli, "approve": approve_cli, "run": run_cli, + "hooks": hooks_cli, "status": status_cli, "next": next_cli, "route": route_cli, diff --git a/lib/wb_hook.py b/lib/wb_hook.py index f8cf306..8f6bf32 100644 --- a/lib/wb_hook.py +++ b/lib/wb_hook.py @@ -1,9 +1,13 @@ -"""Entry point for the Claude Code hooks in hooks/hooks.json. +"""Entry point for every agent's hooks: hooks/hooks.json (Claude Code), +hooks/codex.json (Codex), and what ``wb hooks install`` writes for Gemini CLI +and Cursor. - python "${CLAUDE_PLUGIN_ROOT}/lib/wb_hook.py" + python "/lib/wb_hook.py" [--agent ] -Thin on purpose: the decisions live in ``workbench.hooks``, where they are -tested. This reads the event from stdin, prints the answer as JSON (or nothing, +With no ``--agent`` it speaks Claude Code's protocol, as it always has. + +Thin on purpose: the decisions live in ``workbench.hooks`` and each agent's +protocol in ``workbench.hook_agents``, where they are tested. This reads the event from stdin, prints the answer as JSON (or nothing, which lets the tool call through), and always exits 0. Kept out of ``wb``: a hook fires on every edit, and routing it through the CLI @@ -25,11 +29,21 @@ MAX_PAYLOAD = 1024 * 1024 EVENTS = ("pre-tool-use", "stop") +# Agents that refuse a tool call whose hook answer does not match the event's schema. +SCHEMA_STRICT = ("cursor",) def main(argv: list[str], stdin, stdout) -> int: + name = "" + if argv[:1] == ["--agent"]: + name, argv = (argv[1] if len(argv) > 1 else ""), argv[2:] event = argv[0] if argv else "" try: + from workbench import gitctx, hook_agents + + agent = hook_agents.AGENTS.get(name or hook_agents.DEFAULT) + if agent is None: + raise ValueError(f"unknown agent {name!r}; expected one of: {', '.join(hook_agents.AGENTS)}") if event not in EVENTS: raise ValueError(f"unknown hook event {event!r}; expected one of: {', '.join(EVENTS)}") raw = stdin.read(MAX_PAYLOAD + 1) @@ -39,13 +53,18 @@ def main(argv: list[str], stdin, stdout) -> int: if not isinstance(payload, dict): raise ValueError("hook payload is not a JSON object") - from workbench import gitctx, hooks - - root = gitctx.checkout(Path(str(payload.get("cwd") or Path.cwd()))) - handler = hooks.pre_tool_use if event == "pre-tool-use" else hooks.stop - answer = handler(payload, root) + root = gitctx.checkout(Path(hook_agents.root_hint(payload) or Path.cwd())) + handler = hook_agents.pre_tool_use if event == "pre-tool-use" else hook_agents.stop + answer = handler(agent, payload, root) except Exception as exc: # noqa: BLE001 -- reported below, never swallowed - answer = {"systemMessage": f"workbench {event or 'hook'} did not run ({type(exc).__name__}: {exc}); edit allowed"} + message = f"workbench {event or 'hook'} did not run ({type(exc).__name__}: {exc}); edit allowed" + if name in SCHEMA_STRICT: + # A key outside the event's schema would refuse the edit here, so the + # report goes to stderr instead. + sys.stderr.write(message + "\n") + answer = None + else: + answer = {"systemMessage": message} if answer: stdout.write(json.dumps(answer) + "\n") diff --git a/lib/workbench/agent.py b/lib/workbench/agent.py index bb9ce33..b5e2887 100644 --- a/lib/workbench/agent.py +++ b/lib/workbench/agent.py @@ -2,10 +2,12 @@ ``wb run`` needs exactly one thing from an agent: run one session on a prompt in a checkout, within a time limit, and say what it cost and how it ended. -That is the whole seam. Claude Code is the first and only implementation; a -second agent is its own ticket, written against this interface when someone -needs it -- designing a plugin system for adapters nobody asked for would be -the expensive part of this module and the unused one. +That is the whole seam. Claude Code, Codex, Gemini CLI and Cursor implement +it, each as one non-interactive invocation of its own CLI. Every adapter +normalises its agent's report into the same keys -- ``session_id``, +``num_turns``, ``usage``, ``total_cost_usd``, ``is_error`` -- so ``run.json`` +reads the same whichever agent wrote it, and a key the agent does not report +is simply absent. This module starts a process, so it is one of the few that may (see ``tests/test_structure.py``): with no shell, an empty stdin and a timeout. @@ -18,7 +20,7 @@ import subprocess from dataclasses import dataclass, field from pathlib import Path -from typing import Protocol +from typing import Callable, Protocol DEFAULT_TIMEOUT_S = 1800 @@ -51,6 +53,7 @@ def to_dict(self) -> dict: class Adapter(Protocol): name: str + install: str def missing(self) -> str | None: """Why this agent cannot run here, or ``None``.""" @@ -70,6 +73,7 @@ class ClaudeCode: plugin_dir: str = "" setting_sources: str = "" name: str = "claude-code" + install: str = "install Claude Code: npm i -g @anthropic-ai/claude-code" def missing(self) -> str | None: return None if shutil.which("claude") else "claude is not on PATH" @@ -86,25 +90,113 @@ def argv(self, prompt: str) -> list[str]: return argv def session(self, prompt: str, root: Path, timeout_s: int) -> Session: - try: - done = subprocess.run( - self.argv(prompt), - cwd=str(root), - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - stdin=subprocess.DEVNULL, - timeout=timeout_s, - check=False, - ) - except subprocess.TimeoutExpired: - return Session(exit_code=124, timed_out=True, error=f"timed out after {timeout_s}s") - except OSError as exc: - return Session(exit_code=126, error=f"could not start claude: {exc}") - report = parse(done.stdout) - error = "" if done.returncode == 0 else (done.stderr or "").strip()[-300:] - return Session(exit_code=done.returncode, report=report, error=error) + return _session("claude", self.argv(prompt), root, timeout_s, parse) + + +@dataclass +class Codex: + """``codex exec --json``: one non-interactive session, reported as JSON lines.""" + + model: str = "" + name: str = "codex" + install: str = "install Codex: npm i -g @openai/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]: + codex = shutil.which("codex") or "codex" + argv = [codex, "exec", "--json", "--sandbox", "workspace-write"] + if self.model: + argv += ["--model", self.model] + return argv + [prompt] + + def session(self, prompt: str, root: Path, timeout_s: int) -> Session: + return _session("codex", self.argv(prompt), root, timeout_s, parse_codex) + + +@dataclass +class Gemini: + """``gemini -p --output-format json``: one headless session, edits auto-approved.""" + + model: 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]: + gemini = shutil.which("gemini") or "gemini" + argv = [gemini, "-p", prompt, "--output-format", "json", "--approval-mode", "auto_edit"] + 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) + + +@dataclass +class Cursor: + """Cursor's ``agent -p --output-format json --force``: one headless session.""" + + model: str = "" + name: str = "cursor" + install: str = "install the Cursor CLI: see https://cursor.com/docs/cli/using" + + def missing(self) -> str | None: + return None if shutil.which("agent") else "agent (the Cursor CLI) is not on PATH" + + def argv(self, prompt: str, root: Path) -> list[str]: + cursor = shutil.which("agent") or "agent" + argv = [cursor, "-p", prompt, "--output-format", "json", "--force", "--workspace", str(root)] + if self.model: + argv += ["--model", self.model] + return argv + + def session(self, prompt: str, root: Path, timeout_s: int) -> Session: + return _session("agent", self.argv(prompt, root), root, timeout_s, parse) + + +AGENTS: dict[str, type] = {"claude-code": ClaudeCode, "codex": Codex, "gemini": Gemini, "cursor": Cursor} +DEFAULT = "claude-code" + + +def select(name: str, **settings: str) -> Adapter: + """The adapter called ``name``, given only the settings it understands. + + ``permission_mode``, ``plugin_dir`` and ``setting_sources`` are Claude + Code's; another agent is never handed a flag it would reject. + """ + if name not in AGENTS: + raise ValueError(f"unknown agent {name!r}; expected one of: {', '.join(AGENTS)}") + kind = AGENTS[name] + accepted = set(getattr(kind, "__dataclass_fields__", {})) + adapter: Adapter = kind(**{key: value for key, value in settings.items() if key in accepted and value}) + return adapter + + +def _session(program: str, argv: list[str], root: Path, timeout_s: int, reader: Callable[[str], dict]) -> Session: + try: + done = subprocess.run( + argv, + cwd=str(root), + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + stdin=subprocess.DEVNULL, + timeout=timeout_s, + check=False, + ) + except subprocess.TimeoutExpired: + return Session(exit_code=124, timed_out=True, error=f"timed out after {timeout_s}s") + except OSError as exc: + return Session(exit_code=126, error=f"could not start {program}: {exc}") + report = reader(done.stdout) + error = "" if done.returncode == 0 else (done.stderr or "").strip()[-300:] + return Session(exit_code=done.returncode, report=report, error=error) def parse(stdout: str) -> dict: @@ -114,3 +206,68 @@ def parse(stdout: str) -> dict: except (TypeError, ValueError): return {} return payload if isinstance(payload, dict) else {} + + +def parse_codex(stdout: str) -> dict: + """The report in ``codex exec --json``'s event stream, or ``{}``. + + One JSON object per line: ``thread.started`` carries the id, each + ``turn.completed`` its usage, and ``turn.failed`` or ``error`` a failure. + A line that is not an object is skipped, never raised on. + """ + report: dict = {} + usage: dict = {} + turns = 0 + for line in (stdout or "").splitlines(): + try: + event = json.loads(line) + except ValueError: + continue + if not isinstance(event, dict): + continue + kind = event.get("type") + if kind == "thread.started" and event.get("thread_id"): + report["session_id"] = event["thread_id"] + elif kind == "turn.completed": + turns += 1 + _add(usage, event.get("usage")) + elif kind in ("turn.failed", "error"): + report["is_error"] = True + if turns: + report["num_turns"] = turns + if usage: + report["usage"] = usage + return report + + +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. + """ + payload = parse(stdout) + if not payload: + return {} + report: dict = {} + if payload.get("error"): + report["is_error"] = True + usage: dict = {} + stats = payload.get("stats") + models = stats.get("models") if isinstance(stats, dict) else None + if isinstance(models, dict): + for model in models.values(): + if isinstance(model, dict): + _add(usage, model.get("tokens")) + if usage: + report["usage"] = usage + return report + + +def _add(total: dict, counts: object) -> None: + """Add every whole-number count in ``counts`` into ``total``.""" + if not isinstance(counts, dict): + return + for key, value in counts.items(): + if isinstance(value, int) and not isinstance(value, bool): + total[key] = total.get(key, 0) + value diff --git a/lib/workbench/cli/hooks.py b/lib/workbench/cli/hooks.py new file mode 100644 index 0000000..3ce9c04 --- /dev/null +++ b/lib/workbench/cli/hooks.py @@ -0,0 +1,132 @@ +"""``wb hooks`` -- put the scope guard into an agent that has no plugin for it. + +Claude Code and Codex load workbench's hooks from the plugin itself +(hooks/hooks.json, hooks/codex.json). Gemini CLI and Cursor read hooks from the +project instead, so this proposes the entries for that agent's project config +and, with ``--write``, merges them in. + +It proposes and you dispose, like ``wb init``: nothing is written without +``--write``, every key it did not write is kept, and a second run replaces its +own entries rather than adding more. The command names this checkout's +``wb_hook.py`` by absolute path, so moving the checkout means running it again. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from .. import gitctx +from ..errors import ConfigError, UsageError + +ACTIONS = ["install"] +ENTRY = Path(__file__).resolve().parents[2] / "wb_hook.py" +MARK = "wb_hook.py" + +# Where each agent reads project hooks, and the entries workbench adds there. +# Gemini counts timeouts in milliseconds, Cursor in seconds. +TARGETS = { + "gemini": Path(".gemini") / "settings.json", + "cursor": Path(".cursor") / "hooks.json", +} + + +def register(subparsers: argparse._SubParsersAction) -> None: + parser = subparsers.add_parser("hooks", help="install the scope guard into Gemini CLI or Cursor for this repo") + actions = parser.add_subparsers(dest="action", metavar="{" + ",".join(ACTIONS) + "}") + install = actions.add_parser("install", help="propose this repo's hook config for an agent; --write merges it in") + install.add_argument("agent", choices=sorted(TARGETS)) + install.add_argument("--write", action="store_true", help="write the config instead of only proposing it") + + +def run(args: argparse.Namespace) -> int: + if not args.action: + raise UsageError("wb hooks needs an action", fix=[f"actions: {', '.join(ACTIONS)}"]) + return _install(args) + + +def command(agent: str, event: str) -> str: + return f'"{Path(sys.executable).as_posix()}" "{ENTRY.as_posix()}" --agent {agent} {event}' + + +def entries(agent: str) -> dict[str, list[dict]]: + """The hook entries workbench adds for ``agent``, keyed by event.""" + if agent == "gemini": + return { + "BeforeTool": [{"matcher": "write_file|replace", "hooks": [ + {"type": "command", "command": command(agent, "pre-tool-use"), "timeout": 15000}]}], + "AfterAgent": [{"hooks": [{"type": "command", "command": command(agent, "stop"), "timeout": 60000}]}], + } + return { + "preToolUse": [{"command": command(agent, "pre-tool-use"), "matcher": "Write", "timeout": 15}], + "stop": [{"command": command(agent, "stop"), "timeout": 60}], + } + + +def merge(existing: dict, agent: str) -> dict: + """``existing`` with workbench's entries for ``agent`` in place of any older ones.""" + merged = json.loads(json.dumps(existing)) + if agent == "cursor": + merged.setdefault("version", 1) + hooks = merged.get("hooks") + if hooks is None: + hooks = merged["hooks"] = {} + if not isinstance(hooks, dict): + raise ConfigError(f"'hooks' in the {agent} config is not an object; workbench will not guess how to merge it") + for event, ours in entries(agent).items(): + current = hooks.get(event) or [] + if not isinstance(current, list): + raise ConfigError(f"'hooks.{event}' in the {agent} config is not a list; workbench will not guess how to merge it") + hooks[event] = [entry for entry in current if not _ours(entry)] + ours + return merged + + +def _ours(entry: object) -> bool: + """An entry an earlier ``wb hooks install`` wrote: it runs wb_hook.py.""" + return MARK in json.dumps(entry) + + +def _install(args: argparse.Namespace) -> int: + root = gitctx.checkout() + path = root / TARGETS[args.agent] + existing: dict = {} + if path.is_file(): + try: + loaded = json.loads(path.read_text(encoding="utf-8")) + except ValueError as exc: + raise ConfigError(f"{gitctx.shown(path, root)} is not valid JSON; fix it before merging hooks into it") from exc + if not isinstance(loaded, dict): + raise ConfigError(f"{gitctx.shown(path, root)} is not a JSON object") + existing = loaded + merged = merge(existing, args.agent) + + shown = gitctx.shown(path, root) + if merged == existing: + print(f"up to date {shown}: workbench's {args.agent} hooks are already there") + _skills_note() + return 0 + + print(f"{'writing' if args.write else 'proposed'} {shown}") + print() + for line in json.dumps({"hooks": entries(args.agent)}, indent=2).splitlines(): + print(f" {line}") + print() + if not args.write: + print(f"nothing written. To apply it: wb hooks install {args.agent} --write") + _skills_note() + return 0 + + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8") + print(f"wrote {shown}; every other key in it is as it was") + _skills_note() + return 0 + + +def _skills_note() -> None: + skills = (ENTRY.parent.parent / "skills").as_posix() + bin_dir = (ENTRY.parent.parent / "bin").as_posix() + print(f"skills: copy or link {skills}/* into .agents/skills/ (this repo) or ~/.agents/skills/ (every repo)") + print(f"wb: put {bin_dir} on PATH so the skills can call it") diff --git a/lib/workbench/cli/run.py b/lib/workbench/cli/run.py index 270a250..c888bf9 100644 --- a/lib/workbench/cli/run.py +++ b/lib/workbench/cli/run.py @@ -55,9 +55,14 @@ def register(subparsers: argparse._SubParsersAction) -> None: parser.add_argument("--until", choices=GOALS, default="pr", help="stop once committed, or once the PR is drafted") parser.add_argument("--max-sessions", type=int, default=MAX_SESSIONS, metavar="N") parser.add_argument("--timeout", type=int, default=agent.DEFAULT_TIMEOUT_S, metavar="S", help="seconds per session") + parser.add_argument( + "--agent", default="", choices=["", *agent.AGENTS], metavar="NAME", + help=f"the agent to drive: {', '.join(agent.AGENTS)}; run.agent in the repo config, else {agent.DEFAULT}", + ) parser.add_argument("--model", default="", help="the agent's model; its own default when omitted") parser.add_argument( - "--permission-mode", default="", help="passed to claude; run.permission_mode in the repo config, else acceptEdits" + "--permission-mode", default="", + help="Claude Code only: run.permission_mode in the repo config, else acceptEdits", ) parser.add_argument("--plugin-dir", default="", help="load workbench from this directory in each session") parser.add_argument( @@ -83,15 +88,20 @@ def run(args: argparse.Namespace) -> int: if args.max_sessions < 1: raise UsageError("--max-sessions must be at least 1") - adapter = agent.ClaudeCode( - model=args.model, - permission_mode=args.permission_mode or _config(root).get("permission_mode") or "acceptEdits", - plugin_dir=args.plugin_dir, - setting_sources=args.setting_sources, - ) + name = args.agent or str(_config(root).get("agent") or agent.DEFAULT) + try: + adapter = agent.select( + name, + model=args.model, + permission_mode=args.permission_mode or _config(root).get("permission_mode") or "acceptEdits", + plugin_dir=args.plugin_dir, + setting_sources=args.setting_sources, + ) + except ValueError as exc: + raise ConfigError(f"wb run: {exc}", fix=[f'set "run": {{"agent": "{agent.DEFAULT}"}} in .workflow/config.json']) from exc missing = adapter.missing() if missing: - raise ConfigError(f"wb run cannot start an agent: {missing}", fix=["install Claude Code: npm i -g @anthropic-ai/claude-code"]) + raise ConfigError(f"wb run cannot start an agent: {missing}", fix=[adapter.install]) start_cli.run(argparse.Namespace(key=key, refresh=False)) record = _load(key, root) diff --git a/lib/workbench/hook_agents.py b/lib/workbench/hook_agents.py new file mode 100644 index 0000000..7556db0 --- /dev/null +++ b/lib/workbench/hook_agents.py @@ -0,0 +1,160 @@ +"""Each agent's hook protocol, around the one decision in ``workbench.hooks``. + +Claude Code, Codex, Gemini CLI and Cursor all fire a hook before a tool runs +and when the agent stops, and all read the answer as JSON on stdout. What +differs is small and mechanical, and it is all here: + +- which tool writes a file, and where its input names the path; +- how a refusal is spelled; +- how a stop is held open, and what stops that from looping. + +The decisions themselves -- which path the audited plan covers, whether the +verification still describes the code -- are made once, in ``hooks``. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +from . import hooks + +DEFAULT = "claude-code" + +# Codex edits through apply_patch; the patch text names every path it touches. +_PATCH_PATH = re.compile(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+?)\s*$", re.MULTILINE) + + +@dataclass(frozen=True) +class HookAgent: + name: str + # The paths one tool call writes, or ``None`` when it writes no file. + paths: Callable[[dict], list | None] + deny: Callable[[str], dict] + # The answer to a stop: (message, strict, payload) -> JSON, or ``None``. + hold: Callable[[str, bool, dict], dict | None] + + +def pre_tool_use(agent: HookAgent, payload: dict, root: Path) -> dict | None: + if agent.name == DEFAULT: + return hooks.pre_tool_use(payload, root) + if hooks.mode(root) == hooks.OFF: + return None + paths = agent.paths(payload) + if not paths: + return None + reason = hooks.guard_edit(paths, root) + return None if reason is None else agent.deny(reason) + + +def stop(agent: HookAgent, payload: dict, root: Path) -> dict | None: + if agent.name == DEFAULT: + return hooks.stop(payload, root) + found = hooks.check_stop(root) + if found is None: + return None + message, strict = found + return agent.hold(message, strict, payload) + + +def root_hint(payload: dict) -> str: + """The directory the agent is working in, as its payload names it.""" + if payload.get("cwd"): + return str(payload["cwd"]) + roots = payload.get("workspace_roots") + if isinstance(roots, list) and roots and isinstance(roots[0], str): + return roots[0] + return "" + + +def _input(payload: dict) -> dict: + tool_input = payload.get("tool_input") + return tool_input if isinstance(tool_input, dict) else {} + + +def _named(tools: dict[str, tuple[str, ...]]) -> Callable[[dict], list | None]: + """Paths from a tool whose input carries the path in one of ``fields``.""" + + def paths(payload: dict) -> list | None: + fields = tools.get(str(payload.get("tool_name", ""))) + if not fields: + return None + tool_input = _input(payload) + for field in fields: + if tool_input.get(field): + return [str(tool_input[field])] + return None + + return paths + + +def patch_paths(patch: str) -> list[str]: + """Every path an apply_patch body adds, updates, deletes or moves to.""" + return [match.strip() for match in _PATCH_PATH.findall(patch or "")] + + +def _codex_paths(payload: dict) -> list | None: + if str(payload.get("tool_name", "")) == "apply_patch": + tool_input = _input(payload) + body = tool_input.get("command") or tool_input.get("input") or "" + if isinstance(body, list): + body = "\n".join(str(part) for part in body) + # Patch paths are relative to the session's directory, which need not be + # the checkout root the guard resolves a bare relative path against. + here = Path(str(payload.get("cwd") or ".")) + return [str(path if Path(path).is_absolute() else here / path) for path in patch_paths(str(body))] or None + return _named({"Edit": ("file_path",), "Write": ("file_path",)})(payload) + + +def _claude_deny(reason: str) -> dict: + return { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": reason, + } + } + + +def _claude_hold(message: str, strict: bool, payload: dict) -> dict: + # stop_hook_active: this stop already follows a block, and blocking again would loop. + if strict and not payload.get("stop_hook_active"): + return {"decision": "block", "reason": message} + return {"systemMessage": message} + + +def _gemini_hold(message: str, strict: bool, payload: dict) -> dict: + # AfterAgent: deny rejects the response and retries it, once. + if strict and not payload.get("stop_hook_active"): + return {"decision": "deny", "reason": message} + return {"systemMessage": message} + + +def _cursor_hold(message: str, strict: bool, payload: dict) -> dict | None: + # Cursor's stop cannot block, only submit a follow-up; loop_count keeps it to one. + if strict and payload.get("loop_count", 0) == 0: + return {"followup_message": message} + return None + + +AGENTS: dict[str, HookAgent] = { + agent.name: agent + for agent in ( + HookAgent(DEFAULT, _named({tool: (field,) for tool, field in hooks.PATH_FIELDS.items()}), _claude_deny, _claude_hold), + HookAgent("codex", _codex_paths, _claude_deny, _claude_hold), + HookAgent( + "gemini", + _named({"write_file": ("file_path",), "replace": ("file_path",)}), + lambda reason: {"decision": "deny", "reason": reason}, + _gemini_hold, + ), + HookAgent( + "cursor", + _named({"Write": ("file_path", "path")}), + lambda reason: {"permission": "deny", "user_message": reason, "agent_message": reason}, + _cursor_hold, + ), + ) +} diff --git a/lib/workbench/hooks.py b/lib/workbench/hooks.py index ca7dd99..4a02bc7 100644 --- a/lib/workbench/hooks.py +++ b/lib/workbench/hooks.py @@ -1,4 +1,4 @@ -"""Claude Code hooks: the scope guard at the moment of the edit. +"""Agent hooks: the scope guard at the moment of the edit. ``wb impl check`` reports scope when somebody runs it, and the skill asks the agent to run it "after each step or two". A check that depends on being @@ -21,6 +21,10 @@ The active ticket is the one the **branch** names, never the most recently touched one: ``wb next`` may guess, a hook that refuses edits may not. + +The decisions (``guard_edit``, ``check_stop``) speak no agent's protocol: they +take paths and return a reason or a message. ``pre_tool_use`` and ``stop`` are +the Claude Code wrappers; every other agent's wrapper is in ``hook_agents``. """ from __future__ import annotations @@ -64,20 +68,20 @@ def active(root: Path) -> str | None: return status.key_from_branch(status.keys(root), root) -def pre_tool_use(payload: dict, root: Path) -> dict | None: - """The answer to one edit: a deny, or ``None`` to stay out of the way.""" +def guard_edit(paths: list[str], root: Path) -> str | None: + """Why an edit to ``paths`` is refused, or ``None`` to let it through.""" if mode(root) == OFF: return None - field = PATH_FIELDS.get(str(payload.get("tool_name", ""))) - tool_input = payload.get("tool_input") - if not field or not isinstance(tool_input, dict) or not tool_input.get(field): - return None - - relative = _relative(root, str(tool_input[field])) - if relative is None or relative.split("/", 1)[0].casefold() == artifacts.WORKFLOW_DIR: - # Outside the repo is not this tool's business, and the plan itself - # has to be writable or it could never be corrected. + relatives = [] + for raw in paths: + relative = _relative(root, raw) + if relative is None or relative.split("/", 1)[0].casefold() == artifacts.WORKFLOW_DIR: + # Outside the repo is not this tool's business, and the plan itself + # has to be writable or it could never be corrected. + continue + relatives.append(relative) + if not relatives: return None key = active(root) @@ -91,28 +95,28 @@ def pre_tool_use(payload: dict, root: Path) -> dict | None: why = audit.standing(report, plan) if why is not None: - return _deny( - f"{key}: the plan {why}, so no edit is covered by it. " - f"Re-run: wb sdd audit {key} -- then retry this edit." - ) + return f"{key}: the plan {why}, so no edit is covered by it. Re-run: wb sdd audit {key} -- then retry this edit." planned = _planned(plan) - if relative in planned or relative in scope.claims(key, root): - return None - if companions.reason(relative, planned, companions.generated_globs(root)): - # The same tie impl check accepts: a test, declaration, lockfile or - # generated file following a planned one. - return None - - return _deny( - f"{relative} is not in the audited plan for {key}. " - "Either leave it alone, or say why the plan was wrong and add it: " - f'wb sdd amend {key} {relative} --why "" (--new for a file to create)' - ) + claimed = scope.claims(key, root) + generated = companions.generated_globs(root) + for relative in relatives: + if relative in planned or relative in claimed: + continue + if companions.reason(relative, planned, generated): + # The same tie impl check accepts: a test, declaration, lockfile or + # generated file following a planned one. + continue + return ( + f"{relative} is not in the audited plan for {key}. " + "Either leave it alone, or say why the plan was wrong and add it: " + f'wb sdd amend {key} {relative} --why "" (--new for a file to create)' + ) + return None -def stop(payload: dict, root: Path) -> dict | None: - """A report on unverified work, or ``None`` when there is nothing to say.""" +def check_stop(root: Path) -> tuple[str, bool] | None: + """``(message, strict)`` about unverified work, or ``None`` when there is nothing to say.""" setting = mode(root) if setting == OFF: return None @@ -132,9 +136,30 @@ def stop(payload: dict, root: Path) -> dict | None: why = verify.standing(evidence, audit.digest(plan), gitctx.tree(root)) if why is None: return None + return f"{key}: planned files changed but the verification {why}. Run: wb impl verify {key}", setting == STRICT + - message = f"{key}: planned files changed but the verification {why}. Run: wb impl verify {key}" - if setting == STRICT and not payload.get("stop_hook_active"): +def pre_tool_use(payload: dict, root: Path) -> dict | None: + """Claude Code's answer to one edit: a deny, or ``None`` to stay out of the way.""" + if mode(root) == OFF: + return None + + field = PATH_FIELDS.get(str(payload.get("tool_name", ""))) + tool_input = payload.get("tool_input") + if not field or not isinstance(tool_input, dict) or not tool_input.get(field): + return None + + reason = guard_edit([str(tool_input[field])], root) + return None if reason is None else _deny(reason) + + +def stop(payload: dict, root: Path) -> dict | None: + """Claude Code's report on unverified work, or ``None`` when there is nothing to say.""" + found = check_stop(root) + if found is None: + return None + message, strict = found + if strict and not payload.get("stop_hook_active"): # stop_hook_active means this stop already follows a block: blocking # again would loop, so the second time it only reports. return {"decision": "block", "reason": message} diff --git a/skills/address-review/SKILL.md b/skills/address-review/SKILL.md index 6b63e3c..84e9780 100644 --- a/skills/address-review/SKILL.md +++ b/skills/address-review/SKILL.md @@ -6,7 +6,7 @@ description: Turns PR review comments into a triaged change list, applies the ac # address-review ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` ## Steps @@ -27,7 +27,7 @@ python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" 3. **Verify before agreeing.** A reviewer can be wrong about this codebase. Read the code the comment refers to before accepting it — - `${CLAUDE_PLUGIN_ROOT}/shared/code-search.md` — and quote the line in the + `../../shared/code-search.md` — and quote the line in the reply when you disagree. 4. **Apply the accepted changes.** Same discipline as `implement-change`: diff --git a/skills/draft-pr/SKILL.md b/skills/draft-pr/SKILL.md index 9212116..c73108b 100644 --- a/skills/draft-pr/SKILL.md +++ b/skills/draft-pr/SKILL.md @@ -6,7 +6,7 @@ description: Writes a PR title and description to .workflow//pr.md from the # draft-pr ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` This skill writes the description. Opening the PR is the user's call. diff --git a/skills/frame-product/SKILL.md b/skills/frame-product/SKILL.md index 07b653c..c4b6e62 100644 --- a/skills/frame-product/SKILL.md +++ b/skills/frame-product/SKILL.md @@ -6,7 +6,7 @@ description: Turns a feature idea into a product decision - who, which metric, w # frame-product ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` The entry here is an **idea**, not a ticket. The output is a decision someone can @@ -42,7 +42,7 @@ successful outcome. 4. **Check it against the code.** Does something similar already exist? An idea that is a config change is not a project. - `${CLAUDE_PLUGIN_ROOT}/shared/code-search.md`. + `../../shared/code-search.md`. 5. **Write `.workflow/idea-/frame.md`** with those answers, the chosen slice, and a recommendation: **build now**, **build later** (with what would diff --git a/skills/implement-change/SKILL.md b/skills/implement-change/SKILL.md index 9f94982..bb6c389 100644 --- a/skills/implement-change/SKILL.md +++ b/skills/implement-change/SKILL.md @@ -6,7 +6,7 @@ description: Executes an audited plan from .workflow//sdd.json, holding the # implement-change ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` ## Steps diff --git a/skills/plan-change/SKILL.md b/skills/plan-change/SKILL.md index 3b889c7..2b3627e 100644 --- a/skills/plan-change/SKILL.md +++ b/skills/plan-change/SKILL.md @@ -6,7 +6,7 @@ description: Turns .workflow//triage.json and the code into an audited impl # plan-change ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` ## Steps @@ -33,7 +33,7 @@ python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" codebase needs a `file:line` and the text of that line, because the audit in step 7 reopens each one. A claim you cannot cite is a question, not a fact — put it in `questions`. Search with the strongest tool available and quote - only lines you actually read: `${CLAUDE_PLUGIN_ROOT}/shared/code-search.md`. + only lines you actually read: `../../shared/code-search.md`. 5. **Find the raised bar.** `repo zones ...` with every file you plan to touch. Billing, auth, user data, migrations and secrets are held to a higher diff --git a/skills/review-diff/SKILL.md b/skills/review-diff/SKILL.md index bd34597..d333682 100644 --- a/skills/review-diff/SKILL.md +++ b/skills/review-diff/SKILL.md @@ -6,7 +6,7 @@ description: Reviews the current diff against the repo's quality preset, reporti # review-diff ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` ## Steps @@ -18,7 +18,7 @@ python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" 2. **Read the diff itself**, then read the surrounding code. A diff shows what changed, not what it broke. For anything that changes a shared contract, ask the index who calls it: - `${CLAUDE_PLUGIN_ROOT}/shared/code-search.md`. + `../../shared/code-search.md`. 3. **Settle the mechanical gates first.** `review gates` (add `--key ` so the bug-fix regression rule knows the ticket type). It reads the added lines diff --git a/skills/trace-incident/SKILL.md b/skills/trace-incident/SKILL.md index 3219d02..d62b502 100644 --- a/skills/trace-incident/SKILL.md +++ b/skills/trace-incident/SKILL.md @@ -6,7 +6,7 @@ description: Traces a production symptom to its cause and produces a minimal hot # trace-incident ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` The entry is a **symptom** — an error, an alert, a user report — not a ticket. @@ -28,7 +28,7 @@ built on a guess extends the incident. effect. `route incident-` lists it as the `mitigate` step. 3. **Trace it, do not guess it.** Follow the symptom to the code path with the - strongest search available: `${CLAUDE_PLUGIN_ROOT}/shared/code-search.md`. + strongest search available: `../../shared/code-search.md`. Then read the actual lines. Every step of the chain from symptom to cause needs a `file:line` you have read. @@ -39,7 +39,7 @@ built on a guess extends the incident. 5. **Plan the smallest fix.** `.workflow/incident-/sdd.json`, persona `incident-responder`, shape in - `${CLAUDE_PLUGIN_ROOT}/skills/plan-change/references/sdd.md`. Nothing tidied, + `../plan-change/references/sdd.md`. Nothing tidied, nothing renamed, nothing upgraded. `rollback` states the user-visible state during and after, not just "revert the commit". diff --git a/skills/triage-task/SKILL.md b/skills/triage-task/SKILL.md index e0ce44b..eafce15 100644 --- a/skills/triage-task/SKILL.md +++ b/skills/triage-task/SKILL.md @@ -9,7 +9,7 @@ All tracker access goes through one command. Never construct JQL, WIQL, URLs or field lists — the provider builds them from the resolved context. ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` ## Steps diff --git a/skills/write-commit/SKILL.md b/skills/write-commit/SKILL.md index 635657d..236e8ba 100644 --- a/skills/write-commit/SKILL.md +++ b/skills/write-commit/SKILL.md @@ -6,7 +6,7 @@ description: Writes a commit message in the repo's own convention, validated and # write-commit ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` This skill writes the message. Committing stays the user's call: the CLI prints diff --git a/skills/write-handover/SKILL.md b/skills/write-handover/SKILL.md index 2010cb6..e22356a 100644 --- a/skills/write-handover/SKILL.md +++ b/skills/write-handover/SKILL.md @@ -6,7 +6,7 @@ description: Writes the non-technical note for a support ticket - symptom, cause # write-handover ``` -python "${CLAUDE_PLUGIN_ROOT}/lib/wb.py" +wb # wb not on PATH: python /../../lib/wb.py ``` The audience is not engineering. A QA lead has to validate this without reading diff --git a/tests/test_hook_agents.py b/tests/test_hook_agents.py new file mode 100644 index 0000000..accf59a --- /dev/null +++ b/tests/test_hook_agents.py @@ -0,0 +1,174 @@ +"""WB-61: the scope guard speaks each agent's hook protocol, and decides once.""" + +from __future__ import annotations + +import io +import json +import sys +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "lib")) + +from test_hooks import HookCase, _plan # noqa: E402 + +import wb_hook # noqa: E402 +from workbench import hook_agents, hooks # noqa: E402 + +CODEX = hook_agents.AGENTS["codex"] +GEMINI = hook_agents.AGENTS["gemini"] +CURSOR = hook_agents.AGENTS["cursor"] +CLAUDE = hook_agents.AGENTS["claude-code"] + + +def _patch(*lines: str) -> dict: + body = "\n".join(["*** Begin Patch", *lines, "*** End Patch"]) + return {"tool_name": "apply_patch", "tool_input": {"command": body}} + + +class Guarded(HookCase): + def setUp(self) -> None: + super().setUp() + self.record("ABC-1", _plan()) + + def hook(self, *argv: str, payload: dict) -> dict | None: + out = io.StringIO() + self.assertEqual(0, wb_hook.main(list(argv), io.StringIO(json.dumps({**payload, "cwd": str(self.root)})), out)) + text = out.getvalue().strip() + return json.loads(text) if text else None + + +class Claude(Guarded): + def test_the_default_agent_answers_exactly_as_before(self) -> None: + payload = {"tool_name": "Edit", "tool_input": {"file_path": str(self.root / "src/other.py")}, "cwd": str(self.root)} + self.assertEqual(hooks.pre_tool_use(payload, self.root), self.hook("pre-tool-use", payload=payload)) + self.assertEqual( + hooks.pre_tool_use(payload, self.root), self.hook("--agent", "claude-code", "pre-tool-use", payload=payload) + ) + answer = self.hook("pre-tool-use", payload=payload) + self.assertEqual(["hookSpecificOutput"], list(answer)) + self.assertEqual("deny", answer["hookSpecificOutput"]["permissionDecision"]) + self.assertEqual("PreToolUse", answer["hookSpecificOutput"]["hookEventName"]) + + def test_the_neutral_guard_takes_paths_not_payloads(self) -> None: + self.assertIsNone(hooks.guard_edit(["src/checkout.py"], self.root)) + self.assertIn("src/other.py", hooks.guard_edit(["src/checkout.py", "src/other.py"], self.root)) + + def test_the_claude_stop_holds_once_then_reports(self) -> None: + with mock.patch.object(hooks, "check_stop", return_value=("unverified", True)): + self.assertEqual({"decision": "block", "reason": "unverified"}, hook_agents.stop(CLAUDE, {}, self.root)) + self.assertEqual( + {"systemMessage": "unverified"}, hook_agents.stop(CLAUDE, {"stop_hook_active": True}, self.root) + ) + + +class Codex(Guarded): + def test_a_patch_touching_an_unplanned_file_is_refused_naming_it(self) -> None: + answer = self.hook("--agent", "codex", "pre-tool-use", payload=_patch( + "*** Update File: src/checkout.py", "@@", "-a", "+b", "*** Add File: src/other.py", "+x = 3", + )) + output = answer["hookSpecificOutput"] + self.assertEqual("deny", output["permissionDecision"]) + self.assertIn("src/other.py", output["permissionDecisionReason"]) + self.assertNotIn("src/checkout.py is not", output["permissionDecisionReason"]) + + def test_a_patch_touching_only_planned_files_is_allowed(self) -> None: + self.assertIsNone( + self.hook("--agent", "codex", "pre-tool-use", payload=_patch("*** Update File: src/checkout.py", "+b")) + ) + + def test_a_move_destination_is_a_touched_path(self) -> None: + self.assertEqual( + ["src/checkout.py", "src/renamed.py"], + hook_agents.patch_paths("*** Update File: src/checkout.py\n*** Move to: src/renamed.py\n"), + ) + answer = self.hook("--agent", "codex", "pre-tool-use", payload=_patch( + "*** Update File: src/checkout.py", "*** Move to: src/renamed.py", + )) + self.assertIn("src/renamed.py", answer["hookSpecificOutput"]["permissionDecisionReason"]) + + def test_patch_paths_are_read_from_the_session_s_directory(self) -> None: + """A Codex session started in src/ writes paths relative to src/.""" + payload = {**_patch("*** Update File: checkout.py", "+b"), "cwd": str(self.root / "src")} + out = io.StringIO() + self.assertEqual(0, wb_hook.main(["--agent", "codex", "pre-tool-use"], io.StringIO(json.dumps(payload)), out)) + self.assertEqual("", out.getvalue(), "src/checkout.py is planned") + payload = {**_patch("*** Update File: other.py", "+b"), "cwd": str(self.root / "src")} + out = io.StringIO() + wb_hook.main(["--agent", "codex", "pre-tool-use"], io.StringIO(json.dumps(payload)), out) + self.assertIn("src/other.py", json.loads(out.getvalue())["hookSpecificOutput"]["permissionDecisionReason"]) + + def test_a_tool_that_writes_nothing_is_let_through(self) -> None: + self.assertIsNone( + self.hook("--agent", "codex", "pre-tool-use", payload={"tool_name": "Bash", "tool_input": {"command": "ls"}}) + ) + + def test_hooks_off_lets_every_patch_through(self) -> None: + with mock.patch.dict("os.environ", {"WB_NO_HOOKS": "1"}): + self.assertIsNone( + self.hook("--agent", "codex", "pre-tool-use", payload=_patch("*** Add File: src/other.py")) + ) + + +class Gemini(Guarded): + def test_an_unplanned_write_is_denied_with_its_reason(self) -> None: + for tool in ("write_file", "replace"): + with self.subTest(tool=tool): + answer = self.hook("--agent", "gemini", "pre-tool-use", payload={ + "tool_name": tool, "tool_input": {"file_path": str(self.root / "src/other.py")}, + }) + self.assertEqual("deny", answer["decision"]) + self.assertIn("src/other.py", answer["reason"]) + + def test_a_planned_write_is_allowed(self) -> None: + self.assertIsNone(self.hook("--agent", "gemini", "pre-tool-use", payload={ + "tool_name": "write_file", "tool_input": {"file_path": "src/checkout.py"}, + })) + + def test_after_agent_denies_once_in_strict_mode_then_reports(self) -> None: + with mock.patch.object(hooks, "check_stop", return_value=("unverified", True)): + self.assertEqual({"decision": "deny", "reason": "unverified"}, hook_agents.stop(GEMINI, {}, self.root)) + self.assertEqual({"systemMessage": "unverified"}, hook_agents.stop(GEMINI, {"stop_hook_active": True}, self.root)) + with mock.patch.object(hooks, "check_stop", return_value=("unverified", False)): + self.assertEqual({"systemMessage": "unverified"}, hook_agents.stop(GEMINI, {}, self.root)) + + +class Cursor(Guarded): + def test_an_unplanned_write_is_denied_in_cursor_s_own_shape(self) -> None: + for field in ("file_path", "path"): + with self.subTest(field=field): + answer = self.hook("--agent", "cursor", "pre-tool-use", payload={ + "tool_name": "Write", "tool_input": {field: str(self.root / "src/other.py")}, + }) + self.assertEqual("deny", answer["permission"]) + self.assertIn("src/other.py", answer["agent_message"]) + + def test_a_write_with_no_path_it_can_read_is_allowed(self) -> None: + self.assertIsNone(self.hook("--agent", "cursor", "pre-tool-use", payload={ + "tool_name": "Write", "tool_input": {"contents": "x"}, + })) + + def test_the_workspace_root_stands_in_for_cwd(self) -> None: + payload = {"tool_name": "Write", "tool_input": {"file_path": "src/other.py"}, "workspace_roots": [str(self.root)]} + self.assertEqual(str(self.root), hook_agents.root_hint(payload)) + + def test_stop_follows_up_once_in_strict_mode_and_is_silent_otherwise(self) -> None: + with mock.patch.object(hooks, "check_stop", return_value=("unverified", True)): + self.assertEqual({"followup_message": "unverified"}, hook_agents.stop(CURSOR, {"loop_count": 0}, self.root)) + self.assertIsNone(hook_agents.stop(CURSOR, {"loop_count": 1}, self.root)) + with mock.patch.object(hooks, "check_stop", return_value=("unverified", False)): + self.assertIsNone(hook_agents.stop(CURSOR, {"loop_count": 0}, self.root)) + + def test_an_internal_error_prints_nothing_cursor_would_read_as_a_refusal(self) -> None: + out, err = io.StringIO(), io.StringIO() + with mock.patch.object(sys, "stderr", err): + self.assertEqual(0, wb_hook.main(["--agent", "cursor", "pre-tool-use"], io.StringIO("[1]"), out)) + self.assertEqual("", out.getvalue()) + self.assertIn("edit allowed", err.getvalue()) + + +class Unknown(Guarded): + def test_an_unknown_agent_is_reported_and_the_edit_allowed(self) -> None: + answer = self.hook("--agent", "vim", "pre-tool-use", payload={"tool_name": "Edit", "tool_input": {}}) + self.assertIn("unknown agent 'vim'", answer["systemMessage"]) + self.assertIn("edit allowed", answer["systemMessage"]) diff --git a/tests/test_hooks.py b/tests/test_hooks.py index de9c84c..96b24e4 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -296,6 +296,21 @@ def test_every_hook_calls_the_entry_point_through_the_plugin_root(self) -> None: with self.subTest(event=event): self.assertEqual("command", hook["type"]) self.assertIn('"${CLAUDE_PLUGIN_ROOT}/lib/wb_hook.py"', hook["command"]) + self.assertNotIn("--agent", hook["command"], "Claude Code is the default; its command stays as it was") + self.assertIn("timeout", hook) + + def test_codex_calls_the_entry_point_through_its_own_plugin_root(self) -> None: + """WB-61: Codex substitutes ${PLUGIN_ROOT}, not ${CLAUDE_PLUGIN_ROOT}.""" + config = json.loads((ROOT / "hooks" / "codex.json").read_text(encoding="utf-8"))["hooks"] + self.assertEqual({"PreToolUse", "Stop"}, set(config)) + self.assertIn("apply_patch", config["PreToolUse"][0]["matcher"].split("|")) + expected = {"PreToolUse": "pre-tool-use", "Stop": "stop"} + for event, groups in config.items(): + for group in groups: + for hook in group["hooks"]: + with self.subTest(event=event): + self.assertIn('"${PLUGIN_ROOT}/lib/wb_hook.py" --agent codex', hook["command"]) + self.assertTrue(hook["command"].endswith(f" {expected[event]}")) self.assertIn("timeout", hook) def test_every_file_writing_tool_is_matched(self) -> None: diff --git a/tests/test_hooks_cli.py b/tests/test_hooks_cli.py new file mode 100644 index 0000000..37a3ed1 --- /dev/null +++ b/tests/test_hooks_cli.py @@ -0,0 +1,88 @@ +"""WB-61: wb hooks install proposes, merges, and never drops a key it did not write.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "lib")) + +from test_cli import run # noqa: E402 + +from workbench.cli import hooks as hooks_cli # noqa: E402 + + +class Install(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name).resolve() + subprocess.run(["git", "init", "-q", "."], cwd=str(self.root), capture_output=True, check=False) + cwd = os.getcwd() + os.chdir(self.root) + self.addCleanup(os.chdir, cwd) + + def read(self, relative: str) -> dict: + return json.loads((self.root / relative).read_text(encoding="utf-8")) + + def test_without_write_nothing_changes(self) -> None: + for agent, target in (("gemini", ".gemini/settings.json"), ("cursor", ".cursor/hooks.json")): + with self.subTest(agent=agent): + code, out, err = run("hooks", "install", agent) + self.assertEqual(0, code, out + err) + self.assertIn("nothing written", out) + self.assertFalse((self.root / target).exists()) + + def test_write_adds_workbench_and_keeps_every_other_key(self) -> None: + settings = self.root / ".gemini" / "settings.json" + settings.parent.mkdir() + foreign = {"matcher": "run_shell_command", "hooks": [{"type": "command", "command": "lint.sh"}]} + settings.write_text(json.dumps({"theme": "dark", "hooks": {"BeforeTool": [foreign]}}), encoding="utf-8") + + code, out, err = run("hooks", "install", "gemini", "--write") + self.assertEqual(0, code, out + err) + data = self.read(".gemini/settings.json") + self.assertEqual("dark", data["theme"]) + self.assertEqual(foreign, data["hooks"]["BeforeTool"][0]) + ours = data["hooks"]["BeforeTool"][1] + self.assertEqual("write_file|replace", ours["matcher"]) + self.assertIn("--agent gemini pre-tool-use", ours["hooks"][0]["command"]) + self.assertIn("--agent gemini stop", data["hooks"]["AfterAgent"][0]["hooks"][0]["command"]) + + def test_a_second_run_changes_nothing(self) -> None: + self.assertEqual(0, run("hooks", "install", "cursor", "--write")[0]) + first = (self.root / ".cursor" / "hooks.json").read_text(encoding="utf-8") + code, out, _ = run("hooks", "install", "cursor", "--write") + self.assertEqual(0, code) + self.assertIn("up to date", out) + self.assertEqual(first, (self.root / ".cursor" / "hooks.json").read_text(encoding="utf-8")) + data = json.loads(first) + self.assertEqual(1, data["version"]) + self.assertEqual(1, len(data["hooks"]["preToolUse"])) + self.assertEqual("Write", data["hooks"]["preToolUse"][0]["matcher"]) + + def test_an_older_workbench_entry_is_replaced_not_duplicated(self) -> None: + old = {"command": 'python "/moved/lib/wb_hook.py" --agent cursor stop'} + merged = hooks_cli.merge({"version": 1, "hooks": {"stop": [old, {"command": "notify.sh"}]}}, "cursor") + commands = [entry["command"] for entry in merged["hooks"]["stop"]] + self.assertEqual("notify.sh", commands[0]) + self.assertEqual(2, len(commands)) + self.assertNotIn("/moved/", commands[1]) + + def test_a_config_it_cannot_read_is_refused_not_overwritten(self) -> None: + target = self.root / ".cursor" / "hooks.json" + target.parent.mkdir() + target.write_text("{not json", encoding="utf-8") + code, _, err = run("hooks", "install", "cursor", "--write") + self.assertNotEqual(0, code) + self.assertIn("not valid JSON", err) + self.assertEqual("{not json", target.read_text(encoding="utf-8")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_plugin.py b/tests/test_plugin.py index 2e8577a..932d4ba 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -138,13 +138,18 @@ def test_skill_bodies_stay_short(self) -> None: lines = len(path.read_text(encoding="utf-8").splitlines()) self.assertLessEqual(lines, MAX_SKILL_LINES, f"{path.parent.name} is {lines} lines") - def test_skills_invoke_the_cli_through_the_plugin_root(self) -> None: - """A hardcoded path works on the author's machine and nowhere else.""" + def test_skills_invoke_the_cli_the_same_way_under_every_agent(self) -> None: + """A hardcoded path works on the author's machine and nowhere else, and + ``${CLAUDE_PLUGIN_ROOT}`` works in one agent and nowhere else. ``wb`` on + PATH works everywhere, and the fallback is relative to the skill.""" for path in _skills(): with self.subTest(skill=path.parent.name): body = path.read_text(encoding="utf-8") + self.assertNotIn("CLAUDE_PLUGIN_ROOT", body) if "wb.py" in body: - self.assertIn("${CLAUDE_PLUGIN_ROOT}", body) + self.assertIn("wb ", body) + self.assertIn("../../lib/wb.py", body) + self.assertTrue((path.parent / "../../lib/wb.py").resolve().is_file()) def test_every_command_a_skill_names_exists(self) -> None: """A SKILL.md is an instruction an agent follows, not a document a @@ -253,8 +258,26 @@ def test_every_declared_version_agrees_with_the_package(self) -> None: plugin = json.loads((ROOT / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8")) marketplace = json.loads((ROOT / ".claude-plugin" / "marketplace.json").read_text(encoding="utf-8")) + codex = json.loads((ROOT / ".codex-plugin" / "plugin.json").read_text(encoding="utf-8")) self.assertEqual(__version__, plugin["version"]) self.assertEqual(__version__, marketplace["metadata"]["version"]) + self.assertEqual(__version__, codex["version"]) + + def test_the_codex_manifest_points_at_real_components(self) -> None: + """Codex loads hooks/hooks.json when a manifest names no hooks, and that + file is Claude Code's. Naming codex.json keeps each agent on its own.""" + data = json.loads((ROOT / ".codex-plugin" / "plugin.json").read_text(encoding="utf-8")) + self.assertEqual("workbench", data["name"]) + self.assertTrue((ROOT / data["skills"]).is_dir()) + self.assertEqual("./hooks/codex.json", data["hooks"]) + self.assertTrue((ROOT / data["hooks"]).is_file()) + + def test_the_codex_marketplace_points_at_a_real_plugin(self) -> None: + data = json.loads((ROOT / ".agents" / "plugins" / "marketplace.json").read_text(encoding="utf-8")) + self.assertTrue(data["plugins"]) + for entry in data["plugins"]: + source = (ROOT / entry["source"]["path"]).resolve() + self.assertTrue((source / ".codex-plugin" / "plugin.json").is_file()) def test_the_user_agent_carries_the_package_version(self) -> None: from workbench import __version__, http @@ -295,11 +318,13 @@ def test_the_declared_version_has_been_released(self) -> None: ) def test_shared_references_exist_where_skills_point(self) -> None: - pattern = re.compile(r"\$\{CLAUDE_PLUGIN_ROOT\}/([\w./-]+\.md)") + """References are relative to the skill's own directory, the one + convention every agent that reads SKILL.md shares.""" + pattern = re.compile(r"`(\.\./[\w./-]+\.md)`") for path in _skills(): for reference in pattern.findall(path.read_text(encoding="utf-8")): with self.subTest(skill=path.parent.name, reference=reference): - self.assertTrue((ROOT / reference).is_file(), f"missing {reference}") + self.assertTrue((path.parent / reference).resolve().is_file(), f"missing {reference}") if __name__ == "__main__": diff --git a/tests/test_run.py b/tests/test_run.py index ba99c69..3ca0c8b 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -1,5 +1,7 @@ """WB-56: wb run drives a ticket headless and stops only for a person.""" +from __future__ import annotations + import json import os import sys @@ -181,5 +183,128 @@ def test_an_error_report_is_not_ok(self) -> None: self.assertTrue(agent.Session(0).ok) +class Selection(Driven): + """WB-61: the agent is a choice, Claude Code by default.""" + + def drive(self, *args: str, config: dict | None = None): + chosen: list[str] = [] + + def session(adapter, prompt, root, timeout_s): + chosen.append(adapter.name) + return self.works() + + patches = [mock.patch.object(kind, "session", autospec=True, side_effect=session) for kind in agent.AGENTS.values()] + patches += [mock.patch.object(kind, "missing", return_value=None) for kind in agent.AGENTS.values()] + if config is not None: + patches.append(mock.patch.object(run_cli, "_config", return_value=config)) + for patch in patches: + patch.start() + self.addCleanup(patch.stop) + code, out, err = run("run", "ABC-1", "--until", "commit", *args) + return code, out + err, chosen + + def test_claude_code_is_the_default(self) -> None: + code, output, chosen = self.drive() + self.assertEqual(0, code, output) + self.assertEqual(["claude-code"], chosen) + self.assertEqual("claude-code", self.record()["sessions"][0]["agent"]) + + def test_the_repo_config_picks_the_agent(self) -> None: + code, output, chosen = self.drive(config={"agent": "codex"}) + self.assertEqual(0, code, output) + self.assertEqual(["codex"], chosen) + + def test_the_flag_overrides_the_repo_config(self) -> None: + code, output, chosen = self.drive("--agent", "gemini", config={"agent": "codex"}) + self.assertEqual(0, code, output) + self.assertEqual(["gemini"], chosen) + + def test_an_unknown_agent_is_refused_naming_the_known_ones(self) -> None: + code, output, chosen = self.drive(config={"agent": "vim"}) + self.assertNotEqual(0, code) + self.assertEqual([], chosen) + self.assertIn("unknown agent 'vim'", output) + for name in agent.AGENTS: + self.assertIn(name, output) + + def test_a_missing_agent_names_its_own_install(self) -> None: + with mock.patch.object(agent.Codex, "missing", return_value="codex is not on PATH"): + code, _, err = run("run", "ABC-1", "--agent", "codex") + self.assertNotEqual(0, code) + self.assertIn("npm i -g @openai/codex", err) + self.assertNotIn("claude-code", err) + + +class OtherAdapters(unittest.TestCase): + def test_select_hands_each_agent_only_the_settings_it_takes(self) -> None: + codex = agent.select("codex", model="m", permission_mode="acceptEdits", plugin_dir="/p") + self.assertEqual("m", codex.model) + self.assertFalse(hasattr(codex, "permission_mode")) + claude = agent.select("claude-code", permission_mode="bypassPermissions") + self.assertEqual("bypassPermissions", claude.permission_mode) + with self.assertRaises(ValueError): + agent.select("vim") + + 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") + 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.assertNotIn("--model", plain) + + def test_the_codex_event_stream_becomes_the_same_report(self) -> None: + stream = chr(10).join([ + '{"type":"thread.started","thread_id":"t-1"}', + "not json", + '{"type":"turn.completed","usage":{"input_tokens":10,"cached_input_tokens":4,"output_tokens":2}}', + "[1]", + '{"type":"turn.completed","usage":{"input_tokens":5,"output_tokens":1}}', + ]) + report = agent.parse_codex(stream) + self.assertEqual("t-1", report["session_id"]) + self.assertEqual(2, report["num_turns"]) + self.assertEqual({"input_tokens": 15, "cached_input_tokens": 4, "output_tokens": 3}, report["usage"]) + self.assertTrue(agent.Session(0, report=report).ok) + + def test_a_failed_codex_turn_is_not_ok(self) -> None: + report = agent.parse_codex('{"type":"turn.failed","error":{"message":"stream ended"}}') + self.assertFalse(agent.Session(0, report=report).ok) + self.assertEqual({}, agent.parse_codex("")) + + 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]) + self.assertEqual("auto_edit", argv[argv.index("--approval-mode") + 1]) + self.assertEqual("gemini-3-pro", argv[argv.index("--model") + 1]) + + def test_gemini_token_counts_are_summed_over_its_models(self) -> None: + payload = {"response": "done", "stats": {"models": { + "a": {"tokens": {"prompt": 10, "candidates": 3, "cached": 2}}, + "b": {"tokens": {"prompt": 1, "candidates": 1}}, + }}} + report = agent.parse_gemini(json.dumps(payload)) + self.assertEqual({"prompt": 11, "candidates": 4, "cached": 2}, report["usage"]) + self.assertTrue(agent.Session(0, report=report).ok) + self.assertFalse(agent.Session(0, report=agent.parse_gemini('{"error": {"message": "quota"}}')).ok) + self.assertEqual({}, agent.parse_gemini("oops")) + + 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")) + self.assertEqual(["/bin/agent", "-p", "go", "--output-format", "json"], argv[:5]) + self.assertIn("--force", argv) + self.assertEqual(str(Path("/repo")), argv[argv.index("--workspace") + 1]) + self.assertNotIn("--model", argv) + + def test_the_cursor_result_reads_like_claude_s(self) -> None: + report = agent.parse('{"type":"result","is_error":true,"session_id":"s-9","result":"x"}') + self.assertEqual("s-9", agent.Session(0, report=report).to_dict()["session_id"]) + self.assertFalse(agent.Session(0, report=report).ok) + + if __name__ == "__main__": unittest.main() From 10c848207e9545b4b329d45b28f45b4a6a7bb59e Mon Sep 17 00:00:00 2001 From: matheusPavaneli Date: Mon, 28 Sep 2026 15:33:03 -0300 Subject: [PATCH 2/2] chore: close WB-61 in the local backlog --- .workflow/tasks/WB-61.json | 4 ++-- README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.workflow/tasks/WB-61.json b/.workflow/tasks/WB-61.json index f4e98cb..b1da78e 100644 --- a/.workflow/tasks/WB-61.json +++ b/.workflow/tasks/WB-61.json @@ -2,10 +2,10 @@ "key": "WB-61", "title": "Make workbench agent-agnostic, not Claude Code only", "type": "feature", - "status": "open", + "status": "done", "desc": "Decouple the edges from Claude Code so skills, hooks and wb run work with other coding agents (Codex, Cursor, Gemini CLI). Coupling today: (1) skills/*/SKILL.md call ${CLAUDE_PLUGIN_ROOT}/lib/wb.py and ${CLAUDE_PLUGIN_ROOT}/shared/*; (2) hooks/hooks.json + lib/wb_hook.py + lib/workbench/hooks.py speak only the Claude Code hook protocol; (3) lib/workbench/agent.py has claude -p as the only Agent, cli/run.py hardcodes --permission-mode and the claude install hint; (4) README/docs describe it as Claude Code only. Acceptance: skills resolve wb without CLAUDE_PLUGIN_ROOT (fallback to wb on PATH / WB_ROOT) and still work in Claude Code; hook logic behind an agent-neutral interface with Claude Code as one adapter; wb run selects an agent by config (run.agent), claude-code default, at least one second adapter or a documented seam; README install section per agent; all existing tests pass, new tests for path resolution and agent selection. Non-goals: dropping Claude Code support.", "created": "2026-09-28T17:51:08Z", - "updated": "2026-09-28T17:51:08Z", + "updated": "2026-09-28T18:31:53Z", "comments": [], "linked": [] } diff --git a/README.md b/README.md index 181a182..c50762e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Ticket-to-PR development workflow skills for coding agents -- Claude Code, OpenAI Codex, Gemini CLI and Cursor -- with pluggable issue trackers (Jira Cloud, Azure DevOps, GitHub Issues, GitLab Issues, Linear, or a backlog in the repo). -Ten skills, one CLI, two hooks, four agents, 1244 tests, no third-party dependencies. +Ten skills, one CLI, two hooks, four agents, 1245 tests, no third-party dependencies. ## Quickstart