diff --git a/health_agent/capabilities.yaml b/health_agent/capabilities.yaml index abd4c7ac..257b1fd2 100644 --- a/health_agent/capabilities.yaml +++ b/health_agent/capabilities.yaml @@ -61,8 +61,8 @@ continuous_checks: measures: "open PR count + max age per repo" gate_role: "YELLOW if an open PR is >= 7 days old" - id: worktree_drift - impl: heart/checks/worktree_drift.sh - measures: "PyAutoLabs-wt/ dirs vs PyAutoMind active.md (orphan/missing/dirty)" + impl: heart/checks/worktree_drift.py + measures: "worktree dirs (wt root + claimed paths) vs PyAutoMind active.md/parked.md (orphan/parked/missing/dirty/canonical-dirty)" gate_role: "monitoring (surfaced in status; not a readiness reason)" - id: script_timing impl: heart/checks/script_timing.py diff --git a/heart/checks/worktree_drift.py b/heart/checks/worktree_drift.py new file mode 100644 index 00000000..e36a0fa7 --- /dev/null +++ b/heart/checks/worktree_drift.py @@ -0,0 +1,190 @@ +"""heart/checks/worktree_drift.py — task worktrees vs the Mind's claims. + +Compares the worktree dirs on disk (``$PYAUTO_WT_ROOT`` plus any claimed path +outside it) against the ``worktree:`` claims in PyAutoMind's ``active.md`` and +``parked.md``, and categorises: + + ORPHAN on disk, claimed by neither active.md nor parked.md + PARKED on disk, claimed by parked.md (legitimate — not drift) + MISSING claimed by active.md but the path does not exist + DIRTY a REAL task worktree (never a symlink) with uncommitted work + CANONICAL DIRTY a canonical checkout that task worktrees symlink to, itself + dirty — counted ONCE per checkout, never per worktree + +The symlink distinction is the point: ``worktree_create`` symlinks every +non-claimed repo back to ``~/Code/PyAutoLabs/``, so following symlinks +counted one dirty canonical repo once per task worktree that linked it (the +"66 dirty" totals). A user's dirty canonical checkout is their own working +state, not task drift — it gets its own category and a yellow, not a red. + +Claims are path-tested directly (``~`` expanded), wherever they point — a +claim under ``PyAutoLabs/.codex-worktrees/`` is tracked like any other, not +reported missing because it isn't under the wt root. Claim values that are not +path-shaped (parked.md carries prose like ``worktree: none (…)``) are ignored. + +Monitoring-only: surfaced on the dashboard/status, never a readiness reason. +``worktree_drift.sh`` is a thin shim over this module for tick.sh. +""" + +from __future__ import annotations + +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import Any + +HEART_HOME = Path(__file__).resolve().parents[2] +_p3 = Path(__file__).resolve().parents[3] +PYAUTO_ROOT = _p3 if _p3.name == "PyAutoLabs" else Path.home() / "Code" / "PyAutoLabs" +PYAUTO_WT_ROOT = Path(os.environ.get("PYAUTO_WT_ROOT") or Path.home() / "Code" / "PyAutoLabs-wt") +ACTIVE_MD = PYAUTO_ROOT / "PyAutoMind" / "active.md" +PARKED_MD = PYAUTO_ROOT / "PyAutoMind" / "parked.md" +HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart") + + +def _claims(registry_md: Path) -> list[dict[str, str]]: + """``[{task, path}]`` from a registry file's ``worktree:`` lines. + + Only path-shaped values count (``/…`` or ``~…``): parked.md legitimately + records prose like ``worktree: none (pushed to origin; local removed)``.""" + if not registry_md.is_file(): + return [] + claims = [] + current_task = None + for line in registry_md.read_text().splitlines(): + m = re.match(r"^## (\S+)", line) + if m: + current_task = m.group(1) + elif current_task: + wm = re.search(r"worktree:\s*(\S+)", line) + if wm and wm.group(1)[0] in "/~": + claims.append( + {"task": current_task, "path": os.path.expanduser(wm.group(1))} + ) + return claims + + +def _dirty_file_count(repo: Path) -> int: + try: + res = subprocess.run( + ["git", "-C", str(repo), "status", "--porcelain"], + capture_output=True, text=True, timeout=10, + ) + except Exception: + return 0 + return len(res.stdout.strip().splitlines()) if res.stdout.strip() else 0 + + +def scan( + wt_root: Path = PYAUTO_WT_ROOT, + active_md: Path = ACTIVE_MD, + parked_md: Path = PARKED_MD, +) -> dict[str, Any]: + active_claims = _claims(active_md) + parked_claims = _claims(parked_md) + active_paths = {c["path"] for c in active_claims} + parked_paths = {c["path"] for c in parked_claims} + + # Worktree dirs on disk: everything under the wt root, plus any claimed + # path that exists elsewhere (e.g. .codex-worktrees/). + on_disk: list[dict[str, Any]] = [] + seen: set[str] = set() + + def note(path: Path, name: str) -> None: + key = str(path) + if key in seen or not path.is_dir(): + return + seen.add(key) + has_content = any( + child.is_symlink() or (child.is_dir() and (child / ".git").exists()) + for child in path.iterdir() + ) + on_disk.append({"name": name, "path": key, "has_real_worktrees": has_content}) + + if wt_root.is_dir(): + for entry in sorted(wt_root.iterdir()): + if entry.is_dir(): + note(entry, entry.name) + for c in active_claims + parked_claims: + note(Path(c["path"]), Path(c["path"]).name) + + on_disk_paths = {d["path"] for d in on_disk} + orphans = [ + d for d in on_disk + if d["path"] not in active_paths and d["path"] not in parked_paths + ] + parked = [d for d in on_disk if d["path"] in parked_paths] + # Missing is a property of the CLAIMED path itself, tested directly — + # never of whether it happens to sit under the wt root. + missing = [c for c in active_claims if not Path(c["path"]).is_dir()] + + # Task-branch dirt: real (non-symlink) worktree children only. Dirty + # canonical checkouts reached via symlinks are deduped by resolved path. + dirty: list[dict[str, Any]] = [] + canonical_seen: set[str] = set() + canonical_dirty: list[dict[str, Any]] = [] + for entry in on_disk: + for child in Path(entry["path"]).iterdir(): + if not (child.is_dir() and (child / ".git").exists()): + continue + if child.is_symlink(): + target = str(child.resolve()) + if target in canonical_seen: + continue + canonical_seen.add(target) + n = _dirty_file_count(child) + if n: + canonical_dirty.append({"repo": child.name, "dirty_files": n}) + continue + n = _dirty_file_count(child) + if n: + dirty.append( + {"worktree": entry["name"], "repo": child.name, "dirty_files": n} + ) + + return { + "on_disk_count": len(on_disk), + "claimed_count": len(active_claims), + "orphans": orphans, + "parked": parked, + "missing": missing, + "dirty": dirty, + "canonical_dirty": sorted(canonical_dirty, key=lambda d: d["repo"]), + } + + +def main(argv: list[str] | None = None) -> int: + result = scan() + + sys.path.insert(0, str(HEART_HOME)) + from heart import state + + state.atomic_write_json(HEART_STATE_DIR / "worktree_drift.json", result) + + from heart.heart_color import c_fail, c_info, c_ok, c_warn, glyph_fail, glyph_ok, glyph_warn + + orphan_n = len(result["orphans"]) + missing_n = len(result["missing"]) + dirty_n = len(result["dirty"]) + canon_n = len(result["canonical_dirty"]) + if dirty_n or missing_n: + glyph, label = glyph_fail(), c_fail( + f"drift: {orphan_n} orphan / {missing_n} missing / {dirty_n} dirty" + ) + elif orphan_n or canon_n: + bits = [] + if orphan_n: + bits.append(f"{orphan_n} orphan dir(s) (clean)") + if canon_n: + bits.append(f"{canon_n} canonical checkout(s) dirty") + glyph, label = glyph_warn(), c_warn(" / ".join(bits)) + else: + glyph, label = glyph_ok(), c_ok("no drift") + print(f"{glyph} {c_info('worktrees')} {label}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/heart/checks/worktree_drift.sh b/heart/checks/worktree_drift.sh index c67c3e83..73636891 100755 --- a/heart/checks/worktree_drift.sh +++ b/heart/checks/worktree_drift.sh @@ -1,128 +1,16 @@ #!/usr/bin/env bash -# heart/checks/worktree_drift.sh — PyAutoLabs-wt/ dirs vs active.md claims. +# heart/checks/worktree_drift.sh — thin shim over heart/checks/worktree_drift.py. # -# Three signals: -# ORPHAN dirs on disk under $PYAUTO_WT_ROOT that are NOT in active.md -# MISSING active.md entries whose worktree dir does NOT exist on disk -# DIRTY any worktree on disk that has uncommitted changes -# -# Writes $HEART_STATE_DIR/worktree_drift.json with the categorised lists. -# Colour summary: -# no drift → green -# only clean orphans → yellow -# dirty orphans / missing claimed → red +# The scan/categorise/report logic lives in the python module, where it is +# unit-testable (tests/test_worktree_drift.py); this wrapper only preserves the +# sourced-function contract tick.sh and the capabilities surface rely on. set -u source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../_common.sh" -PYAUTO_WT_ROOT="${PYAUTO_WT_ROOT:-$HOME/Code/PyAutoLabs-wt}" -# The active-task journal moved with the PyAutoPrompt → PyAutoMind rename. -ACTIVE_MD="$PYAUTO_ROOT/PyAutoMind/active.md" - check_worktree_drift() { - heart_state_dir - heart_log INFO "$(c_info "worktree_drift: scanning $PYAUTO_WT_ROOT vs $ACTIVE_MD")" - - local result_json - result_json="$(python3 - "$PYAUTO_WT_ROOT" "$ACTIVE_MD" <<'PY' -import json -import os -import re -import subprocess -import sys -from pathlib import Path - -wt_root = Path(sys.argv[1]) -active_md = Path(sys.argv[2]) - -# 1. Worktree dirs on disk. -on_disk = [] -if wt_root.is_dir(): - for entry in sorted(wt_root.iterdir()): - if not entry.is_dir(): - continue - # Empty stubs vs real worktrees (real worktrees contain at least - # one symlink or subdir with .git). - has_content = any( - child.is_symlink() or (child.is_dir() and (child / ".git").exists()) - for child in entry.iterdir() - ) - on_disk.append({ - "name": entry.name, - "path": str(entry), - "has_real_worktrees": has_content, - }) - -# 2. Active.md claimed worktrees. -claimed = [] -if active_md.is_file(): - text = active_md.read_text() - current_task = None - for line in text.splitlines(): - m = re.match(r"^## (\S+)", line) - if m: - current_task = m.group(1) - elif current_task: - wm = re.search(r"worktree:\s*(\S+)", line) - if wm: - # Expand ~ if present. - path = os.path.expanduser(wm.group(1)) - claimed.append({"task": current_task, "path": path}) - -# 3. Categorise. -claimed_paths = {c["path"] for c in claimed} -on_disk_paths = {d["path"] for d in on_disk} - -orphans = [d for d in on_disk if d["path"] not in claimed_paths] -missing = [c for c in claimed if c["path"] not in on_disk_paths] - -# 4. Check each on-disk worktree for dirtiness. -dirty = [] -for entry in on_disk: - if not entry["has_real_worktrees"]: - continue - for child in Path(entry["path"]).iterdir(): - if child.is_dir() and (child / ".git").exists(): - try: - res = subprocess.run( - ["git", "-C", str(child), "status", "--porcelain"], - capture_output=True, text=True, timeout=10, - ) - if res.stdout.strip(): - dirty.append({ - "worktree": entry["name"], - "repo": child.name, - "dirty_files": len(res.stdout.strip().splitlines()), - }) - except Exception: - pass - -print(json.dumps({ - "on_disk_count": len(on_disk), - "claimed_count": len(claimed), - "orphans": orphans, - "missing": missing, - "dirty": dirty, -})) -PY -)" - - heart_write_json "$HEART_STATE_DIR/worktree_drift.json" "$result_json" - - local orphan_n missing_n dirty_n - orphan_n="$(echo "$result_json" | python3 -c "import sys,json; print(len(json.load(sys.stdin)['orphans']))")" - missing_n="$(echo "$result_json" | python3 -c "import sys,json; print(len(json.load(sys.stdin)['missing']))")" - dirty_n="$(echo "$result_json" | python3 -c "import sys,json; print(len(json.load(sys.stdin)['dirty']))")" - - local glyph label - if [[ "$orphan_n" -eq 0 && "$missing_n" -eq 0 && "$dirty_n" -eq 0 ]]; then - glyph="$(glyph_ok)"; label="$(c_ok "no drift")" - elif [[ "$dirty_n" -gt 0 || "$missing_n" -gt 0 ]]; then - glyph="$(glyph_fail)"; label="$(c_fail "drift: ${orphan_n} orphan / ${missing_n} missing / ${dirty_n} dirty")" - else - glyph="$(glyph_warn)"; label="$(c_warn "drift: ${orphan_n} orphan dir(s) (clean)")" - fi - printf '%s %s %s\n' "$glyph" "$(c_info worktrees)" "$label" + heart_log INFO "$(c_info "worktree_drift: scanning via heart/checks/worktree_drift.py")" + PYTHONPATH="$HEART_HOME${PYTHONPATH:+:$PYTHONPATH}" python3 -m heart.checks.worktree_drift heart_log OK "$(c_ok "worktree_drift: done")" } diff --git a/heart/dashboard.py b/heart/dashboard.py index c49e6e1e..d6afdb2f 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -342,16 +342,29 @@ def build_board( orphans = wt.get("orphans", []) or [] missing = wt.get("missing", []) or [] dirty = wt.get("dirty", []) or [] + canonical = wt.get("canonical_dirty", []) or [] + parked = wt.get("parked", []) or [] if dirty or missing: st = FAIL summary = f"{len(orphans)} orphan / {len(missing)} missing / {len(dirty)} dirty" - elif orphans: - st, summary = WARN, f"{len(orphans)} orphan dir(s) (clean)" + elif orphans or canonical: + # Canonical-checkout dirt is the user's own working state, not + # task drift — a caution with its own label, never a red. + bits = [] + if orphans: + bits.append(f"{len(orphans)} orphan dir(s) (clean)") + if canonical: + bits.append(f"{len(canonical)} canonical checkout(s) dirty") + st, summary = WARN, " / ".join(bits) else: - st, summary = OK, "no drift" + st = OK + summary = "no drift" + (f" ({len(parked)} parked)" if parked else "") details = [ f"{d.get('worktree')}/{d.get('repo')}: {d.get('dirty_files')} dirty" for d in dirty[:5] + ] + [ + f"canonical {d.get('repo')}: {d.get('dirty_files')} dirty" + for d in canonical[:5] ] sections.append(Section("worktree_drift", "Worktree drift", st, summary, details)) diff --git a/tests/test_worktree_drift.py b/tests/test_worktree_drift.py new file mode 100644 index 00000000..25c0abe9 --- /dev/null +++ b/tests/test_worktree_drift.py @@ -0,0 +1,106 @@ +"""tests/test_worktree_drift.py — categorisation over synthetic worktree trees. + +Covers the three noise mechanisms fixed in PyAutoHeart#123: claims outside the +wt root read as missing forever (path-test instead), symlinked canonical +checkouts counted dirty once per linking worktree (dedupe into their own +category), and parked.md worktrees read as orphans. +""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +from heart.checks import worktree_drift as wd + + +def _git_repo(path: Path, dirty: bool = False) -> Path: + path.mkdir(parents=True) + subprocess.run(["git", "init", "-q", str(path)], check=True) + if dirty: + (path / "uncommitted.txt").write_text("x") + return path + + +def _registry(path: Path, entries: dict[str, str]) -> Path: + lines = ["# Registry", ""] + for task, wt in entries.items(): + lines += [f"## {task}", f"- worktree: {wt}", ""] + path.write_text("\n".join(lines)) + return path + + +def test_claim_outside_wt_root_is_not_missing_and_not_orphan(tmp_path): + outside = tmp_path / "codex-worktrees" / "some-task" + _git_repo(outside / "RepoA") + active = _registry(tmp_path / "active.md", {"some-task": str(outside)}) + out = wd.scan(tmp_path / "wt-root", active, tmp_path / "parked.md") + assert out["missing"] == [] + assert out["orphans"] == [] + assert any(d["path"] == str(outside) for d in out["parked"]) is False + + +def test_nonexistent_claim_is_missing(tmp_path): + active = _registry(tmp_path / "active.md", {"gone": str(tmp_path / "nope")}) + out = wd.scan(tmp_path / "wt-root", active, tmp_path / "parked.md") + assert [m["task"] for m in out["missing"]] == ["gone"] + + +def test_symlinked_canonical_dirt_counted_once_and_not_task_dirt(tmp_path): + canonical = _git_repo(tmp_path / "PyAutoLabs" / "PyAutoMind", dirty=True) + wt_root = tmp_path / "wt-root" + for task in ("task-a", "task-b"): + d = wt_root / task + d.mkdir(parents=True) + (d / "PyAutoMind").symlink_to(canonical) + active = _registry(tmp_path / "active.md", { + "task-a": str(wt_root / "task-a"), "task-b": str(wt_root / "task-b")}) + out = wd.scan(wt_root, active, tmp_path / "parked.md") + assert out["dirty"] == [] # never task drift + assert len(out["canonical_dirty"]) == 1 # deduped across worktrees + assert out["canonical_dirty"][0]["repo"] == "PyAutoMind" + assert out["canonical_dirty"][0]["dirty_files"] == 1 + + +def test_real_worktree_dirt_still_attributed(tmp_path): + wt_root = tmp_path / "wt-root" + _git_repo(wt_root / "task-a" / "RepoA", dirty=True) + active = _registry(tmp_path / "active.md", {"task-a": str(wt_root / "task-a")}) + out = wd.scan(wt_root, active, tmp_path / "parked.md") + assert out["dirty"] == [ + {"worktree": "task-a", "repo": "RepoA", "dirty_files": 1}] + assert out["canonical_dirty"] == [] + + +def test_parked_worktree_is_not_an_orphan(tmp_path): + wt_root = tmp_path / "wt-root" + _git_repo(wt_root / "parked-task" / "RepoA") + parked = _registry(tmp_path / "parked.md", {"parked-task": str(wt_root / "parked-task")}) + out = wd.scan(wt_root, tmp_path / "active.md", parked) + assert out["orphans"] == [] + assert [p["name"] for p in out["parked"]] == ["parked-task"] + + +def test_unclaimed_dir_is_an_orphan(tmp_path): + wt_root = tmp_path / "wt-root" + _git_repo(wt_root / "mystery" / "RepoA") + out = wd.scan(wt_root, tmp_path / "active.md", tmp_path / "parked.md") + assert [o["name"] for o in out["orphans"]] == ["mystery"] + + +def test_prose_worktree_values_are_ignored(tmp_path): + parked = tmp_path / "parked.md" + parked.write_text("## shipped-task\n- worktree: none (pushed; local removed)\n") + out = wd.scan(tmp_path / "wt-root", tmp_path / "active.md", parked) + assert out["missing"] == [] + assert out["claimed_count"] == 0 + + +def test_tilde_claims_are_expanded(tmp_path, monkeypatch): + monkeypatch.setenv("HOME", str(tmp_path)) + wt = tmp_path / "Code" / "PyAutoLabs-wt" / "task-a" + _git_repo(wt / "RepoA") + active = _registry(tmp_path / "active.md", {"task-a": "~/Code/PyAutoLabs-wt/task-a"}) + out = wd.scan(tmp_path / "Code" / "PyAutoLabs-wt", active, tmp_path / "parked.md") + assert out["missing"] == [] + assert out["orphans"] == []