From 256a32083b57cb9fa1e57c47680e832053e6c4b6 Mon Sep 17 00:00:00 2001 From: Joshua Napoli Date: Thu, 22 Oct 2026 11:27:40 -0400 Subject: [PATCH] Run quality checks in the worktree where files were edited The Claude Code desktop app starts a session in the main checkout and then works in a git worktree. The Stop hooks ran in CLAUDE_PROJECT_DIR, so worktree edits were never checked, and unrelated failures in the main checkout were fed back to the agent, which could not fix them and looped. Group tracked files by the checkout that contains them (nearest .git entry, keeping the project's subdirectory within its repository) and run each check there. Only checkouts that still fail stay tracked. git status uses the session cwd from the hook input. Session state and toggles stay in CLAUDE_PROJECT_DIR. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 + pyproject.toml | 2 +- src/python_claude/hooks/base.py | 62 +++++++ src/python_claude/hooks/git_status_hook.py | 2 +- src/python_claude/hooks/mypy_hook.py | 59 ++++--- src/python_claude/hooks/pytest_hook.py | 42 +++-- src/python_claude/hooks/ruff_check_hook.py | 47 ++--- src/python_claude/hooks/ruff_format_hook.py | 41 +++-- tests/test_checkout.py | 186 ++++++++++++++++++++ uv.lock | 2 +- 10 files changed, 362 insertions(+), 85 deletions(-) create mode 100644 tests/test_checkout.py diff --git a/README.md b/README.md index 0006024..fa25de7 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,10 @@ When Claude is ready to stop: - Run the tests with `pytest` (only if files were edited) Note: We defer all quality checks until Claude stops to avoid changing files while Claude is working. Changing files during editing would spoil Claude's edits and force it to reread files. Quality checks only run when at least one Python file has been edited during the session. + +### Git worktrees + +Claude Code (for example, the desktop app) may start a session in the main checkout and then do its work in a git worktree. The hooks are configured, and `CLAUDE_PROJECT_DIR` points, at the main checkout, but the quality checks run in the checkout that contains each edited file. Worktrees nested inside the main checkout (such as `.claude/worktrees/`) are recognized by their own `.git` file. If the project lives in a subdirectory of its repository, the checks run in the same subdirectory of the worktree. Checkouts without edits from this session are not checked, so unrelated failures in the main checkout are not reported to the agent. Session tracking state and toggle settings stay in the main checkout's `.claude` directory. ## Installation ```bash diff --git a/pyproject.toml b/pyproject.toml index f3c7488..de0e28d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "python-claude" -version = "0.5.0" +version = "0.5.1" description = "Python hooks for Claude Code" authors = [{name = "CVector", email = "support@cvector.com"}] readme = "README.md" diff --git a/src/python_claude/hooks/base.py b/src/python_claude/hooks/base.py index 6a658c9..b2052e0 100644 --- a/src/python_claude/hooks/base.py +++ b/src/python_claude/hooks/base.py @@ -38,6 +38,37 @@ def from_stdin(cls) -> "HookInput": return cls(session_id=session_id, tool_input=tool_input, raw=data) +def _git_root(path: Path) -> Path | None: + """Find the nearest directory containing a .git entry (a directory in a main checkout, a file in a worktree).""" + for candidate in [path, *path.parents]: + if (candidate / ".git").exists(): + return candidate + return None + + +def checkout_dir(path: Path, project_dir: Path) -> Path: + """Find the directory that plays the role of project_dir in the checkout containing path. + + Claude Code may edit files in a git worktree rather than in the checkout where the session started (CLAUDE_PROJECT_DIR). Quality checks must run in the worktree, at the same relative location as the project directory within its repository. + """ + root = _git_root(path) + if root is None: + return project_dir + project_root = _git_root(project_dir) + if project_root is not None: + candidate = root / project_dir.relative_to(project_root) + if path.is_relative_to(candidate): + return candidate + return root + + +def combine_exit_codes(exit_codes: list[int]) -> int: + """Combine exit codes from several checkouts, preferring 2 so that Claude is asked to fix any failure it can act on.""" + if 2 in exit_codes: + return 2 + return next((code for code in exit_codes if code != 0), 0) + + class Hook(ABC): """Base class for Claude Code hooks.""" @@ -59,6 +90,37 @@ def project_dir(self) -> Path: self._project_dir = Path.cwd() return self._project_dir + @property + def working_dir(self) -> Path: + """Get the checkout containing the session's current working directory.""" + cwd = self.input.raw.get("cwd") + if not cwd: + return self.project_dir + return checkout_dir(Path(cwd), self.project_dir) + + def group_by_checkout(self, files: list[str]) -> dict[Path, list[str]]: + """Group edited files by the checkout that contains them.""" + groups: dict[Path, list[str]] = {} + for file_path in files: + checkout = checkout_dir(Path(file_path), self.project_dir) + groups.setdefault(checkout, []).append(file_path) + return groups + + def read_tracked_files(self, track_file: Path) -> list[str]: + """Read the files recorded in a tracking file.""" + if not track_file.exists(): + return [] + return [ + line.strip() for line in track_file.read_text().split("\n") if line.strip() + ] + + def retain_tracked_files(self, track_file: Path, files: list[str]) -> None: + """Replace the contents of a tracking file, removing it when no files remain.""" + if files: + track_file.write_text("".join(f"{file_path}\n" for file_path in files)) + else: + track_file.unlink(missing_ok=True) + @property def log_dir(self) -> Path: """Get the log directory for this session.""" diff --git a/src/python_claude/hooks/git_status_hook.py b/src/python_claude/hooks/git_status_hook.py index 31ad692..6a20922 100644 --- a/src/python_claude/hooks/git_status_hook.py +++ b/src/python_claude/hooks/git_status_hook.py @@ -18,6 +18,6 @@ def run(self) -> int: print("# git status") result = subprocess.run( ["git", "status"], - cwd=self.project_dir, + cwd=self.working_dir, ) return result.returncode diff --git a/src/python_claude/hooks/mypy_hook.py b/src/python_claude/hooks/mypy_hook.py index a4b94b7..b416467 100644 --- a/src/python_claude/hooks/mypy_hook.py +++ b/src/python_claude/hooks/mypy_hook.py @@ -4,7 +4,12 @@ import sys from pathlib import Path -from python_claude.hooks.base import Hook, HookInput +from python_claude.hooks.base import ( + Hook, + HookInput, + checkout_dir, + combine_exit_codes, +) from python_claude.hooks.state import QualityCheckState @@ -35,37 +40,45 @@ def run(self) -> int: file_path = self.input.file_path - # Determine what to type check if file_path: # File path provided - check if it's a Python file if not self.is_python_file(file_path): return 0 - mypy_target = file_path - else: - # No file path (Stop hook) - check if any Python files were edited - if not self.track_file.exists() or self.track_file.stat().st_size == 0: - self.log("No edited Python files") - return 0 - # Check entire project - mypy_target = "." + checkout = checkout_dir(Path(file_path), self.project_dir) + exit_code = self._run_mypy(file_path, checkout) + # Map mypy exit code 1 (type errors) to exit code 2 for Claude Code correction + return 2 if exit_code == 1 else exit_code + + # No file path (Stop hook) - check if any Python files were edited + files = self.read_tracked_files(self.track_file) + if not files: + self.log("No edited Python files") + return 0 + + # Check the entire project in each checkout where files were edited + exit_codes: list[int] = [] + remaining: list[str] = [] + for checkout, checkout_files in self.group_by_checkout(files).items(): + exit_code = self._run_mypy(".", checkout) + if exit_code == 1: + exit_code = 2 + if exit_code != 0: + remaining.extend(checkout_files) + exit_codes.append(exit_code) - self.log(mypy_target) + self.retain_tracked_files(self.track_file, remaining) + return combine_exit_codes(exit_codes) + + def _run_mypy(self, mypy_target: str, checkout: Path) -> int: + """Run mypy on the target in the given checkout and return its exit code.""" + self.log(f"{mypy_target} in {checkout}") # mypy writes errors to stdout, but only stderr is fed back to Claude result = subprocess.run( ["uv", "run", "mypy", mypy_target], - cwd=self.project_dir, + cwd=checkout, stdout=sys.stderr, # Redirect stdout to stderr for Claude ) - exit_code = result.returncode - self.log(f"exit {exit_code}") - - # Clean up tracking file on success (only for Stop hook) - if exit_code == 0 and not file_path: - self.track_file.unlink(missing_ok=True) - - # Map mypy exit code 1 (type errors) to exit code 2 for Claude Code correction - if exit_code == 1: - return 2 - return exit_code + self.log(f"exit {result.returncode}") + return result.returncode diff --git a/src/python_claude/hooks/pytest_hook.py b/src/python_claude/hooks/pytest_hook.py index 827ff02..a2ebcd2 100644 --- a/src/python_claude/hooks/pytest_hook.py +++ b/src/python_claude/hooks/pytest_hook.py @@ -4,7 +4,7 @@ import sys from pathlib import Path -from python_claude.hooks.base import Hook, HookInput +from python_claude.hooks.base import Hook, HookInput, combine_exit_codes from python_claude.hooks.state import QualityCheckState @@ -32,27 +32,33 @@ def run(self) -> int: self.log(f"{self.track_file}") # Check if any Python files were edited - if not self.track_file.exists() or self.track_file.stat().st_size == 0: + files = self.read_tracked_files(self.track_file) + if not files: self.log("No edited Python files") return 0 - self.log("Running pytest") + exit_codes: list[int] = [] + remaining: list[str] = [] + for checkout, checkout_files in self.group_by_checkout(files).items(): + self.log(f"Running pytest in {checkout}") - result = subprocess.run( - ["uv", "run", "pytest"], - cwd=self.project_dir, - stdout=sys.stderr, - ) + result = subprocess.run( + ["uv", "run", "pytest"], + cwd=checkout, + stdout=sys.stderr, + ) - exit_code = result.returncode - # Transform pytest exit code 1 (test failures) to exit code 2 - # for Claude Code to properly understand test failures - if exit_code == 1: - exit_code = 2 - self.log(f"exit {exit_code}") + exit_code = result.returncode + # Transform pytest exit code 1 (test failures) to exit code 2 + # for Claude Code to properly understand test failures + if exit_code == 1: + exit_code = 2 + self.log(f"exit {exit_code}") - # Clean up tracking file on success - if exit_code == 0: - self.track_file.unlink(missing_ok=True) + # Keep tracking files of checkouts that still fail + if exit_code != 0: + remaining.extend(checkout_files) + exit_codes.append(exit_code) - return exit_code + self.retain_tracked_files(self.track_file, remaining) + return combine_exit_codes(exit_codes) diff --git a/src/python_claude/hooks/ruff_check_hook.py b/src/python_claude/hooks/ruff_check_hook.py index 8323ac4..535cbcc 100644 --- a/src/python_claude/hooks/ruff_check_hook.py +++ b/src/python_claude/hooks/ruff_check_hook.py @@ -4,7 +4,7 @@ import sys from pathlib import Path -from python_claude.hooks.base import Hook, HookInput +from python_claude.hooks.base import Hook, HookInput, combine_exit_codes from python_claude.hooks.state import QualityCheckState @@ -29,37 +29,40 @@ def run(self) -> int: return 0 # Check if tracking file exists and has content - if not self.track_file.exists() or self.track_file.stat().st_size == 0: + tracked = self.read_tracked_files(self.track_file) + if not tracked: self.log("No edited Python files to check") return 0 - files: list[str] = [] - for line in self.track_file.read_text().strip().split("\n"): - file_path = line.strip() - if file_path and Path(file_path).exists(): - files.append(file_path) - + files = [file_path for file_path in tracked if Path(file_path).exists()] if not files: self.log("No existing Python files to check") self.track_file.unlink(missing_ok=True) return 0 - self.log(f"Checking {len(files)} files: {' '.join(files)}") + exit_codes: list[int] = [] + remaining: list[str] = [] + for checkout, checkout_files in self.group_by_checkout(files).items(): + self.log( + f"Checking {len(checkout_files)} files in {checkout}: {' '.join(checkout_files)}" + ) - result = subprocess.run( - ["uv", "run", "ruff", "check", "--fix", *files], - cwd=self.project_dir, - stdout=sys.stderr, - ) + result = subprocess.run( + ["uv", "run", "ruff", "check", "--fix", *checkout_files], + cwd=checkout, + stdout=sys.stderr, + ) - exit_code = result.returncode - self.log(f"exit {exit_code}") + exit_code = result.returncode + self.log(f"exit {exit_code}") - if exit_code == 0: - self.track_file.unlink(missing_ok=True) + # ruff check exit code 1 indicates a lint error that was not automatically fixed; return status 2 to signal claude to consider fixing it + if exit_code == 1: + exit_code = 2 - # ruff check exit code 1 indicates a lint error that was not automatically fixed; return status 2 to signal claude to consider fixing it - if exit_code == 1: - return 2 + if exit_code != 0: + remaining.extend(checkout_files) + exit_codes.append(exit_code) - return exit_code + self.retain_tracked_files(self.track_file, remaining) + return combine_exit_codes(exit_codes) diff --git a/src/python_claude/hooks/ruff_format_hook.py b/src/python_claude/hooks/ruff_format_hook.py index c1d33b2..3bf998b 100644 --- a/src/python_claude/hooks/ruff_format_hook.py +++ b/src/python_claude/hooks/ruff_format_hook.py @@ -4,7 +4,7 @@ import sys from pathlib import Path -from python_claude.hooks.base import Hook, HookInput +from python_claude.hooks.base import Hook, HookInput, combine_exit_codes from python_claude.hooks.state import QualityCheckState @@ -29,33 +29,36 @@ def run(self) -> int: return 0 # Check if tracking file exists and has content - if not self.track_file.exists() or self.track_file.stat().st_size == 0: + tracked = self.read_tracked_files(self.track_file) + if not tracked: self.log("No edited Python files to format") return 0 - files: list[str] = [] - for line in self.track_file.read_text().strip().split("\n"): - file_path = line.strip() - if file_path and Path(file_path).exists(): - files.append(file_path) - + files = [file_path for file_path in tracked if Path(file_path).exists()] if not files: self.log("No existing Python files to format") self.track_file.unlink(missing_ok=True) return 0 - self.log(f"Formatting {len(files)} files: {' '.join(files)}") + exit_codes: list[int] = [] + remaining: list[str] = [] + for checkout, checkout_files in self.group_by_checkout(files).items(): + self.log( + f"Formatting {len(checkout_files)} files in {checkout}: {' '.join(checkout_files)}" + ) - result = subprocess.run( - ["uv", "run", "ruff", "format", *files], - cwd=self.project_dir, - stdout=sys.stderr, - ) + result = subprocess.run( + ["uv", "run", "ruff", "format", *checkout_files], + cwd=checkout, + stdout=sys.stderr, + ) - exit_code = result.returncode - self.log(f"exit {exit_code}") + exit_code = result.returncode + self.log(f"exit {exit_code}") - if exit_code == 0: - self.track_file.unlink(missing_ok=True) + if exit_code != 0: + remaining.extend(checkout_files) + exit_codes.append(exit_code) - return exit_code + self.retain_tracked_files(self.track_file, remaining) + return combine_exit_codes(exit_codes) diff --git a/tests/test_checkout.py b/tests/test_checkout.py new file mode 100644 index 0000000..2ba4442 --- /dev/null +++ b/tests/test_checkout.py @@ -0,0 +1,186 @@ +"""Tests for running quality checks in the checkout where files were edited.""" + +import os +from pathlib import Path +from unittest.mock import MagicMock, patch + +from python_claude.hooks.base import HookInput, checkout_dir +from python_claude.hooks.git_status_hook import GitStatusHook +from python_claude.hooks.mypy_hook import MypyHook +from python_claude.hooks.pytest_hook import PytestHook +from python_claude.hooks.ruff_check_hook import RuffCheckHook +from python_claude.hooks.ruff_format_hook import RuffFormatHook + + +def make_repo(tmp_path: Path) -> tuple[Path, Path]: + """Create a main checkout with a worktree nested under .claude/worktrees, as the Claude Code desktop app does.""" + main = tmp_path / "repo" + (main / ".git").mkdir(parents=True) + (main / "src").mkdir() + (main / "src" / "main_file.py").write_text("") + worktree = main / ".claude" / "worktrees" / "feature" + (worktree / "src").mkdir(parents=True) + (worktree / ".git").write_text(f"gitdir: {main}/.git/worktrees/feature\n") + (worktree / "src" / "wt_file.py").write_text("") + return main, worktree + + +def ok() -> MagicMock: + result = MagicMock() + result.returncode = 0 + return result + + +class TestCheckoutDir: + def test_file_in_main_checkout(self, tmp_path: Path) -> None: + main, _ = make_repo(tmp_path) + assert checkout_dir(main / "src" / "main_file.py", main) == main + + def test_file_in_nested_worktree(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + assert checkout_dir(worktree / "src" / "wt_file.py", main) == worktree + + def test_file_in_new_directory(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + assert checkout_dir(worktree / "new" / "pkg" / "x.py", main) == worktree + + def test_project_in_subdirectory_of_repo(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + (main / "backend").mkdir() + (worktree / "backend").mkdir() + project = main / "backend" + assert checkout_dir(worktree / "backend" / "x.py", project) == ( + worktree / "backend" + ) + + def test_file_outside_any_repository(self, tmp_path: Path) -> None: + main, _ = make_repo(tmp_path) + assert checkout_dir(Path("/path/to/file.py"), main) == main + + +class TestStopHooksUseEditedCheckout: + def test_pytest_runs_only_in_worktree(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + hook_input = HookInput(session_id="s", tool_input={}, raw={}) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = PytestHook(hook_input) + hook.track_file.write_text(f"{worktree}/src/wt_file.py\n") + with patch("subprocess.run", return_value=ok()) as mock_run: + assert hook.run() == 0 + assert [c.kwargs["cwd"] for c in mock_run.call_args_list] == [worktree] + assert not hook.track_file.exists() + + def test_pytest_failure_keeps_only_failing_checkout_tracked( + self, tmp_path: Path + ) -> None: + main, worktree = make_repo(tmp_path) + hook_input = HookInput(session_id="s", tool_input={}, raw={}) + + def run(args: list[str], cwd: Path, **kwargs: object) -> MagicMock: + result = MagicMock() + result.returncode = 1 if cwd == worktree else 0 + return result + + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = PytestHook(hook_input) + hook.track_file.write_text( + f"{main}/src/main_file.py\n{worktree}/src/wt_file.py\n" + ) + with patch("subprocess.run", side_effect=run) as mock_run: + assert hook.run() == 2 + assert {c.kwargs["cwd"] for c in mock_run.call_args_list} == { + main, + worktree, + } + assert hook.track_file.read_text() == f"{worktree}/src/wt_file.py\n" + + def test_mypy_stop_runs_in_worktree(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + hook_input = HookInput(session_id="s", tool_input={}, raw={}) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = MypyHook(hook_input) + hook.track_file.write_text(f"{worktree}/src/wt_file.py\n") + with patch("subprocess.run", return_value=ok()) as mock_run: + assert hook.run() == 0 + mock_run.assert_called_once() + assert mock_run.call_args.args[0] == ["uv", "run", "mypy", "."] + assert mock_run.call_args.kwargs["cwd"] == worktree + + def test_mypy_single_file_runs_in_its_checkout(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + file_path = f"{worktree}/src/wt_file.py" + hook_input = HookInput( + session_id="s", tool_input={"file_path": file_path}, raw={} + ) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = MypyHook(hook_input) + with patch("subprocess.run", return_value=ok()) as mock_run: + assert hook.run() == 0 + assert mock_run.call_args.kwargs["cwd"] == worktree + + def test_ruff_format_groups_files_by_checkout(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + main_file = f"{main}/src/main_file.py" + wt_file = f"{worktree}/src/wt_file.py" + hook_input = HookInput(session_id="s", tool_input={}, raw={}) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = RuffFormatHook(hook_input) + hook.track_file.write_text(f"{main_file}\n{wt_file}\n") + with patch("subprocess.run", return_value=ok()) as mock_run: + assert hook.run() == 0 + calls = {c.kwargs["cwd"]: c.args[0] for c in mock_run.call_args_list} + assert calls == { + main: ["uv", "run", "ruff", "format", main_file], + worktree: ["uv", "run", "ruff", "format", wt_file], + } + + def test_ruff_check_runs_in_worktree(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + wt_file = f"{worktree}/src/wt_file.py" + hook_input = HookInput(session_id="s", tool_input={}, raw={}) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = RuffCheckHook(hook_input) + hook.track_file.write_text(f"{wt_file}\n") + with patch("subprocess.run", return_value=ok()) as mock_run: + assert hook.run() == 0 + mock_run.assert_called_once() + assert mock_run.call_args.args[0] == [ + "uv", + "run", + "ruff", + "check", + "--fix", + wt_file, + ] + assert mock_run.call_args.kwargs["cwd"] == worktree + + def test_session_state_stays_in_project_dir(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + hook_input = HookInput( + session_id="s", tool_input={}, raw={"cwd": str(worktree)} + ) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = PytestHook(hook_input) + assert hook.log_dir == main / ".claude" / "debug" / "sessions" / "s" + + +class TestGitStatusUsesSessionCwd: + def test_git_status_in_worktree(self, tmp_path: Path) -> None: + main, worktree = make_repo(tmp_path) + hook_input = HookInput( + session_id="s", tool_input={}, raw={"cwd": str(worktree / "src")} + ) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = GitStatusHook(hook_input) + with patch("subprocess.run", return_value=ok()) as mock_run: + hook.run() + assert mock_run.call_args.kwargs["cwd"] == worktree + + def test_git_status_without_cwd(self, tmp_path: Path) -> None: + main, _ = make_repo(tmp_path) + hook_input = HookInput(session_id="s", tool_input={}, raw={}) + with patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": str(main)}): + hook = GitStatusHook(hook_input) + with patch("subprocess.run", return_value=ok()) as mock_run: + hook.run() + assert mock_run.call_args.kwargs["cwd"] == main diff --git a/uv.lock b/uv.lock index 4cdb6bf..5250c1a 100644 --- a/uv.lock +++ b/uv.lock @@ -216,7 +216,7 @@ wheels = [ [[package]] name = "python-claude" -version = "0.5.0" +version = "0.5.1" source = { editable = "." } [package.dev-dependencies]