diff --git a/agents/_pyauto_root.py b/agents/_pyauto_root.py index f1a0db40..6d6cdb9e 100644 --- a/agents/_pyauto_root.py +++ b/agents/_pyauto_root.py @@ -9,11 +9,18 @@ (PyAutoBrain/, PyAutoMind/, PyAutoHeart/, ...). It is *derived*, never named: 1. an explicit ``PYAUTO_ROOT`` in the environment — the operator's word, taken - verbatim; -2. the parent of this checkout, when that parent holds at least one sibling + verbatim. It is still reported as verified or not, because a wrong value + exported by a hook should show up in the reason rather than pass silently; +2. the nearest ancestor of this checkout holding a ``.pyauto-root`` marker + file. The marker is the only rule that survives the workspace growing + subdirectories: it names the root instead of inferring it from what happens + to sit beside a checkout; +3. the parent of this checkout, when that parent holds at least one sibling organ. It asks where the code actually *is* rather than where it is usually - kept, so it is true on a developer box and in a remote session alike; -3. the parent of this checkout regardless — the best available guess, reported + kept, so it is true on a developer box and in a remote session alike. A + single-repo remote checkout has no root above it to mark, so this stays — + demoted, not removed; +4. the parent of this checkout regardless — the best available guess, reported as unverified so a caller can say "I looked here and it was not a workspace" instead of silently finding nothing. @@ -25,6 +32,12 @@ naming any absolute workspace path here would reintroduce it for the next environment that does not match. +Step 2 exists for the mirror-image failure. Step 3 asks only "does this +directory hold an organ?", which a family subdirectory such as ``organs/`` +would answer yes to the moment the organs move into one — resolving the root +one level too deep, where every ``root / `` join below misses and, +again, nothing raises. The marker is what a directory says about itself. + Stdlib only. """ @@ -38,6 +51,7 @@ "pyauto_wt_root", "workspace_root_reason", "SIBLING_ORGANS", + "ROOT_MARKER", ] # Any one of these beside a directory marks it as a workspace root. PyAutoMind @@ -53,6 +67,11 @@ "PyAutoGut", ) +# A workspace root says so itself by holding this file. It is deliberately +# unversioned — the root is not a git repo — so it marks a checkout layout on +# one machine, not a fact about the organism. +ROOT_MARKER = ".pyauto-root" + _BRAIN_HOME = Path(__file__).resolve().parents[1] @@ -61,6 +80,19 @@ def _is_root(path: Path) -> bool: return any((path / organ).is_dir() for organ in SIBLING_ORGANS) +def _marked_root(start: Path) -> Path | None: + """The nearest ancestor of `start` holding the marker, or None. + + The layout-independent walk the workspace already uses elsewhere to find a + project root: walk up, take the first ancestor carrying the marker file. + Ancestors only — a checkout is never its own workspace root. + """ + for candidate in start.parents: + if (candidate / ROOT_MARKER).is_file(): + return candidate + return None + + def pyauto_root() -> Path: """The workspace root, by the order documented above.""" return Path(workspace_root_reason()[0]) @@ -75,13 +107,23 @@ def workspace_root_reason() -> tuple[Path, str]: """ env = os.environ.get("PYAUTO_ROOT") if env: - return Path(env), "PYAUTO_ROOT" + # The operator's word either way; the marker only decides how the + # reason reads, so a value exported by a mistaken hook is visible + # rather than silent. + if (Path(env) / ROOT_MARKER).is_file(): + return Path(env), "PYAUTO_ROOT" + return Path(env), f"PYAUTO_ROOT (unverified - no {ROOT_MARKER} marker)" + marked = _marked_root(_BRAIN_HOME) + if marked is not None: + return marked, f"{ROOT_MARKER} marker" parent = _BRAIN_HOME.parent if _is_root(parent): + # No marker anywhere above us: a single-repo remote checkout, a CI + # matrix, a spawned template. What sits beside us is all there is. return parent, "beside this checkout" - # No sibling organ next to us. Still the best guess available — but say so, - # so a degraded caller can report "looked in X, not a workspace" rather - # than an empty result that reads like "nothing to do". + # No sibling organ next to us either. Still the best guess available — but + # say so, so a degraded caller can report "looked in X, not a workspace" + # rather than an empty result that reads like "nothing to do". return parent, "unverified (no sibling organ beside this checkout)" diff --git a/agents/conductors/clone/_clone.py b/agents/conductors/clone/_clone.py index 78d49680..3597b2c9 100644 --- a/agents/conductors/clone/_clone.py +++ b/agents/conductors/clone/_clone.py @@ -46,8 +46,8 @@ from pathlib import Path # Workspace root via the one shared resolver (agents/_pyauto_root.py, mirrored -# by bin/_pyauto_root.sh): PYAUTO_ROOT, else beside this checkout, else the -# developer box. Naming an absolute workspace path as the *default* here +# by bin/_pyauto_root.sh): PYAUTO_ROOT, else the nearest ancestor holding a +# .pyauto-root marker, else beside this checkout, else the parent anyway. Naming an absolute workspace path as the *default* here # resolved into # a non-existent tree in a remote session and reported empty rather than # failing. diff --git a/agents/conductors/community/_community.py b/agents/conductors/community/_community.py index 2680066d..258b62ff 100644 --- a/agents/conductors/community/_community.py +++ b/agents/conductors/community/_community.py @@ -41,8 +41,8 @@ from pathlib import Path # Workspace root via the one shared resolver (agents/_pyauto_root.py, mirrored -# by bin/_pyauto_root.sh): PYAUTO_ROOT, else beside this checkout, else the -# developer box. Naming an absolute workspace path as the *default* here +# by bin/_pyauto_root.sh): PYAUTO_ROOT, else the nearest ancestor holding a +# .pyauto-root marker, else beside this checkout, else the parent anyway. Naming an absolute workspace path as the *default* here # resolved into # a non-existent tree in a remote session and reported empty rather than # failing. diff --git a/agents/conductors/profiling/_profiling.py b/agents/conductors/profiling/_profiling.py index 5ffbc311..1ee66233 100644 --- a/agents/conductors/profiling/_profiling.py +++ b/agents/conductors/profiling/_profiling.py @@ -41,8 +41,8 @@ from typing import Any # Workspace root via the one shared resolver (agents/_pyauto_root.py, mirrored -# by bin/_pyauto_root.sh): PYAUTO_ROOT, else beside this checkout, else the -# developer box. Naming an absolute workspace path as the *default* here +# by bin/_pyauto_root.sh): PYAUTO_ROOT, else the nearest ancestor holding a +# .pyauto-root marker, else beside this checkout, else the parent anyway. Naming an absolute workspace path as the *default* here # resolved into # a non-existent tree in a remote session and reported empty rather than # failing. diff --git a/agents/conductors/workspace/_workspace.py b/agents/conductors/workspace/_workspace.py index 056152ce..79128cfa 100644 --- a/agents/conductors/workspace/_workspace.py +++ b/agents/conductors/workspace/_workspace.py @@ -29,8 +29,8 @@ from pathlib import Path # Workspace root via the one shared resolver (agents/_pyauto_root.py, mirrored -# by bin/_pyauto_root.sh): PYAUTO_ROOT, else beside this checkout, else the -# developer box. Naming an absolute workspace path as the *default* here +# by bin/_pyauto_root.sh): PYAUTO_ROOT, else the nearest ancestor holding a +# .pyauto-root marker, else beside this checkout, else the parent anyway. Naming an absolute workspace path as the *default* here # resolved into # a non-existent tree in a remote session and reported empty rather than # failing. diff --git a/bin/_pyauto_root.sh b/bin/_pyauto_root.sh index 762de641..78cfaf16 100755 --- a/bin/_pyauto_root.sh +++ b/bin/_pyauto_root.sh @@ -23,10 +23,23 @@ # this way (BRAIN_HOME.parent); this file makes that the one convention instead # of the majority one. # +# The order, identical to agents/_pyauto_root.py's: +# +# 1. an explicit PYAUTO_ROOT — the operator's word, taken verbatim, but +# reported as verified or not so a wrong value from a hook is visible; +# 2. the nearest ancestor holding a .pyauto-root marker file — the only rule +# that survives the workspace growing subdirectories, because "does this +# directory hold an organ?" is answered yes by a family directory such as +# organs/ the moment the organs move into one; +# 3. the parent of this checkout when it holds a sibling organ — still true +# for a single-repo remote checkout, which has no root above it to mark; +# 4. the parent regardless, reported as unverified. +# # Usage (from anywhere in this repo): # . "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../bin/_pyauto_root.sh" -# then read $PYAUTO_ROOT. An explicit PYAUTO_ROOT in the environment always -# wins, so a caller can still point the tooling at another workspace. +# then read $PYAUTO_ROOT, and $PYAUTO_ROOT_REASON when reporting a degraded +# result. An explicit PYAUTO_ROOT in the environment always wins, so a caller +# can still point the tooling at another workspace. # Guard against re-sourcing: several agents source both _common.sh and a bin # helper that each pull this in. @@ -39,6 +52,32 @@ _pyauto_brain_home() { cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd } +# A workspace root says so itself by holding this file. It is deliberately +# unversioned — the root is not a git repo — so it marks a checkout layout on +# one machine, not a fact about the organism. +PYAUTO_ROOT_MARKER=".pyauto-root" +export PYAUTO_ROOT_MARKER + +# The nearest ANCESTOR of $1 holding the marker, printed; non-zero when there +# is none. A checkout is never its own workspace root, so the walk starts one +# level up — the layout-independent walk the workspace already uses elsewhere +# to find a project root. +_pyauto_marked_root() { + _pyauto_d=$(dirname "$1") + while [ "$_pyauto_d" != "/" ]; do + if [ -f "$_pyauto_d/$PYAUTO_ROOT_MARKER" ]; then + printf '%s' "$_pyauto_d" + return 0 + fi + _pyauto_d=$(dirname "$_pyauto_d") + done + if [ -f "/$PYAUTO_ROOT_MARKER" ]; then + printf '%s' "/" + return 0 + fi + return 1 +} + # A directory counts as a workspace root if it holds at least one sibling organ # besides this one. The Mind is the strongest signal (it carries repos.yaml, # the body map every consumer wants), but a Brain-only remote session is still @@ -49,21 +88,43 @@ _pyauto_is_root() { || [ -d "$1/PyAutoCortex" ] } +# Assigns PYAUTO_ROOT and PYAUTO_ROOT_REASON rather than printing: one +# decision produces two answers, and a command substitution would drop the +# reason. Called directly, so it runs in this shell, not a subshell. _pyauto_resolve_root() { # 1. An explicit override is the operator's word; never second-guess it. + # The marker only decides how the reason reads. if [ -n "${PYAUTO_ROOT:-}" ]; then - printf '%s' "$PYAUTO_ROOT" + if [ -f "$PYAUTO_ROOT/$PYAUTO_ROOT_MARKER" ]; then + PYAUTO_ROOT_REASON="PYAUTO_ROOT" + else + PYAUTO_ROOT_REASON="PYAUTO_ROOT (unverified - no $PYAUTO_ROOT_MARKER marker)" + fi return 0 fi - # 2. Beside this checkout — the layout that is true in every environment - # the organism actually runs in, remote sessions included. 3. Failing - # that, the parent anyway: the best guess available, and a real path the - # caller can name in a diagnostic. - printf '%s' "$(dirname "$(_pyauto_brain_home)")" + _pyauto_home="$(_pyauto_brain_home)" + # 2. A marked ancestor — the root naming itself, which stays right however + # deep under it this checkout sits. + if _pyauto_marked="$(_pyauto_marked_root "$_pyauto_home")"; then + PYAUTO_ROOT="$_pyauto_marked" + PYAUTO_ROOT_REASON="$PYAUTO_ROOT_MARKER marker" + return 0 + fi + # 3. Beside this checkout — no marker anywhere above us, so what sits + # beside us is all there is: a single-repo remote session, a CI matrix, + # a spawned template. 4. Failing that, the parent anyway: the best guess + # available, and a real path the caller can name in a diagnostic. + PYAUTO_ROOT="$(dirname "$_pyauto_home")" + if _pyauto_is_root "$PYAUTO_ROOT"; then + PYAUTO_ROOT_REASON="beside this checkout" + else + PYAUTO_ROOT_REASON="unverified (no sibling organ beside this checkout)" + fi } -PYAUTO_ROOT="$(_pyauto_resolve_root)" +_pyauto_resolve_root export PYAUTO_ROOT +export PYAUTO_ROOT_REASON # Task worktrees live beside the workspace root, not inside it, so they derive # from whatever the root resolved to rather than re-deriving from $HOME. diff --git a/bin/worktree.sh b/bin/worktree.sh index 66d1da66..9d6fb965 100644 --- a/bin/worktree.sh +++ b/bin/worktree.sh @@ -129,6 +129,27 @@ worktree_create() { mkdir -p "$root" || return 1 + # Mark the bundle as a workspace root of its own. Without this, a tool run + # inside the bundle walks past it to the canonical workspace above — the + # sibling-symlink loop below is `"$PYAUTO_MAIN"/*`, which does not glob + # dotfiles, so the canonical marker never arrives here either. Unversioned + # and per-machine, like the canonical one; `worktree_remove` takes it with + # the bundle. + cat > "$root/$PYAUTO_ROOT_MARKER" <<'EOF' +# Task-bundle root marker. +# +# Its presence is what makes this directory a workspace root: the bundle +# holding this task's real git worktrees, plus a symlink back to the canonical +# checkout for every repo the task did not claim. +# `PyAutoBrain/agents/_pyauto_root.py` and `PyAutoBrain/bin/_pyauto_root.sh` +# walk UP from a checkout and take the first ancestor holding this file, so +# work done in here resolves to the bundle rather than to the workspace above. +# +# Written by worktree_create (PyAutoBrain/bin/worktree.sh). Intentionally +# unversioned: a bundle root is not a git repo, so this file belongs to no +# repository. +EOF + local repo for repo in "$@"; do if ! _worktree_add_one "$task" "$repo"; then diff --git a/tests/test_workspace_root.py b/tests/test_workspace_root.py index f9269a64..8388fc55 100644 --- a/tests/test_workspace_root.py +++ b/tests/test_workspace_root.py @@ -11,6 +11,16 @@ The rule these tests pin: exactly one shell resolver and one Python resolver, they agree, and no other source file resolves the root for itself. + +The second half pins the mirror-image failure. The sibling-organ probe asks +only "does this directory hold an organ?", so a family directory such as +`organs/` satisfies it the moment the organs move into one, and the root +resolves ONE LEVEL TOO DEEP — where every `root / ` join misses and, +again, nothing raises. A `.pyauto-root` marker file walked up to from the +checkout answers it instead. The probe is kept as a fallback, not replaced: a +remote session clones one repo with no workspace root above it to mark, so +`test_flat_workspace_without_a_marker_*` is the proof that this change can +only ADD correctness. """ import os @@ -70,7 +80,9 @@ def test_explicit_override_wins_in_both_resolvers(): os.environ["PYAUTO_ROOT"] = "/tmp/elsewhere" try: assert _pyauto_root.pyauto_root() == Path("/tmp/elsewhere") - assert _pyauto_root.workspace_root_reason()[1] == "PYAUTO_ROOT" + # The value is used whether or not a marker confirms it; only the + # reason says which (see the env-override test below). + assert _pyauto_root.workspace_root_reason()[1].startswith("PYAUTO_ROOT") finally: if old is None: del os.environ["PYAUTO_ROOT"] @@ -83,7 +95,13 @@ def test_root_resolves_beside_this_checkout(): old = os.environ.pop("PYAUTO_ROOT", None) try: root, reason = _pyauto_root.workspace_root_reason() - assert reason == "beside this checkout" + # A developer box marks its root; CI checks three repos out side by + # side with no marker and resolves by the sibling probe. Both are + # correct, and both must name the same directory. + if (BRAIN_HOME.parent / _pyauto_root.ROOT_MARKER).is_file(): + assert reason == f"{_pyauto_root.ROOT_MARKER} marker" + else: + assert reason == "beside this checkout" assert root == BRAIN_HOME.parent # ...and the resolved root really holds a sibling organ, which is the # whole claim: the old default could not have said this. @@ -122,3 +140,171 @@ def test_worktree_root_derives_from_the_resolved_root(): finally: if old is not None: os.environ["PYAUTO_WT_ROOT"] = old + + +# --------------------------------------------------------------------------- +# The marker walk: fake workspaces in tmp_path +# +# Each fixture is a real tree with a real copy of both resolvers in it — +# copies, not symlinks, because both resolvers deliberately follow symlinks +# (`Path.resolve()`, `readlink -f`) to find the checkout they live in, and a +# symlinked fixture would resolve back to this repo. +# --------------------------------------------------------------------------- + +MARKER = _pyauto_root.ROOT_MARKER + + +def _fake_workspace(tmp_path, brain="PyAutoBrain", also=(), marker=True): + """Build a workspace under tmp_path; return (root, brain checkout). + + `brain` is where the Brain checkout sits relative to the root ("PyAutoBrain" + for a flat layout, "organs/PyAutoBrain" for a grouped one) and `also` are + further directories to create, organ or library checkouts alike. + """ + root = tmp_path.resolve() + brain_home = root / brain + (brain_home / "agents").mkdir(parents=True) + (brain_home / "bin").mkdir(parents=True) + (brain_home / "agents" / "_pyauto_root.py").write_text( + PY_RESOLVER.read_text(encoding="utf-8"), encoding="utf-8" + ) + shell = brain_home / "bin" / "_pyauto_root.sh" + shell.write_text(SHELL_RESOLVER.read_text(encoding="utf-8"), encoding="utf-8") + for extra in also: + (root / extra).mkdir(parents=True, exist_ok=True) + if marker: + (root / MARKER).write_text("# fixture workspace root\n", encoding="utf-8") + return root, brain_home + + +def _clean_env(env_overrides=None): + env = dict(os.environ) + env.pop("PYAUTO_ROOT", None) + env.pop("PYAUTO_WT_ROOT", None) + env.update(env_overrides or {}) + return env + + +def _python_resolved(brain_home, env_overrides=None): + """(root, reason) as the copied Python resolver in `brain_home` sees it.""" + code = ( + "import sys; sys.path.insert(0, sys.argv[1]);" + " import _pyauto_root as r;" + " root, why = r.workspace_root_reason();" + " print(root); print(why)" + ) + r = subprocess.run( + [sys.executable, "-c", code, str(brain_home / "agents")], + capture_output=True, text=True, env=_clean_env(env_overrides), timeout=30, + ) + assert r.returncode == 0, r.stderr + root, reason = r.stdout.splitlines() + return Path(root), reason + + +def _shell_resolved(brain_home, env_overrides=None): + """(root, reason) as the copied shell resolver in `brain_home` sees it.""" + script = ( + f'. "{brain_home / "bin" / "_pyauto_root.sh"}";' + ' printf "%s\\n%s\\n" "$PYAUTO_ROOT" "$PYAUTO_ROOT_REASON"' + ) + r = subprocess.run( + ["bash", "-c", script], + capture_output=True, text=True, env=_clean_env(env_overrides), timeout=30, + ) + assert r.returncode == 0, r.stderr + root, reason = r.stdout.splitlines() + return Path(root), reason + + +def _both_resolvers_say(brain_home, env_overrides=None): + """(root, reason), asserted identical in Python and shell. + + The module's stated invariant: "the two must agree, because a shell agent + and the Python it shells out to have to resolve the same tree". + """ + py = _python_resolved(brain_home, env_overrides) + sh = _shell_resolved(brain_home, env_overrides) + assert py == sh, f"python said {py}, shell said {sh}" + return py + + +def test_marker_wins_in_a_nested_workspace(tmp_path): + """Checkouts grouped into subdirectories; the marked root is still the root. + + The grouping is what is under test, not which repos do it, so the checkouts + are fictional: one library family beside a directory of organs. + """ + root, brain = _fake_workspace( + tmp_path, also=("family/LibOne", "family/LibTwo", "organs/OrganOne") + ) + assert _both_resolvers_say(brain) == (root, f"{MARKER} marker") + + +def test_marker_wins_from_inside_a_family_directory(tmp_path): + """The Brain itself grouped under organs/ — the root is still one level up.""" + root, brain = _fake_workspace( + tmp_path, brain="organs/PyAutoBrain", also=("organs/PyAutoMind",) + ) + assert _both_resolvers_say(brain) == (root, f"{MARKER} marker") + + +def test_the_organs_family_directory_is_what_the_old_rule_got_wrong(tmp_path): + """The defect, pinned: the sibling probe alone answers `organs/`. + + `_is_root("/organs")` is true — it holds PyAutoMind — so the + pre-marker order returned the family directory, one level too deep, and + every `root / ` join below it missed silently. Removing the marker + from the fixture reproduces exactly that; the marker is what fixes it. + """ + root, brain = _fake_workspace( + tmp_path, brain="organs/PyAutoBrain", also=("organs/PyAutoMind",), + marker=False, + ) + assert _pyauto_root._is_root(root / "organs") + assert _both_resolvers_say(brain) == (root / "organs", "beside this checkout") + + # ...and with the marker written, the same tree resolves to the real root. + (root / MARKER).write_text("# fixture workspace root\n", encoding="utf-8") + assert _both_resolvers_say(brain) == (root, f"{MARKER} marker") + + +def test_flat_workspace_without_a_marker_still_resolves(tmp_path): + """The remote-session case: one clone layer, no root above it to mark. + + This is the regression guard for the whole change. The sibling probe is + demoted, never removed, so a workspace that resolved correctly before must + still resolve correctly — and by the same reason string. + """ + root, brain = _fake_workspace(tmp_path, also=("PyAutoMind",), marker=False) + assert _both_resolvers_say(brain) == (root, "beside this checkout") + + +def test_lone_checkout_without_marker_or_sibling_is_reported_unverified(tmp_path): + """Nothing to go on: the parent anyway, and said so.""" + root, brain = _fake_workspace(tmp_path, marker=False) + assert _both_resolvers_say(brain) == ( + root, "unverified (no sibling organ beside this checkout)" + ) + + +def test_env_override_is_honoured_and_the_marker_only_changes_the_reason(tmp_path): + """The operator's word stands; whether it is confirmed is visible.""" + root, brain = _fake_workspace(tmp_path, also=("PyAutoMind",)) + elsewhere = tmp_path.resolve() / "elsewhere" + elsewhere.mkdir() + + # Unconfirmed: still used — a hook exporting a wrong value is not + # overridden, only reported. + assert _both_resolvers_say(brain, {"PYAUTO_ROOT": str(elsewhere)}) == ( + elsewhere, f"PYAUTO_ROOT (unverified - no {MARKER} marker)" + ) + + # Confirmed by a marker of its own. + (elsewhere / MARKER).write_text("# fixture workspace root\n", encoding="utf-8") + assert _both_resolvers_say(brain, {"PYAUTO_ROOT": str(elsewhere)}) == ( + elsewhere, "PYAUTO_ROOT" + ) + + # Either way it beats the marker this checkout actually sits under. + assert elsewhere != root