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
4 changes: 2 additions & 2 deletions health_agent/capabilities.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
190 changes: 190 additions & 0 deletions heart/checks/worktree_drift.py
Original file line number Diff line number Diff line change
@@ -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/<repo>``, 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/<task>).
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))
124 changes: 6 additions & 118 deletions heart/checks/worktree_drift.sh
Original file line number Diff line number Diff line change
@@ -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")"
}

Expand Down
19 changes: 16 additions & 3 deletions heart/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
Loading
Loading