From 6edf2e57b8dbbd1501f1ce946e7d17aca68d4d14 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 5 Oct 2026 20:00:19 +0100 Subject: [PATCH] feat: conflict guard warns on unregistered on-disk worktrees (#470) worktree_check_conflict reads claims only from active.md, so a linked git worktree no ledger mentions was invisible to it. It now prints a WARNING per requested repo's on-disk worktree not covered by any active.md or parked.md `worktree:` path (equal or parent, ~-expanded); exit code is unchanged and the registry still fails closed. - worktree_list_on_disk : linked worktrees from `git worktree list --porcelain` (path, branch), main checkout skipped. - worktree_audit_orphans [repo...]: report-only sweep over every checkout; ORPHAN rows with ahead/behind vs origin/main and dirty count, STALE? for active claims with zero commits and zero changes. Removes nothing. - Docs: guard reads active.md only; WARNING + audit described in start_dev reference and WORKFLOW. - tests/test_worktree_orphan_guard.py: 8 hermetic cases. Co-Authored-By: Claude Opus 5.5 --- bin/worktree.sh | 124 ++++++++++++++++ skills/WORKFLOW.md | 4 +- skills/start_dev/reference.md | 2 +- tests/test_worktree_orphan_guard.py | 220 ++++++++++++++++++++++++++++ 4 files changed, 348 insertions(+), 2 deletions(-) create mode 100644 tests/test_worktree_orphan_guard.py diff --git a/bin/worktree.sh b/bin/worktree.sh index 3242ff97..5d15930a 100644 --- a/bin/worktree.sh +++ b/bin/worktree.sh @@ -427,10 +427,121 @@ worktree_list_claimed() { ' "$active" } +# _worktree_canon -> absolute, ~-expanded, symlink-resolved path. +_worktree_canon() { + local p="$1" + [[ "$p" == "~" || "$p" == "~/"* ]] && p="$HOME${p:1}" + readlink -m -- "$p" 2>/dev/null || printf '%s\n' "${p%/}" +} + +# _worktree_claim_roots +# Emits `\t\t` for every entry with a +# `worktree:` field in active.md and (when present) parked.md. A parked claim +# is deliberate, so it exempts its worktree from "orphan" too. Returns 3 when +# active.md cannot be resolved (same fail-closed contract as the guard). +_worktree_claim_roots() { + local active parked ledger file task wt + active="$(worktree_registry_path)" || return 3 + parked="$(dirname "$active")/parked.md" + for file in "$active" "$parked"; do + [[ -f "$file" ]] || continue + ledger="$(basename "$file" .md)" + while IFS=$'\t' read -r task wt; do + [[ -n "$wt" && "$wt" != "-" ]] || continue + printf '%s\t%s\t%s\n' "$ledger" "$task" "$(_worktree_canon "$wt")" + done < <(awk '/^## /{task=$2; next} /^- worktree:/{print task "\t" $3}' "$file") + done +} + +# _worktree_covering_claim +# Echoes `\t` of the first claim whose worktree path equals the +# given path or is a parent of it (bundle roots like //RepoA). +# Returns 1 when no claim covers it. +_worktree_covering_claim() { + local path="$1" ledger task root + while IFS=$'\t' read -r ledger task root; do + [[ -n "$root" ]] || continue + if [[ "$path" == "$root" || "$path" == "$root/"* ]]; then + printf '%s\t%s\n' "$ledger" "$task" + return 0 + fi + done <<< "$2" + return 1 +} + +# worktree_list_on_disk +# Emits `\t` for each LINKED git worktree of the repo's canonical +# checkout that exists on disk (the main checkout itself is skipped). Branch is +# `(detached)` for a detached HEAD. Read-only. +worktree_list_on_disk() { + local repo="$1" dir path branch + dir="$(pyauto_repo_path "$repo" "$PYAUTO_MAIN" 2>/dev/null)" || return 0 + [[ -e "$dir/.git" ]] || return 0 + while IFS=$'\t' read -r path branch; do + [[ -d "$path" ]] && printf '%s\t%s\n' "$path" "$branch" + done < <(git -C "$dir" worktree list --porcelain 2>/dev/null | awk ' + function emit() { if (n > 1 && path != "") printf "%s\t%s\n", path, branch; path = "" } + /^worktree / { emit(); n++; path = substr($0, 10); branch = "(detached)"; next } + /^branch / { branch = substr($0, 8); sub(/^refs\/heads\//, "", branch); next } + END { emit() } + ') +} + +# worktree_audit_orphans [repo ...] +# REPORT-ONLY sweep (removes nothing). For every repo (default: every checkout +# pyauto_repo_list finds under $PYAUTO_MAIN), lists each on-disk linked worktree +# that no active.md/parked.md claim covers: +# ORPHAN\t\t\t\tahead=N\tbehind=M\tdirty=K +# and each active.md-claimed worktree with no commits ahead of origin/main and +# no changed files (a claim that may have died before doing anything): +# STALE?\t\t\t\t +# ahead/behind are `?` when origin/main does not resolve. The list is for a +# human to confirm in /repo_cleanup. Returns 3 when active.md is unreadable. +worktree_audit_orphans() { + local roots repos repo path branch claim ledger task ahead behind dirty counts + local orphans=0 stale=0 + roots="$(_worktree_claim_roots)" || { + echo "worktree_audit_orphans: CANNOT VERIFY — no active.md under \$PYAUTO_MAIN=${PYAUTO_MAIN:-}" >&2 + return 3 + } + if (( $# )); then + repos="$(printf '%s\n' "$@")" + else + repos="$(pyauto_repo_list "$PYAUTO_MAIN" | cut -f1)" + fi + while IFS= read -r repo; do + [[ -n "$repo" ]] || continue + while IFS=$'\t' read -r path branch; do + ahead="?" behind="?" + if git -C "$path" rev-parse --verify -q origin/main >/dev/null 2>&1; then + counts="$(git -C "$path" rev-list --left-right --count HEAD...origin/main 2>/dev/null)" + read -r ahead behind <<< "$counts" + fi + dirty="$(GIT_OPTIONAL_LOCKS=0 git -C "$path" status --porcelain 2>/dev/null | wc -l | tr -d ' ')" + if claim="$(_worktree_covering_claim "$(_worktree_canon "$path")" "$roots")"; then + IFS=$'\t' read -r ledger task <<< "$claim" + if [[ "$ledger" == "active" && "$ahead" == "0" && "$dirty" == "0" ]]; then + printf 'STALE?\t%s\t%s\t%s\t%s\n' "$task" "$repo" "$path" "$branch" + stale=$((stale + 1)) + fi + else + printf 'ORPHAN\t%s\t%s\t%s\tahead=%s\tbehind=%s\tdirty=%s\n' \ + "$repo" "$path" "$branch" "$ahead" "$behind" "$dirty" + orphans=$((orphans + 1)) + fi + done < <(worktree_list_on_disk "$repo") + done <<< "$repos" + echo "worktree_audit_orphans: $orphans orphan(s), $stale stale? claim(s) — report only, nothing removed" +} + # worktree_check_conflict [--allow-missing-registry] [repo2 ...] # Exits 0 if none of the requested repos are claimed by a different task. # Exits 1 and prints the conflicts to stderr otherwise. # Exits 3 when the registry cannot be resolved — see below. +# Claims are read from active.md only (not planned.md/parked.md). Separately, +# each requested repo's on-disk linked worktrees that no active.md/parked.md +# `worktree:` path covers are printed as `WARNING:` lines; these never change +# the exit code (#470). # # THIS GUARD FAILS CLOSED. It used to return 0 when `active.md` could not be # found, which meant a cloud/web/CI session (where the roots were not under the @@ -472,5 +583,18 @@ worktree_check_conflict() { fi done < <(worktree_list_claimed) done + # Unregistered on-disk worktrees (#470): the claims above come only from + # active.md, so a linked worktree no ledger mentions was invisible here. + # Warn per requested repo; the exit code is deliberately unchanged (a hard + # conflict would block nearly every task while historical orphans exist). + # The cross-repo sweep is worktree_audit_orphans, kept out of the guard. + local roots path branch + roots="$(_worktree_claim_roots)" + for want in "$@"; do + while IFS=$'\t' read -r path branch; do + _worktree_covering_claim "$(_worktree_canon "$path")" "$roots" >/dev/null && continue + echo "WARNING: $want has unregistered worktree $path ($branch)" >&2 + done < <(worktree_list_on_disk "$want") + done return $rc } diff --git a/skills/WORKFLOW.md b/skills/WORKFLOW.md index fc49b43a..0c282557 100644 --- a/skills/WORKFLOW.md +++ b/skills/WORKFLOW.md @@ -175,7 +175,9 @@ lifecycle and prompt-sync scripts; do not hand-roll state transitions. Local tasks use the Brain checkout's `bin/worktree.sh` and `feature/` branches. `worktree_check_conflict` fails closed when it -cannot read the registry. A repo bullet beneath an active task's `repos:` is a +cannot read the registry, and warns (exit unchanged) on on-disk worktrees no +`active.md`/`parked.md` claim covers; `worktree_audit_orphans` is the +report-only sweep. A repo bullet beneath an active task's `repos:` is a claim; tasks touching the same repo serialize unless a human explicitly authorizes coordination. Source the generated `activate.sh` before Python or tests. diff --git a/skills/start_dev/reference.md b/skills/start_dev/reference.md index 4e7a0794..6ed246bc 100644 --- a/skills/start_dev/reference.md +++ b/skills/start_dev/reference.md @@ -122,7 +122,7 @@ PyAutoMind. Shared organ boundary and the execution-environment model are in This prints one line per `(task, repo, branch, worktree_path)` quadruple currently registered in `active.md`. For each affected repo the new plan wants to touch, check whether a different task already claims it via a `worktree:` field. If so, flag it as a **hard conflict** — the new task cannot start until the other one ships. - **The guard fails closed (#225).** `worktree_check_conflict` resolves `active.md` under `$PYAUTO_MAIN` (default `$HOME/Code/PyAutoLabs`). When it cannot find the registry it exits **3** with `CANNOT VERIFY`, rather than reporting "no conflict" from a read that never happened — outside local-dev, set `PYAUTO_MAIN` to the directory holding your PyAutoMind checkout. `--allow-missing-registry` proceeds **unguarded** and says so; use it only when you have confirmed by other means that nothing else claims the repos. Exit `1` is a real conflict; `0` is genuinely clear. + **The guard fails closed (#225).** `worktree_check_conflict` resolves `active.md` under `$PYAUTO_MAIN` (default `$HOME/Code/PyAutoLabs`). When it cannot find the registry it exits **3** with `CANNOT VERIFY`, rather than reporting "no conflict" from a read that never happened — outside local-dev, set `PYAUTO_MAIN` to the directory holding your PyAutoMind checkout. `--allow-missing-registry` proceeds **unguarded** and says so; use it only when you have confirmed by other means that nothing else claims the repos. Exit `1` is a real conflict; `0` is genuinely clear. The guard reads claims from `active.md` only (not `planned.md`/`parked.md`). It also prints `WARNING: has unregistered worktree ()` for each on-disk linked worktree of a requested repo that no `active.md`/`parked.md` `worktree:` path covers (#470) — the exit code is unchanged; read the warning, and use the report-only `worktree_audit_orphans` for the cross-repo sweep (`ORPHAN` rows with ahead/behind/dirty, `STALE?` for zero-commit claims) before any `/repo_cleanup`. Then, for each affected repo, also run: ```bash diff --git a/tests/test_worktree_orphan_guard.py b/tests/test_worktree_orphan_guard.py new file mode 100644 index 00000000..aa4347ac --- /dev/null +++ b/tests/test_worktree_orphan_guard.py @@ -0,0 +1,220 @@ +"""tests/test_worktree_orphan_guard.py — unregistered on-disk worktrees (#470). + +`worktree_check_conflict` reads only the `active.md` registry, so a linked git +worktree that exists on disk but is claimed by no task (an "orphan": a dead +session, a hand-made `git worktree add`, a bundle whose ledger row was pruned) +was invisible to it. Two sessions could then work the same repo with the guard +reporting clear. + +The guard now prints a `WARNING:` per unregistered worktree of each requested +repo — exit code unchanged, because a hard conflict would block nearly every +task while historical orphans exist. `worktree_audit_orphans` is the +report-only sweep across every repo; it removes nothing. + +Hermetic: synthetic git repos under tmp_path, on the `_run` idiom of +test_worktree_conflict_guard.py. Repo names are synthetic (tenant firewall). +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +WORKTREE_SH = Path(__file__).resolve().parents[1] / "bin" / "worktree.sh" + + +def _git(*args): + subprocess.run( + ["git", *map(str, args)], check=True, capture_output=True, text=True + ) + + +def _repo(main: Path, name: str, *, with_origin: bool = True) -> Path: + """A flat checkout
/ with one commit and an origin/main ref.""" + repo = main / name + repo.mkdir(parents=True) + _git("init", "-q", "-b", "main", repo) + _git("-C", repo, "config", "user.email", "test@example.com") + _git("-C", repo, "config", "user.name", "Test") + (repo / "README.md").write_text("x\n") + _git("-C", repo, "add", "README.md") + _git("-C", repo, "commit", "-q", "-m", "initial") + if with_origin: + remote = main.parent / f"{name}.git" + _git("init", "-q", "--bare", remote) + _git("-C", repo, "remote", "add", "origin", remote) + _git("-C", repo, "push", "-q", "-u", "origin", "main") + return repo + + +def _worktree(repo: Path, path: Path, branch: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + _git("-C", repo, "worktree", "add", "-q", path, "-b", branch) + _git("-C", path, "config", "user.email", "test@example.com") + _git("-C", path, "config", "user.name", "Test") + return path + + +def _main(tmp_path: Path, active: str | None, parked: str | None = None) -> Path: + main = tmp_path / "main" + mind = main / "PyAutoMind" + mind.mkdir(parents=True) + if active is not None: + (mind / "active.md").write_text(active) + if parked is not None: + (mind / "parked.md").write_text(parked) + return main + + +def _run(tmp_path: Path, snippet: str): + return subprocess.run( + ["bash", "-c", f'source "{WORKTREE_SH}"; {snippet}'], + env={ + "PATH": "/usr/bin:/bin", + "HOME": str(tmp_path), + "PYAUTO_MAIN": str(tmp_path / "main"), + "PYAUTO_WT_ROOT": str(tmp_path / "wt"), + }, + capture_output=True, + text=True, + ) + + +EMPTY = "# Active Tasks\n" + + +def _claim(task: str, wt: Path | str, repo: str = "RepoA") -> str: + return ( + f"## {task}\n- worktree: {wt}\n- repos:\n - {repo} (feature/{task})\n\n" + ) + + +def test_unregistered_worktree_warns_but_exit_0(tmp_path): + main = _main(tmp_path, EMPTY) + repo = _repo(main, "RepoA") + ghost = _worktree(repo, tmp_path / "x" / "RepoA", "feature/ghost") + + r = _run(tmp_path, "worktree_check_conflict new-task RepoA") + + assert r.returncode == 0, r.stderr + assert "WARNING: RepoA has unregistered worktree" in r.stderr + assert str(ghost) in r.stderr + assert "feature/ghost" in r.stderr + + +def test_registered_worktree_no_warning(tmp_path): + wt = tmp_path / "wt" / "claimed-task" / "RepoA" + main = _main(tmp_path, "# Active Tasks\n\n" + _claim("claimed-task", wt)) + repo = _repo(main, "RepoA") + _worktree(repo, wt, "feature/claimed-task") + + r = _run(tmp_path, "worktree_check_conflict claimed-task RepoA") + + assert r.returncode == 0, r.stderr + assert "WARNING" not in r.stderr + + +def test_bundle_root_claim_covers_child(tmp_path): + # Real claims name the bundle root (`~/…-wt/`), with the repo a child. + main = _main(tmp_path, "# Active Tasks\n\n" + _claim("bundle-task", "~/wt/bundle-task")) + repo = _repo(main, "RepoA") + _worktree(repo, tmp_path / "wt" / "bundle-task" / "RepoA", "feature/bundle-task") + + r = _run(tmp_path, "worktree_check_conflict bundle-task RepoA") + + assert r.returncode == 0, r.stderr + assert "WARNING" not in r.stderr + + +def test_parked_claim_not_orphan(tmp_path): + wt = tmp_path / "wt" / "parked-task" + parked = "# Parked tasks\n\n" + _claim("parked-task", wt) + main = _main(tmp_path, EMPTY, parked) + repo = _repo(main, "RepoA") + _worktree(repo, wt / "RepoA", "feature/parked-task") + + guard = _run(tmp_path, "worktree_check_conflict new-task RepoA") + audit = _run(tmp_path, "worktree_audit_orphans") + + assert guard.returncode == 0, guard.stderr + assert "WARNING" not in guard.stderr + assert audit.returncode == 0, audit.stderr + assert "ORPHAN" not in audit.stdout + assert "STALE?" not in audit.stdout # parked is deliberate, never stale + + +def test_other_repo_orphan_not_reported(tmp_path): + main = _main(tmp_path, EMPTY) + _repo(main, "RepoA") + repo_b = _repo(main, "RepoB") + _worktree(repo_b, tmp_path / "x" / "RepoB", "feature/ghost-b") + + r = _run(tmp_path, "worktree_check_conflict new-task RepoA") + + assert r.returncode == 0, r.stderr + assert "WARNING" not in r.stderr + + +def test_audit_lists_orphan_with_ahead_behind_dirty(tmp_path): + main = _main(tmp_path, EMPTY) + repo = _repo(main, "RepoA") + ghost = _worktree(repo, tmp_path / "x" / "RepoA", "feature/ghost") + (ghost / "a.txt").write_text("a\n") + _git("-C", ghost, "add", "a.txt") + _git("-C", ghost, "commit", "-q", "-m", "one") + (ghost / "b.txt").write_text("b\n") + _git("-C", ghost, "add", "b.txt") + _git("-C", ghost, "commit", "-q", "-m", "two") + (ghost / "dirty1.txt").write_text("d\n") + (ghost / "README.md").write_text("changed\n") + + r = _run(tmp_path, "worktree_audit_orphans") + + assert r.returncode == 0, r.stderr + rows = [ln.split("\t") for ln in r.stdout.splitlines() if ln.startswith("ORPHAN")] + assert len(rows) == 1, r.stdout + row = rows[0] + assert row[1] == "RepoA" + assert row[2] == str(ghost) + assert row[3] == "feature/ghost" + assert "ahead=2" in row and "behind=0" in row and "dirty=2" in row, row + assert ghost.is_dir() # report-only: nothing removed + assert "nothing removed" in r.stdout + + +def test_audit_flags_zero_commit_claim(tmp_path): + busy = tmp_path / "wt" / "busy-task" + idle = tmp_path / "wt" / "idle-task" + active = "# Active Tasks\n\n" + _claim("busy-task", busy) + _claim("idle-task", idle, "RepoB") + main = _main(tmp_path, active) + repo_a = _repo(main, "RepoA") + repo_b = _repo(main, "RepoB") + busy_wt = _worktree(repo_a, busy / "RepoA", "feature/busy-task") + (busy_wt / "c.txt").write_text("c\n") + _git("-C", busy_wt, "add", "c.txt") + _git("-C", busy_wt, "commit", "-q", "-m", "work") + _worktree(repo_b, idle / "RepoB", "feature/idle-task") + + r = _run(tmp_path, "worktree_audit_orphans") + + assert r.returncode == 0, r.stderr + stale = [ln.split("\t") for ln in r.stdout.splitlines() if ln.startswith("STALE?")] + assert len(stale) == 1, r.stdout + assert stale[0][1] == "idle-task" + assert stale[0][2] == "RepoB" + assert "ORPHAN" not in r.stdout + + +def test_missing_registry_still_fails_closed(tmp_path): + main = _main(tmp_path, None) + repo = _repo(main, "RepoA") + _worktree(repo, tmp_path / "x" / "RepoA", "feature/ghost") + + guard = _run(tmp_path, "worktree_check_conflict new-task RepoA") + audit = _run(tmp_path, "worktree_audit_orphans") + + assert guard.returncode == 3, guard.stderr + assert "CANNOT VERIFY" in guard.stderr + assert "WARNING" not in guard.stderr + assert audit.returncode == 3, audit.stdout + audit.stderr + assert "ORPHAN" not in audit.stdout