review: Add a batch mode for agent reviews
PATCH v2 1/1 review: Add a batch mode for agent reviews
Agent reviews can take quite some time to run which is not ideal for interactive use. Add a command 'b4 review batch agent' which runs an agent review for everything that is currently in reviewing state, allowing users to ingest a batch of patches then review them all non-interactively. Allow this to be limited to a specific agent in case the user is working with multiple agents and wants to use them all.
A separate agent command can be supplied for this mode, allowing the user to have both interactive and non-interactive sessions, and a substitution {review_dir} is provided to make permissions management easier.
There is a plan to offer batch operations on tagged commits in the TUI but this feels like a case that's worth handling separately. As well as the particularly long runtimes compared to other things that b4 does users may also wish to do them in an isolated environment (or an environment with better connectivity for that matter) so a mechanism for running things non-interactively could be beneficial.
---
Changes in v2:
- Allow a separate command for batch mode.
- Run the batch reviews in a separate worktree, providing a substitution for the worktree.
- Remember to commit new files.
- Link to v1: https://patch.msgid.link/[email protected]
--- docs/config.rst | 38 +- docs/maintainer/review.rst | 85 +++- src/b4/command.py | 26 + src/b4/man/b4.1.rst | 13 + src/b4/review/_review.py | 23 +- src/b4/review/batch.py | 675 +++++++++++++++++++++++++ src/b4/review_tui/_review_app.py | 21 +- src/tests/test_review_batch.py | 1037 ++++++++++++++++++++++++++++++++++++++ src/tests/test_tui_review.py | 90 ++++ 9 files changed, 1999 insertions(+), 9 deletions(-)
docs/config.rst +34 -4
@@ -918,18 +918,48 @@ These settings control ``b4 review`` TUI behaviour. :term:`b4.review-agent-command` The command to invoke for AI-assisted review (triggered by the ``a`` keybinding). Both this option and :term:`b4.review-agent-prompt-path` - must be set for the agent feature to be available. + must be set for the agent feature to be available in the review TUI. + Also used by ``b4 review batch agent`` when + :term:`b4.review-agent-batch-command` is unset. + + ``{review_dir}`` in the command is replaced with the absolute review + output directory, including the tip commit SHA. b4 creates it before + starting a command that uses the placeholder. Replacement happens + after argument parsing, so paths containing spaces remain a single + argument. This works in both the review TUI and batch runs. Default: ``None`` .. versionadded:: v0.15 + :term:`b4.review-agent-batch-command` + The command to invoke for ``b4 review batch agent``. When set, it + overrides :term:`b4.review-agent-command` for batch runs only; otherwise + batch runs use :term:`b4.review-agent-command`. Configure a command that + runs without interaction and exits after completing the review. + It uses the same :term:`b4.review-agent-prompt-path` as the review TUI, + whose ``a`` keybinding continues to use :term:`b4.review-agent-command`. + + During batch runs, ``{review_dir}`` in the selected command is replaced + with the absolute ``.git/b4-review/<tip-sha>`` output directory in the + batch worktree. b4 creates that directory before invoking a command + that uses the placeholder. Replacement happens after argument parsing, + so paths containing spaces remain a single argument. For example:: + + review-agent-batch-command = codex exec --sandbox workspace-write --add-dir {review_dir} + + Default: ``None`` + + .. versionadded:: v0.17 + :term:`b4.review-agent-prompt-path` Path to a file containing the prompt to use with the review agent. Both this option and :term:`b4.review-agent-command` must be set for - the agent feature to be available. A sample prompt is included in - ``misc/agent-reviewer.md`` in the b4 source tree and can be adapted - to your project's review guidelines. + the agent feature to be available in the review TUI. Batch runs require + this option and either :term:`b4.review-agent-batch-command` or + :term:`b4.review-agent-command`. A sample prompt is included in + ``misc/agent-reviewer.md`` in the b4 source tree and can be adapted to + your project's review guidelines. Default: ``None``
docs/maintainer/review.rst +84 -1
97 lines not on this page · raw message
src/b4/command.py +26 -0
@@ -693,6 +693,32 @@ def setup_parser() -> argparse.ArgumentParser: help='Output in JSON format', ) + # b4 review batch + sp_rev_batch = rev_subparsers.add_parser( + 'batch', help='Run review operations across multiple series' + ) + batch_subparsers = sp_rev_batch.add_subparsers( + help='batch sub-command help', dest='batch_subcmd', required=True + ) + sp_batch_agent = batch_subparsers.add_parser( + 'agent', help='Run the review agent on reviewing series without agent reviews' + ) + sp_batch_agent.add_argument( + '--agent-name', + dest='agent_name', + default=None, + metavar='NAME', + help='Skip series only if an existing agent review has this exact ' + 'reviewer name (case-sensitive; default: any agent)', + ) + sp_batch_agent.add_argument( + '--dry-run', + dest='dryrun', + action='store_true', + default=False, + help='List eligible review branches without running the agent', + ) + # b4 review cron sp_rev_cron = rev_subparsers.add_parser( 'cron',
src/b4/man/b4.1.rst +13 -0
@@ -332,6 +332,19 @@ For options and their descriptions, see ``b4 review --help`` and list the series that would be cleaned up without changing the tracking database. +``b4 review batch agent [--agent-name NAME] [--dry-run]`` + Run the configured review agent on every review branch in the current + repository whose state is reviewing and which has no agent review attached. + Reviews run sequentially in a temporary worktree, leaving the current + checkout and working tree alone. Use ``--dry-run`` to list eligible branches. + With ``--agent-name NAME``, skip only series with an agent review whose stored + reviewer display name exactly matches NAME, including case. The configured + agent command still runs; this option only filters existing reviews. + Batch runs use ``b4.review-agent-batch-command`` when set, otherwise + ``b4.review-agent-command``, with the same ``b4.review-agent-prompt-path``. + The command must run without interaction and exit after completing the + review. The review TUI continues to use ``b4.review-agent-command``. + ``b4 review tui`` Launch the review TUI.
src/b4/review/_review.py +21 -2
@@ -516,6 +516,10 @@ def main(cmdargs: argparse.Namespace) -> None: cmd_show_info(cmdargs) elif cmdargs.review_subcmd == 'cron': cmd_cron(cmdargs) + elif cmdargs.review_subcmd == 'batch': + from b4.review import batch + + batch.cmd_agent(cmdargs) def get_review_branch_patch_ids(
@@ -1388,6 +1392,18 @@ def _clear_other_comments( return cleared +def get_agent_review_dir(topdir: str, tip_sha: str) -> str: + """Return the directory agent review files for *tip_sha* are read from. + + It lives under the common git directory. That is ``.git`` in an + ordinary checkout, and it is the one place every worktree of a + repository shares: a linked worktree has a ``.git`` file rather than a + directory, so an agent started in one cannot write below it. + """ + common_dir = b4.git_get_common_dir(topdir) or os.path.join(topdir, '.git') + return os.path.join(common_dir, b4.review.tracking.REVIEW_METADATA_DIR, tip_sha) + + def _integrate_agent_reviews( topdir: str, cover_text: str,
@@ -1417,7 +1433,7 @@ def _integrate_agent_reviews( return False head_sha = out.strip() - review_dir = os.path.join(topdir, '.git', 'b4-review', head_sha) + review_dir = get_agent_review_dir(topdir, head_sha) if not os.path.isdir(review_dir): return False
@@ -1449,6 +1465,7 @@ def _integrate_agent_reviews( series_reviews: Dict[str, Any] = series.setdefault('reviews', {}) entry: Dict[str, Any] = series_reviews.setdefault(reviewer_email, {}) entry['name'] = reviewer_name + entry['source'] = 'agent' old_note = entry.get('note', '') if old_note: entry['note'] = old_note + '\n\n' + series_note
@@ -1524,6 +1541,7 @@ def _integrate_agent_reviews( patch_reviews: Dict[str, Any] = patch.setdefault('reviews', {}) entry = patch_reviews.setdefault(reviewer_email, {}) entry['name'] = reviewer_name + entry['source'] = 'agent' if comments: existing_comments: List[Dict[str, Any]] = entry.setdefault('comments', []) existing_comments.extend(comments)
@@ -1541,7 +1559,8 @@ def _integrate_agent_reviews( # Save tracking — this amends the branch tip, changing its SHA so # the directory is not re-consumed on the next run. if branch: - save_tracking_ref(topdir, branch, cover_text, tracking) + if not save_tracking_ref(topdir, branch, cover_text, tracking): + raise RuntimeError(f'Unable to save agent reviews on {branch}') else: save_tracking(topdir, cover_text, tracking) logger.info(
src/b4/review/batch.py new file +675 -0
675 lines not on this page · raw message
src/b4/review_tui/_review_app.py +19 -2
@@ -2361,11 +2361,28 @@ class ReviewApp(LoreNodeShutdownMixin, CheckRunnerMixin, App[None]): f'Agent prompt file not found: {agent_prompt}', severity='error' ) return - cmdargs += [f'Read and execute the prompt from {prompt_path}'] - if not self._ensure_branch_checked_out(): return + if any('{review_dir}' in arg for arg in cmdargs): + ecode, out = b4.git_run_command(self._topdir, ['rev-parse', 'HEAD']) + if ecode != 0 or not out.strip(): + self.notify('Could not determine the review commit', severity='error') + self._restore_original_branch() + return + review_dir = b4.review.get_agent_review_dir(self._topdir, out.strip()) + try: + os.makedirs(review_dir, exist_ok=True) + except OSError as ex: + self.notify( + f'Could not create the agent review directory: {ex}', + severity='error', + ) + self._restore_original_branch() + return + cmdargs = [arg.replace('{review_dir}', review_dir) for arg in cmdargs] + cmdargs += [f'Read and execute the prompt from {prompt_path}'] + with self.suspend(): logger.info('Running review agent: %s', ' '.join(cmdargs)) try:
src/tests/test_review_batch.py new file +1037 -0
1,037 lines not on this page · raw message
src/tests/test_tui_review.py +90 -0
102 lines not on this page · raw message
---
base-commit: ce4c1158edb292caca0ce4a6087e5edecc1b0371
change-id: 20261111-batch-agent-a0fd59ffd824
Best regards,
Signature · 1 line
Mark Brown <[email protected]>