shareAI-lab/learn-claude-code · error · RuntimeError

Not in a git repository. worktree tools require git.

Error message

Not in a git repository. worktree tools require git.

What it means

Raised as RuntimeError by WorktreeManager._run_git() in agents/s12_worktree_task_isolation.py:252 when git_available is false — i.e. the startup probe `git rev-parse --is-inside-work-tree` (run in repo_root, 10s timeout) failed, was not executable, or raised. Every git-backed operation in the worktree toolset funnels through _run_git, so the whole worktree feature is disabled without a repo.

Source

Thrown at agents/s12_worktree_task_isolation.py:252

            self.index_path.write_text(json.dumps({"worktrees": []}, indent=2))
        self.git_available = self._is_git_repo()

    def _is_git_repo(self) -> bool:
        try:
            r = subprocess.run(
                ["git", "rev-parse", "--is-inside-work-tree"],
                cwd=self.repo_root,
                capture_output=True,
                text=True,
                timeout=10,
            )
            return r.returncode == 0
        except Exception:
            return False

    def _run_git(self, args: list[str]) -> str:
        if not self.git_available:
            raise RuntimeError("Not in a git repository. worktree tools require git.")
        r = subprocess.run(
            ["git", *args],
            cwd=self.repo_root,
            capture_output=True,
            text=True,
            timeout=120,
        )
        if r.returncode != 0:
            msg = (r.stdout + r.stderr).strip()
            raise RuntimeError(msg or f"git {' '.join(args)} failed")
        return (r.stdout + r.stderr).strip() or "(no output)"

    def _load_index(self) -> dict:
        return json.loads(self.index_path.read_text())

    def _save_index(self, data: dict):
        self.index_path.write_text(json.dumps(data, indent=2))

View on GitHub (pinned to 985456f4ad)

Solutions

  1. Run the agent from inside a git repository: `git init` (and make an initial commit) in the workspace, or cd into the real repo
  2. Verify with `git rev-parse --is-inside-work-tree` in the same directory the harness uses as repo_root
  3. Ensure git is installed and on PATH for the harness user (`git --version`)
  4. If the filesystem stalls the probe, investigate the mount; do not raise the 10s timeout blindly

Example fix

# before
$ cd /tmp/scratch && python -m agents.s12_worktree_task_isolation
# worktree_create -> RuntimeError: Not in a git repository...

# after
$ cd /tmp/scratch && git init && git commit --allow-empty -m init
$ python -m agents.s12_worktree_task_isolation
Defensive patterns

Strategy: validation

Validate before calling

import shutil, subprocess

def git_worktree_ready(repo_root: str) -> bool:
    if not shutil.which("git"):
        return False
    try:
        r = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"],
                           cwd=repo_root, capture_output=True, text=True, timeout=10)
        return r.returncode == 0 and r.stdout.strip() == "true"
    except (OSError, subprocess.TimeoutExpired):
        return False

assert git_worktree_ready(str(repo_root)), "worktree tools need a real git work tree; run `git init` + commit first"

Type guard

def is_git_repo_root(path_like: object) -> bool:
    from pathlib import Path
    if not isinstance(path_like, (str, Path)):
        return False
    p = Path(path_like)
    return p.is_dir() and ((p / ".git").exists() or p.joinpath(".git").is_file())

Try / catch

try:
    out = mgr._run_git(["worktree", "add", ...])
except RuntimeError as e:
    if "Not in a git repository" in str(e):
        # fail fast with remediation, do not retry
        return "Worktree tools unavailable: initialize a git repo (git init && git commit --allow-empty -m init) and restart."
    raise

Prevention

When it happens

Trigger: Running the s12 agent with cwd/repo_root inside a directory that is not a git work tree (no .git, or a bare repo checkout path); git missing from PATH (the probe raises and returns False); or the probe timing out at 10s on a hung/network filesystem.

Common situations: Trying the worktree-isolation demo in a freshly made scratch dir that was never `git init`-ed. Containers/cron environments without git installed. repo_root pointing at a subdirectory of the actual repo in a detached state, or at a repo whose .git is unreadable.

Related errors


AI-assisted analysis of shareAI-lab/learn-claude-code@985456f4ad (2026-08-14). Data as JSON: /api/errors/2d38570fd6f52ed7. Report an issue: GitHub.