Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions bin/worktree.sh
Original file line number Diff line number Diff line change
Expand Up @@ -427,10 +427,121 @@ worktree_list_claimed() {
' "$active"
}

# _worktree_canon <path> -> 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 `<ledger>\t<task>\t<canonical-worktree-path>` 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 <canonical-path> <claim-roots-text>
# Echoes `<ledger>\t<task>` of the first claim whose worktree path equals the
# given path or is a parent of it (bundle roots like <root>/<task>/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 <repo>
# Emits `<path>\t<branch>` 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<repo>\t<path>\t<branch>\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<task>\t<repo>\t<path>\t<branch>
# 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:-<unset>}" >&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] <task-name> <repo1> [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
Expand Down Expand Up @@ -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
}
4 changes: 3 additions & 1 deletion skills/WORKFLOW.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<task-name>` 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.
Expand Down
2 changes: 1 addition & 1 deletion skills/start_dev/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <repo> has unregistered worktree <path> (<branch>)` 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
Expand Down
220 changes: 220 additions & 0 deletions tests/test_worktree_orphan_guard.py
Original file line number Diff line number Diff line change
@@ -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 <main>/<name> 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/<task>`), 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
Loading