diff --git a/.claude/scripts/gc-worktrees.sh b/.claude/scripts/gc-worktrees.sh new file mode 100644 index 000000000..d995b7ae6 --- /dev/null +++ b/.claude/scripts/gc-worktrees.sh @@ -0,0 +1,237 @@ +#!/usr/bin/env bash +# gc-worktrees.sh — collect finished agent worktrees so they stop pinning branch names. +# +# WHY THIS EXISTS (the failure it prevents): +# A branch can be checked out in exactly ONE worktree. Every dispatched agent gets its +# own worktree (`isolation: 'worktree'`), and nothing removed them when the run ended, +# so they accumulate. Each one holds its branch hostage: +# $ git checkout feat/some-task +# fatal: 'feat/some-task' is already checked out at '.claude/worktrees/wf_40037…-1' +# The visible symptoms are (a) `gh pr checkout ` aborting outright in a sweep/resolve +# agent, and (b) agents improvising a local branch name of their own and pushing from it. +# The other half of the fix is checking out DETACHED — see the sweep/resolve skills. +# +# Usage: gc-worktrees.sh [--dry-run] [--prune-branches] +# --dry-run report what would be removed; change nothing. Exit 0 either way. +# --prune-branches also `git branch -d` each freed branch (safe delete — git itself +# refuses if it is not merged; we only ever offer merged ones). +# +# REMOVAL RULE (all four must hold — fail-closed, never force): +# 1. SCOPE — the worktree path is under /.claude/worktrees/. The primary +# checkout and any worktree a human made elsewhere are silently skipped. +# (Without this the repo root itself matches "merged" trivially and git +# rejects `worktree remove ` with a confusing error every run.) +# 2. SETTLED — its branch belongs to a PR GitHub reports as MERGED or CLOSED. +# NOT `git merge-base --is-ancestor origin/`: a repo that +# SQUASH-merges never makes a landed branch's tip an ancestor of the default +# branch, so that test looks right, passes review, and silently collects +# NOTHING forever. It is kept only as the fallback for a detached HEAD (no +# branch to look up) and for when `gh` is unavailable. +# 3. CLEAN — `git status --porcelain` is empty. Uncommitted work (tracked OR +# untracked) is never discarded; the worktree is reported and skipped. +# 4. UNLOCKED — `git worktree lock` is the explicit "do not collect this" marker. +# +# ORPHANS: a worktree whose branch has NO pull request at all is kept (we cannot prove the +# work landed), but it is counted and LISTED separately rather than folded into the +# "still in flight" total. Those are usually the improvised local branch names that the +# detached-checkout fix exists to stop creating, and they pin their names indefinitely — +# a silent count is what lets them accumulate unnoticed. +# +# Safe to run concurrently with live agents: a worktree an agent is actively using has an +# open PR (rule 2) or a dirty tree (rule 3), so it fails the rule set. This is also why the +# script never takes a lock of its own — `git worktree remove` is atomic enough for the +# narrow set that survives all four rules. + +set -euo pipefail + +dry_run=0 +prune_branches=0 +for arg in "$@"; do + case "$arg" in + --dry-run) dry_run=1 ;; + --prune-branches) prune_branches=1 ;; + *) echo "usage: gc-worktrees.sh [--dry-run] [--prune-branches]" >&2; exit 2 ;; + esac +done + +git rev-parse --show-toplevel >/dev/null 2>&1 || { echo "ABORT: not inside a git repository" >&2; exit 1; } +# Resolve the MAIN checkout, not the caller's worktree: this script may be invoked from +# inside a linked worktree, where --show-toplevel is that worktree. Worktrees live under +# the main checkout, so scope must be anchored there. +# +# Take it from `worktree list` (git always lists the main worktree first) rather than from +# `dirname $(git rev-parse --git-common-dir)` + `pwd`. On Git Bash `pwd` yields an MSYS path +# (/h/Vscode/repo) while `worktree list` yields a Windows one (H:/Vscode/repo), so the two +# never string-match and the SCOPE guard silently rejects every worktree — the whole script +# becomes a no-op that reports "0 collected". Reading both from the same git command keeps +# the path format consistent by construction. +main_root="$(git worktree list --porcelain | sed -n '1s/^worktree //p')" +[ -n "$main_root" ] || { echo "ABORT: could not resolve the main worktree path" >&2; exit 1; } +scope="$main_root/.claude/worktrees/" + +# Refresh origin once — rule 2's fallback compares against it, and a stale ref would make +# landed work look unmerged (the conservative direction: we collect nothing). +git -C "$main_root" fetch origin --quiet 2>/dev/null || \ + echo "note: could not fetch origin — judging merged-ness against the local remote refs" >&2 + +# Do NOT hardcode `main`: this script ships to repos whose default branch differs. +default_branch="$(git -C "$main_root" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||')" +if [ -z "$default_branch" ]; then + default_branch="$(gh repo view --json defaultBranchRef --jq .defaultBranchRef.name 2>/dev/null || true)" +fi +[ -n "$default_branch" ] || default_branch="main" + +if ! git -C "$main_root" rev-parse --verify --quiet "origin/$default_branch" >/dev/null; then + echo "ABORT: origin/$default_branch is not resolvable — cannot judge which worktrees have landed" >&2 + exit 1 +fi + +# Rule 2's primary source: head-branch names whose PR GitHub reports SETTLED — MERGED or +# CLOSED. Closed counts because removing a CLEAN worktree destroys nothing (the branch and +# every commit survive; only the checkout directory goes). +# One paginated call, not one per worktree. If `gh` is missing or unauthenticated we fall +# back to the ancestor test per worktree — which under a squash-merge workflow collects +# almost nothing, so say so out loud rather than reporting a clean "0 collected". +# `gh --jq` uses gh's BUILT-IN jq, so this needs no external jq on PATH. +settled_heads=""; open_heads="" +gh_ok=0 +if command -v gh >/dev/null 2>&1 \ + && all_prs="$(gh pr list --state all --limit 1000 --json headRefName,state \ + --jq '.[] | "\(.state)\t\(.headRefName)"' 2>/dev/null)"; then + open_heads="$(printf '%s\n' "$all_prs" | sed -n 's/^OPEN\t//p')" + settled_heads="$(printf '%s\n' "$all_prs" | sed -n '/^OPEN\t/!s/^[A-Z]*\t//p')" + gh_ok=1 +else + echo "note: gh unavailable/unauthenticated — falling back to the ancestor test, which under" >&2 + echo " a squash-merge workflow will collect almost nothing. Re-run with gh." >&2 +fi + +# Classify this worktree's work. $1 = branch name ("" when detached), $2 = HEAD sha. +# 0 = settled -> collect +# 1 = open PR -> live work, keep quietly +# 2 = no PR -> orphan, keep but REPORT +classify() { + local branch="$1" head="$2" + if [ "$gh_ok" -eq 1 ] && [ -n "$branch" ]; then + # An OPEN PR anywhere on this branch vetoes collection, even if an older PR on the + # same branch settled (a re-dispatch reuses the name) — the open one is live work. + # Exact whole-line match — "plan/FU-46" must not match "plan/FU-460". + # HERE-STRINGS, not `printf … | grep -q`: with `set -o pipefail`, grep -q exits on the + # first match, the producer takes SIGPIPE, and the pipeline reports 141 — so a settled + # branch would read as unsettled. A here-string has no pipe and no such failure mode. + grep -qxF "$branch" <<<"$open_heads" && return 1 + grep -qxF "$branch" <<<"$settled_heads" && return 0 + return 2 + fi + # Detached HEAD, or no gh: fall back to the ancestor test. A detached worktree has no + # name to pin, so keeping it costs nothing when the test is inconclusive. + if git -C "$main_root" merge-base --is-ancestor "$head" "origin/$default_branch" 2>/dev/null; then + return 0 + fi + return 1 +} + +# Directories that no longer exist on disk: git's own bookkeeping handles these. +[ "$dry_run" -eq 1 ] || git -C "$main_root" worktree prune + +# These are newline-delimited STRINGS, not arrays: `${#arr[@]}` on an empty array trips +# `set -u` on bash 3.2, which this script still targets for portability. +removed=0; skipped_dirty=0; skipped_open=0; skipped_orphan=0; skipped_locked=0 +freed_branches=""; orphan_branches="" + +# `git worktree list --porcelain` emits stanzas: worktree / HEAD / +# branch |detached / locked. Parse the stanza rather than the human format, whose +# columns are ambiguous once a path contains spaces. +current_path=""; current_head=""; current_branch=""; current_locked=0 + +flush() { + [ -n "$current_path" ] || return 0 + local path="$current_path" head="$current_head" branch="$current_branch" locked="$current_locked" + current_path=""; current_head=""; current_branch=""; current_locked=0 + + # Rule 1 — SCOPE. + case "$path/" in "$scope"*) ;; *) return 0 ;; esac + # Defence in depth: never touch the main checkout even if it somehow matched. + [ "$path" != "$main_root" ] || return 0 + + local label="${branch:-detached@${head:0:8}}" + + # Rule 4 — UNLOCKED. + if [ "$locked" -eq 1 ]; then + skipped_locked=$((skipped_locked + 1)) + echo " skip (locked) $label" + return 0 + fi + + # Rule 2 — SETTLED. + local verdict=0 + classify "$branch" "$head" || verdict=$? + case "$verdict" in + 1) skipped_open=$((skipped_open + 1)); return 0 ;; + 2) skipped_orphan=$((skipped_orphan + 1)) + orphan_branches="${orphan_branches}${label} +" + return 0 ;; + esac + + # Rule 3 — CLEAN. + if [ -n "$(git -C "$path" status --porcelain 2>/dev/null)" ]; then + skipped_dirty=$((skipped_dirty + 1)) + echo " skip (uncommitted work) $label — $path" + return 0 + fi + + if [ "$dry_run" -eq 1 ]; then + echo " would remove $label" + else + if git -C "$main_root" worktree remove "$path" 2>/dev/null; then + echo " removed $label" + else + echo " skip (git refused the remove) $label — $path" + return 0 + fi + fi + removed=$((removed + 1)) + if [ -n "$branch" ]; then + freed_branches="${freed_branches}${branch} +" + fi + return 0 +} + +while IFS= read -r line; do + case "$line" in + "worktree "*) flush; current_path="${line#worktree }" ;; + "HEAD "*) current_head="${line#HEAD }" ;; + "branch "*) current_branch="${line#branch refs/heads/}" ;; + "locked"|"locked "*) current_locked=1 ;; + esac +done < <(git -C "$main_root" worktree list --porcelain) +flush + +if [ "$prune_branches" -eq 1 ] && [ "$dry_run" -eq 0 ] && [ -n "$freed_branches" ]; then + while IFS= read -r b; do + [ -n "$b" ] || continue + # -d (not -D): git refuses if the branch is somehow not merged after all. + if git -C "$main_root" branch -d "$b" >/dev/null 2>&1; then echo " branch deleted $b"; fi + done <` — `git worktree list` does not expose creation timestamps) -- It matches the sub-agent pattern `.claude/worktrees/agent-` AND has no uncommitted changes AND its branch has no commits ahead of `origin/main` (sub-agent worktrees are typically ephemeral and orphaned after the agent finishes) +Staleness is decided by `.claude/scripts/gc-worktrees.sh`, which is the single source for this rule. Run it in dry-run to get the triage list: + +```bash +bash .claude/scripts/gc-worktrees.sh --dry-run +``` + +It reports a worktree as collectable only when **all** of: its path is under `/.claude/worktrees/` (the scope guard, enforced in code); its branch belongs to a **settled** PR — merged or closed — with no open PR on that branch; its tree has no uncommitted changes; and it is not `git worktree lock`ed. Directories that vanished are handled by `git worktree prune` inside the script. + +> **Do not hand-roll this check with `git branch --merged origin/main`.** In a repo that **squash-merges**, a landed branch's tip is never an ancestor of the default branch, so `--merged` lists almost nothing — the check looks right, passes review, and silently reports every finished worktree as still in flight. The script resolves merged-ness from GitHub PR state for exactly this reason, and detects the default branch rather than assuming `main`. + +The script also reports an **orphan** bucket separately: worktrees whose branch has no PR at all. It never removes these (the work cannot be proven landed), but it names them, because they pin their branch names indefinitely and are usually the residue of an agent that improvised a local branch name after a checkout collision. Surface that list to the user. + +To remove what it found, after confirming with the user: + +```bash +bash .claude/scripts/gc-worktrees.sh --prune-branches +``` + +`--prune-branches` also deletes each freed branch with `git branch -d` (safe delete — git refuses an unmerged branch); drop the flag to keep the branches. **If `DRY_RUN`:** stop after the `--dry-run` call above. The script never force-removes a worktree with uncommitted changes — it prints those as "has uncommitted work"; report that list rather than overriding it. ### 1d. Identify bloated worktrees (NEW) diff --git a/.claude/skills/resolve/SKILL.md b/.claude/skills/resolve/SKILL.md index c616e6a1f..23389215b 100644 --- a/.claude/skills/resolve/SKILL.md +++ b/.claude/skills/resolve/SKILL.md @@ -114,6 +114,12 @@ echo "Pre-flight passed. PR: $(jq -r '.title' .codegraph/resolve/pr-meta.json)" Check out the PR branch and run `git merge` to surface all conflicts. +Check out **detached**. A plain `gh pr checkout` claims the branch *name*, and a branch can +be checked out in only one worktree — if a concurrent agent or a leftover worktree already +holds `$HEAD_BRANCH`, it aborts with `fatal: '' is already checked out at ...`. A +detached HEAD claims no name, so it cannot collide; the push at the end targets the branch +by refspec instead. + ```bash HEAD_BRANCH=$(cat .codegraph/resolve/head-branch) BASE_BRANCH=$(cat .codegraph/resolve/base-branch) @@ -121,7 +127,7 @@ PR_NUMBER=$(cat .codegraph/resolve/pr-number) REPO=$(cat .codegraph/resolve/repo) echo "Checking out PR branch: $HEAD_BRANCH" -gh pr checkout "$PR_NUMBER" --repo "$REPO" \ +gh pr checkout "$PR_NUMBER" --repo "$REPO" --detach \ || { echo "ERROR: failed to check out PR #$PR_NUMBER"; exit 1; } @@ -545,6 +551,7 @@ fi Commit the resolved merge and push to the PR branch. ```bash +HEAD_BRANCH=$(cat .codegraph/resolve/head-branch) BASE_BRANCH=$(cat .codegraph/resolve/base-branch) # Guard against empty commit (all staged changes might have been no-ops) @@ -562,8 +569,12 @@ else echo "Committed merge resolution." fi -echo "Pushing to origin..." -git push \ +# Push BY REFSPEC: Phase 1 checked out detached (so the checkout could not collide with +# another worktree holding this branch), and a bare `git push origin "HEAD:$HEAD_BRANCH"` from a detached HEAD fails +# with "You are not currently on a branch". HEAD: is still a normal +# fast-forward-only push — a non-fast-forward is rejected exactly as before. +echo "Pushing to origin/$HEAD_BRANCH..." +git push origin "HEAD:$HEAD_BRANCH" \ || { echo "ERROR: push failed — check branch protection or authentication"; exit 1; } echo "Pushed successfully." ``` diff --git a/.claude/skills/sweep/SKILL.md b/.claude/skills/sweep/SKILL.md index f3f7b579f..a5a5f959f 100644 --- a/.claude/skills/sweep/SKILL.md +++ b/.claude/skills/sweep/SKILL.md @@ -79,12 +79,37 @@ Several steps below require waiting on something external — CI runs, `npm test - For a reviewer response (Greptile/Claude), a real review typically posts within minutes but can take 15–30+ minutes. Poll for new comments on an interval rather than checking once and assuming silence means "satisfied." - Only stop polling once you have an actual terminal state: a check conclusion, a test exit code, or (for reviews) either a new comment/reaction or enough elapsed real time that you're confident nothing more is coming. -### 2a. Check out the PR branch +### 2a. Check out the PR head (detached) + +A full sweep runs one subagent per PR in parallel, so **never** run a bare `gh pr checkout `: it claims the head branch *name*, and a branch can be checked out in exactly **one** worktree. If a concurrent agent — or a leftover worktree that was never collected — already holds it, the checkout aborts outright: + +```text +fatal: 'fix/some-branch' is already checked out at '.claude/worktrees/wf_40037ee4-070-1' +``` + +Check out **detached** instead. A detached HEAD claims no branch name, so it can never collide; push by refspec at the end. Do **not** work around a collision by inventing a local branch name of your own. + +```bash +oid=$(gh pr view --json headRefOid -q .headRefOid) +gh pr checkout --detach +# Fail closed if HEAD is not the PR head (stale fetch, or the head moved as you started). +[ "$(git rev-parse HEAD)" = "$oid" ] || { echo "ABORT: HEAD is not PR 's head"; exit 1; } +``` + +**Do not carry the branch name in a shell variable across steps.** Each Bash tool call may run in a fresh shell — variables set in one call do not survive into the next. A `head=...` captured here is gone by the time a later step pushes, silently expanding `git push origin "HEAD:$head"` into the invalid refspec `HEAD:` and leaving your fixes unpushed with no error surfaced until you check the PR. Instead, **re-derive the branch name in the same Bash call as every push**: ```bash -gh pr checkout +git push origin "HEAD:$(gh pr view --json headRefName -q .headRefName)" ``` +This applies to every push in this skill, including the commitlint-amend exception: + +```bash +git push --force-with-lease origin "HEAD:$(gh pr view --json headRefName -q .headRefName)" +``` + +> Stale worktrees are the usual reason a name is taken. `bash .claude/scripts/gc-worktrees.sh` collects the finished ones; it never touches a worktree with uncommitted work. + ### 2b. Resolve merge conflicts Check if the PR has conflicts with its base branch: @@ -255,9 +280,12 @@ After addressing all comments for a PR: 1. Stage only the files you changed. 2. Group changes by concern — each logically distinct fix gets its own commit (e.g., one commit for a missing validation, another for a naming change). Do not lump all feedback into a single commit. 3. Use descriptive messages per commit: `fix: (#)` -4. Push to the PR branch. +4. Push to the PR branch — re-derive the branch name in the same call, per Step 2a: + ```bash + git push origin "HEAD:$(gh pr view --json headRefName -q .headRefName)" + ``` 5. **If the push is rejected** (e.g., by a hook or commitlint), diagnose the error before retrying: - - **Commitlint failure** (bad commit message format): This is the ONE case where amend + force-push is allowed. Fix the message with `git commit --amend -m "correct message"` then `git push --force-with-lease`. + - **Commitlint failure** (bad commit message format): This is the ONE case where amend + force-push is allowed. Fix the message with `git commit --amend -m "correct message"` then `git push --force-with-lease origin "HEAD:$(gh pr view --json headRefName -q .headRefName)"` (by refspec — you are on a detached HEAD from step 2a). - **Hook denial** (guard-git.sh blocking staged files not in session edit log): The worktree has no edit log — commit with explicit file paths (`git commit -m "msg"`) instead of staging first. - **Branch name validation failure**: You are on the wrong branch — check out the correct PR branch before retrying. - **Any other failure**: Fix with a new commit. Never amend + force-push for code changes. @@ -389,7 +417,8 @@ If any subagent failed or returned an error, note it in the Status column as `ag ## Rules - **Never rebase.** Always `git merge ` to resolve conflicts. -- **Never force-push** unless fixing a commit message that fails commitlint. Amend + force-push is the only way to fix a pushed commit title (messages are part of the SHA). This is safe on feature branches. For all other problems, fix with a new commit. **If a push or commit is denied by a hook**, read the denial reason — don't blindly retry or escalate to force-push. Common causes: (1) commitlint rejects the message format → amend + force-push (`git push --force-with-lease`), (2) guard-git blocks staged files not in session edit log → use `git commit -m "msg"` with explicit paths, (3) branch name validation fails → you're on the wrong branch. +- **Push by refspec — you are detached.** Step 2a checks the PR head out with `--detach` so the checkout cannot collide with another worktree holding that branch name. A bare `git push` therefore fails with *"You are not currently on a branch"*: every push is `git push origin "HEAD:$(gh pr view --json headRefName -q .headRefName)"`, re-deriving the branch name in the same Bash call as the push — a shell variable captured in an earlier step does not survive into a later one. +- **Never force-push** unless fixing a commit message that fails commitlint. Amend + force-push is the only way to fix a pushed commit title (messages are part of the SHA). This is safe on feature branches. For all other problems, fix with a new commit. **If a push or commit is denied by a hook**, read the denial reason — don't blindly retry or escalate to force-push. Common causes: (1) commitlint rejects the message format → amend + force-push (`git push --force-with-lease origin "HEAD:$(gh pr view --json headRefName -q .headRefName)"`), (2) guard-git blocks staged files not in session edit log → use `git commit -m "msg"` with explicit paths, (3) branch name validation fails → your detached HEAD is not on the PR's head commit. - **Address ALL comments from ALL reviewers** (Claude, Greptile, and humans), even minor/nit/optional ones. Leave zero unaddressed. Do not only respond to one reviewer and skip another. - **Always reply to comments** explaining what was done. Don't just fix silently. Every reviewer must see a reply on their feedback. - **Mine the Greptile *summary* body, not just inline comments** (Step 2d.1). A `Confidence Score: N/5` with `N < 5` always names at least one gap in prose, and those gaps frequently have **no** inline comment. Extract every finding from the summary and fix it (or file a tracked `follow-up`). Missing a summary-only finding is the #1 way a Greptile concern survives a sweep — reconcile your fixes against the summary before declaring the PR ready. diff --git a/.gitattributes b/.gitattributes index 05cfca246..771be5ed1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,3 +6,10 @@ *.node binary *.png binary *.ico binary + +# Shell scripts must be LF on every platform. With core.autocrlf=true a Windows +# checkout smudges them to CRLF, which breaks the `#!/usr/bin/env bash` shebang when a +# script is executed directly, and — the quieter failure — embeds a stray CR inside +# heredocs and here-strings, so gc-worktrees.sh's exact branch-name matching compares +# "feat/x" against "feat/x\r" and never matches. +*.sh text eol=lf