diff --git a/config/repos.yaml b/config/repos.yaml index 363fe0a8..e945f14c 100644 --- a/config/repos.yaml +++ b/config/repos.yaml @@ -185,7 +185,6 @@ smoke: # Excluded — not polled. Listed here for documentation only. excluded: - - admin_jammy # personal tooling - autolens_assistant # public-facing template - autolens_profiling # profiling project - autolens_inference # inference benchmark project (search/inference runs; results tracked) diff --git a/heart/_common.sh b/heart/_common.sh index fdfd8844..9502e239 100644 --- a/heart/_common.sh +++ b/heart/_common.sh @@ -11,7 +11,8 @@ # HEART_LOG_DIR — daemon log files # HEART_PID_FILE — daemon pidfile # HEART_STATE_FILE — aggregated latest snapshot -# PYAUTO_ROOT — ~/Code/PyAutoLabs/ (where the repos live) +# PYAUTO_ROOT — the workspace root (where the repos live), and +# PYAUTO_ROOT_REASON / PYAUTO_WT_ROOT with it # # And the helper functions: # @@ -28,8 +29,11 @@ _heart_common_self="${BASH_SOURCE[0]}" HEART_HOME="$(cd "$(dirname "$_heart_common_self")/.." && pwd)" export HEART_HOME -PYAUTO_ROOT="${PYAUTO_ROOT:-$HOME/Code/PyAutoLabs}" -export PYAUTO_ROOT +# PYAUTO_ROOT (+ _REASON, _MARKER, PYAUTO_WT_ROOT) via the one shared +# resolver — the Brain's bin/_pyauto_root.sh when a checkout is in reach, the +# same rule applied locally when it is not. No workspace path is named here: +# the literal that used to be is right on one box and wrong everywhere else. +source "$HEART_HOME/heart/_workspace.sh" HEART_STATE_DIR="${HEART_STATE_DIR:-$HOME/.pyauto-heart}" HEART_PER_REPO_DIR="$HEART_STATE_DIR/per-repo" diff --git a/heart/_workspace.py b/heart/_workspace.py new file mode 100644 index 00000000..8e02eb33 --- /dev/null +++ b/heart/_workspace.py @@ -0,0 +1,230 @@ +"""heart/_workspace.py — where the workspace root is, asked in one place. + +The answer belongs to the organism, not to this organ: it lives in +``PyAutoBrain/agents/_pyauto_root.py`` (mirrored by ``bin/_pyauto_root.sh``, +and by ``heart/_workspace.sh`` on this side). This module is the Heart's +door to it — every Heart module that needs the root imports from here, so the +rule can move once, in the Brain, and the Heart follows. + +Heart used to roll its own answer in five places, and they disagreed: some +walked up from ``__file__`` and accepted the parent only when it was literally +named after this workspace's own directory, others fell back to a hard-coded +path under ``$HOME``. Both are instance facts — a task bundle is not named +after the workspace it belongs to, and a remote session's ``$HOME`` is not the +developer's — so both spellings resolved into directories that do not exist, +silently, because every consumer here degrades rather than raises. + +**Two concepts, not one.** "Where am I" and "which tree does the Heart grade" +are different questions, and conflating them relaxes a release gate by accident: + +``workspace_root()`` where this checkout is — siblings, config, the Brain, the + shared theme. Follows a ``.pyauto-root`` marker, so inside + a task bundle it is the bundle. Right for locating things. +``canonical_root()`` the MAIN checkout — the tree health grades. Never a task + bundle: a bundle's repos are git worktrees OF the + canonical repos, so git itself names the main checkout + (``rev-parse --git-common-dir``), whatever the cwd. +``wt_root()`` where task worktrees live — beside the canonical root, + never beside a bundle. + +Health is a release gate, and the documented way to grade a branch is to opt in +with ``$PYAUTO_ROOT``, which still wins over everything below. Without that +split, running the Heart from the bundle you happen to be working in graded the +bundle — the more flattering answer, reached by cwd alone. + +**No hard dependency on PyAutoBrain.** The Heart runs with no Brain in reach — +a standalone ``pip install pyauto-heart``, a single-repo session — which is why +``dashboard.theme()`` degrades instead of importing unconditionally. So does +this: when the Brain's resolver cannot be found, the rule below is applied +locally and the reason string says so, rather than a wrong root passing for a +right one. The local copy is deliberate duplication of a documented rule, kept +as short as it can be; the Brain's module is the one that explains it. + +Stdlib only; the Brain module is loaded by file path rather than by pushing a +directory onto ``sys.path``, so importing the Heart never changes what any +other ``import`` in this process resolves to. +""" + +from __future__ import annotations + +import importlib.util +import os +import subprocess +from pathlib import Path + +__all__ = [ + "workspace_root", + "workspace_root_reason", + "canonical_root", + "canonical_root_reason", + "wt_root", + "ROOT_MARKER", +] + +HEART_HOME = Path(__file__).resolve().parents[1] + +# Mirrors PyAutoBrain/agents/_pyauto_root.py. Only the degraded path below +# reads these; when the Brain is in reach its own values are used. +ROOT_MARKER = ".pyauto-root" +_SIBLING_ORGANS = ( + "PyAutoMind", + "PyAutoCortex", + "PyAutoMemory", + "PyAutoHeart", + "PyAutoHands", + "PyAutoNerves", + "PyAutoGut", +) + +_DEGRADED = " (no PyAutoBrain in reach)" + +_shared_cache: object | None = None + + +def _shared(): + """The Brain's resolver module, or None when no Brain checkout is in reach. + + Candidate order mirrors ``dashboard.theme()``: the explicit ``$PYAUTO_BRAIN`` + first, then a Brain beside this checkout (where CI puts it — heart-tests.yml + and heart-health.yml check PyAutoBrain out next to PyAutoHeart), then a + vendored one inside it. + """ + global _shared_cache + if _shared_cache is not None: + return _shared_cache or None + for cand in ( + os.environ.get("PYAUTO_BRAIN"), + HEART_HOME.parent / "PyAutoBrain", + HEART_HOME / "PyAutoBrain", + ): + if not cand: + continue + module_path = Path(cand) / "agents" / "_pyauto_root.py" + if not module_path.is_file(): + continue + try: + spec = importlib.util.spec_from_file_location( + "_pyauto_root", module_path + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + except Exception: # a broken/partial checkout must not break the Heart + continue + if not callable(getattr(module, "workspace_root_reason", None)): + continue # a resolver older than this API: degrade, do not raise + _shared_cache = module + return module + _shared_cache = False + return None + + +def _marked_root(start: Path) -> Path | None: + """The nearest ANCESTOR of `start` holding the marker, or None.""" + for candidate in start.parents: + if (candidate / ROOT_MARKER).is_file(): + return candidate + return None + + +def workspace_root_reason() -> tuple[Path, str]: + """``(root, why)`` — the workspace root and the rule that produced it. + + Callers that degrade should report the reason: "resolved to a directory + that does not exist" must not read the same as "resolved fine, found + nothing". + """ + shared = _shared() + if shared is not None: + return shared.workspace_root_reason() + # Degraded: the same order as the Brain's module, applied here. The + # environment override comes first, so an operator's word still wins. + env = os.environ.get("PYAUTO_ROOT") + if env: + if (Path(env) / ROOT_MARKER).is_file(): + return Path(env), "PYAUTO_ROOT" + _DEGRADED + return ( + Path(env), + f"PYAUTO_ROOT (unverified - no {ROOT_MARKER} marker)" + _DEGRADED, + ) + marked = _marked_root(HEART_HOME) + if marked is not None: + return marked, f"{ROOT_MARKER} marker" + _DEGRADED + parent = HEART_HOME.parent + if any((parent / organ).is_dir() for organ in _SIBLING_ORGANS): + return parent, "beside this checkout" + _DEGRADED + return parent, "unverified (no sibling organ beside this checkout)" + _DEGRADED + + +def workspace_root() -> Path: + """The workspace root — the directory holding the organ checkouts.""" + return Path(workspace_root_reason()[0]) + + +_canonical_cache: tuple[Path, str] | None = None + + +def _canonical_from_git(start: Path) -> Path | None: + """The main checkout's workspace root, as git reports it, or None. + + A task bundle's repos are linked git worktrees of the canonical repos, and + a linked worktree's *common* dir is the main repo's ``.git`` — so git + already knows where the main checkout is, and says so from inside a bundle + as readily as from the canonical tree. From the canonical checkout the + answer comes back relative (``.git``), which resolves to the same place. + + ``//.git`` -> ````. + """ + try: + result = subprocess.run( + ["git", "-C", str(start), "rev-parse", "--git-common-dir"], + capture_output=True, text=True, timeout=10, + ) + except (OSError, subprocess.SubprocessError): # no git at all + return None + if result.returncode != 0 or not result.stdout.strip(): + return None + common = Path(result.stdout.strip()) + if not common.is_absolute(): + common = start / common + return common.resolve().parent.parent + + +def canonical_root_reason() -> tuple[Path, str]: + """``(root, why)`` — the MAIN checkout's workspace root, for grading. + + ``$PYAUTO_ROOT`` first, so the documented "grade this branch" opt-in still + works exactly as it does today; then git; then the workspace root as a last + resort, with a reason that says the main checkout could not be named. + """ + global _canonical_cache + env = os.environ.get("PYAUTO_ROOT") + if env: + return Path(env), "PYAUTO_ROOT" + if _canonical_cache is not None: + return _canonical_cache + from_git = _canonical_from_git(HEART_HOME) + if from_git is not None: + _canonical_cache = (from_git, "main checkout (git --git-common-dir)") + else: + root, why = workspace_root_reason() + _canonical_cache = (root, f"workspace root — git could not name the main checkout ({why})") + return _canonical_cache + + +def canonical_root() -> Path: + """The MAIN checkout's workspace root — the tree the Heart grades.""" + return Path(canonical_root_reason()[0]) + + +def wt_root() -> Path: + """Where task worktrees live: beside the CANONICAL root, suffixed ``-wt``. + + Never beside a task bundle — a bundle has no ``-wt`` sibling of its own, + and the drift check that reads this compares what is on disk against the + Mind's claims, which are claims on the one worktree area. + """ + env = os.environ.get("PYAUTO_WT_ROOT") + if env: + return Path(env) + root = canonical_root() + return root.parent / f"{root.name}-wt" diff --git a/heart/_workspace.sh b/heart/_workspace.sh new file mode 100644 index 00000000..11af4cb2 --- /dev/null +++ b/heart/_workspace.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# heart/_workspace.sh — where the workspace root is, asked in one place. +# +# The shell half of heart/_workspace.py, and the same contract: the answer +# belongs to the organism, so it is asked of PyAutoBrain/bin/_pyauto_root.sh +# whenever a Brain checkout is in reach, and only applied locally when it is +# not. Sourcing this sets, exactly as the Brain's file does: +# +# PYAUTO_ROOT — the directory holding the organ checkouts +# PYAUTO_ROOT_REASON — the rule that produced it (say so when degrading) +# PYAUTO_ROOT_MARKER — the marker filename (.pyauto-root) +# PYAUTO_WT_ROOT — where task worktrees live +# +# plus one of the Heart's own, because "where am I" and "which tree do I grade" +# are different questions: +# +# PYAUTO_MAIN_ROOT — the MAIN checkout: the tree health grades. Never a +# task bundle. A bundle's repos are git worktrees OF +# the canonical repos, so git names the main checkout +# (`rev-parse --git-common-dir`) whatever the cwd. +# PYAUTO_MAIN_ROOT_REASON — the rule that produced it +# +# Health is a release gate, and grading a branch is an opt-in: $PYAUTO_ROOT +# wins over both. Without the split, running the Heart from the bundle you +# happen to be working in graded the bundle — the more flattering answer, +# reached by cwd alone. +# +# An explicit PYAUTO_ROOT / PYAUTO_WT_ROOT in the environment still wins: this +# replaces the DEFAULT — which used to be a path spelled out under $HOME, +# right on one developer's box and nowhere else — never the override. + +if [ -z "${_HEART_WORKSPACE_SOURCED:-}" ]; then +_HEART_WORKSPACE_SOURCED=1 + +_heart_workspace_home="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)" + +# Whether the operator named a root, recorded BEFORE the resolver runs: after +# it, PYAUTO_ROOT is always set and the two cases are indistinguishable. +_heart_workspace_env_root="${PYAUTO_ROOT:-}" + +# The Brain's resolver, if a checkout is in reach. Candidate order mirrors +# dashboard.theme(): $PYAUTO_BRAIN, then beside this checkout (where CI puts +# it), then vendored inside it. +_heart_workspace_shared="" +for _heart_cand in "${PYAUTO_BRAIN:-}" \ + "$_heart_workspace_home/../PyAutoBrain" \ + "$_heart_workspace_home/PyAutoBrain"; do + [ -n "$_heart_cand" ] || continue + if [ -f "$_heart_cand/bin/_pyauto_root.sh" ]; then + _heart_workspace_shared="$_heart_cand/bin/_pyauto_root.sh" + break + fi +done + +if [ -n "$_heart_workspace_shared" ]; then + . "$_heart_workspace_shared" + # A PyAutoBrain checkout older than the marker rule sets only PYAUTO_ROOT. + # Fill the rest in rather than leave a caller reading an unset variable + # under `set -u`; the reason says the root came from there either way. + PYAUTO_ROOT_MARKER="${PYAUTO_ROOT_MARKER:-.pyauto-root}" + PYAUTO_ROOT_REASON="${PYAUTO_ROOT_REASON:-PyAutoBrain resolver (no reason reported)}" + PYAUTO_WT_ROOT="${PYAUTO_WT_ROOT:-${PYAUTO_ROOT}-wt}" + export PYAUTO_ROOT_MARKER PYAUTO_ROOT_REASON PYAUTO_WT_ROOT +else + # Degraded: the same order, applied here, with the reason saying so — a + # wrong root must never read like a right one. The Heart runs with no Brain + # in reach (a standalone install, a single-repo session), which is the same + # case dashboard.theme() degrades for. + PYAUTO_ROOT_MARKER=".pyauto-root" + export PYAUTO_ROOT_MARKER + if [ -n "${PYAUTO_ROOT:-}" ]; then + if [ -f "$PYAUTO_ROOT/$PYAUTO_ROOT_MARKER" ]; then + PYAUTO_ROOT_REASON="PYAUTO_ROOT (no PyAutoBrain in reach)" + else + PYAUTO_ROOT_REASON="PYAUTO_ROOT (unverified - no $PYAUTO_ROOT_MARKER marker) (no PyAutoBrain in reach)" + fi + else + _heart_d="$(dirname "$_heart_workspace_home")" + PYAUTO_ROOT="" + while [ "$_heart_d" != "/" ]; do + if [ -f "$_heart_d/$PYAUTO_ROOT_MARKER" ]; then + PYAUTO_ROOT="$_heart_d" + PYAUTO_ROOT_REASON="$PYAUTO_ROOT_MARKER marker (no PyAutoBrain in reach)" + break + fi + _heart_d="$(dirname "$_heart_d")" + done + if [ -z "$PYAUTO_ROOT" ]; then + PYAUTO_ROOT="$(dirname "$_heart_workspace_home")" + if [ -d "$PYAUTO_ROOT/PyAutoMind" ] || [ -d "$PYAUTO_ROOT/PyAutoHeart" ] \ + || [ -d "$PYAUTO_ROOT/PyAutoHands" ] || [ -d "$PYAUTO_ROOT/PyAutoMemory" ] \ + || [ -d "$PYAUTO_ROOT/PyAutoGut" ] || [ -d "$PYAUTO_ROOT/PyAutoNerves" ] \ + || [ -d "$PYAUTO_ROOT/PyAutoCortex" ]; then + PYAUTO_ROOT_REASON="beside this checkout (no PyAutoBrain in reach)" + else + PYAUTO_ROOT_REASON="unverified (no sibling organ beside this checkout) (no PyAutoBrain in reach)" + fi + fi + fi + export PYAUTO_ROOT PYAUTO_ROOT_REASON + PYAUTO_WT_ROOT="${PYAUTO_WT_ROOT:-${PYAUTO_ROOT}-wt}" + export PYAUTO_WT_ROOT +fi + +# The MAIN checkout — the tree the grading checks read. $PYAUTO_ROOT first, so +# the documented "grade this branch" opt-in keeps working; then git, which +# names the main repo of any linked worktree (and, from the canonical checkout, +# answers `.git` relative to it — one code path, both layouts); then the +# workspace root as a last resort, saying so. +if [ -n "$_heart_workspace_env_root" ]; then + PYAUTO_MAIN_ROOT="$_heart_workspace_env_root" + PYAUTO_MAIN_ROOT_REASON="PYAUTO_ROOT" +else + _heart_common_dir="$(git -C "$_heart_workspace_home" rev-parse --git-common-dir 2>/dev/null)" || _heart_common_dir="" + case "$_heart_common_dir" in + ""|/*) ;; + *) _heart_common_dir="$_heart_workspace_home/$_heart_common_dir" ;; + esac + # //.git -> + if [ -n "$_heart_common_dir" ] && [ -e "$_heart_common_dir" ]; then + PYAUTO_MAIN_ROOT="$(cd "$(dirname "$(dirname "$_heart_common_dir")")" && pwd)" + PYAUTO_MAIN_ROOT_REASON="main checkout (git --git-common-dir)" + else + PYAUTO_MAIN_ROOT="$PYAUTO_ROOT" + PYAUTO_MAIN_ROOT_REASON="workspace root — git could not name the main checkout ($PYAUTO_ROOT_REASON)" + fi +fi +export PYAUTO_MAIN_ROOT PYAUTO_MAIN_ROOT_REASON + +fi diff --git a/heart/checks/manifest_drift.py b/heart/checks/manifest_drift.py index 79e427eb..a8e24d9f 100644 --- a/heart/checks/manifest_drift.py +++ b/heart/checks/manifest_drift.py @@ -31,12 +31,12 @@ from pathlib import Path from typing import Any +from heart import _workspace + HEART_HOME = Path(__file__).resolve().parents[2] -_p3 = Path(__file__).resolve().parents[3] -PYAUTO_ROOT = Path( - os.environ.get("PYAUTO_ROOT") - or (_p3 if _p3.name == "PyAutoLabs" else Path.home() / "Code" / "PyAutoLabs") -) +# $PYAUTO_ROOT first, then the MAIN checkout — grading reads the canonical +# tree, not a task bundle. See heart/_workspace.py. +PYAUTO_ROOT = _workspace.canonical_root() HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" diff --git a/heart/checks/profiling_drift.py b/heart/checks/profiling_drift.py index 4d489612..00cc6b8a 100644 --- a/heart/checks/profiling_drift.py +++ b/heart/checks/profiling_drift.py @@ -31,12 +31,16 @@ from pathlib import Path from typing import Any +from heart import _workspace + HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" ) HEART_HOME = Path(__file__).resolve().parents[2] -PYAUTO_ROOT = Path(__file__).resolve().parents[3] if Path(__file__).resolve().parents[3].name == "PyAutoLabs" else Path.home() / "Code" / "PyAutoLabs" +# The MAIN checkout via the one shared resolver — grading reads the +# canonical tree, not a task bundle. See heart/_workspace.py. +PYAUTO_ROOT = _workspace.canonical_root() RESULTS_ROOT = PYAUTO_ROOT / "autolens_profiling" / "results" diff --git a/heart/checks/repo_state.sh b/heart/checks/repo_state.sh index 4e0fddfd..793aaa89 100755 --- a/heart/checks/repo_state.sh +++ b/heart/checks/repo_state.sh @@ -13,7 +13,7 @@ check_one_repo() { local owner_name="$1" local group="$2" local name="${owner_name##*/}" - local repo_path="$PYAUTO_ROOT/$name" + local repo_path="$PYAUTO_MAIN_ROOT/$name" if [[ ! -d "$repo_path/.git" ]]; then heart_write_json "$HEART_PER_REPO_DIR/$name.repo_state.json" "$(printf '{"name":"%s","present":false,"group":"%s"}' "$name" "$group")" diff --git a/heart/checks/script_timing.py b/heart/checks/script_timing.py index a01c9d9c..ced6ed89 100644 --- a/heart/checks/script_timing.py +++ b/heart/checks/script_timing.py @@ -68,6 +68,8 @@ import yaml +from heart import _workspace + HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" @@ -75,7 +77,9 @@ HEART_TIMINGS_DIR = HEART_STATE_DIR / "timings" HEART_HOME = Path(__file__).resolve().parents[2] CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" -PYAUTO_ROOT = Path(__file__).resolve().parents[3] if Path(__file__).resolve().parents[3].name == "PyAutoLabs" else Path.home() / "Code" / "PyAutoLabs" +# The MAIN checkout via the one shared resolver — grading reads the +# canonical tree, not a task bundle. See heart/_workspace.py. +PYAUTO_ROOT = _workspace.canonical_root() TEST_RESULTS_LATEST = PYAUTO_ROOT / "PyAutoHands" / "run_logs" / "latest" # Distinct runs the prior window must hold before a ratio is a verdict rather diff --git a/heart/checks/test_run.py b/heart/checks/test_run.py index 54dbe7a9..2cafc9b6 100644 --- a/heart/checks/test_run.py +++ b/heart/checks/test_run.py @@ -36,10 +36,13 @@ from pathlib import Path from typing import Any, Callable -# Reuse the same root/latest resolution as script_timing.py. +from heart import _workspace + +# Reuse the same root/latest resolution as script_timing.py: the one shared +# resolver, via heart/_workspace.py, asked for the MAIN checkout — grading +# reads the canonical tree, not a task bundle. 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_ROOT = _workspace.canonical_root() TEST_RESULTS_LATEST = PYAUTO_ROOT / "PyAutoHands" / "run_logs" / "latest" HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") diff --git a/heart/checks/unit_test_timing.py b/heart/checks/unit_test_timing.py index af6e949f..0a44e9bc 100644 --- a/heart/checks/unit_test_timing.py +++ b/heart/checks/unit_test_timing.py @@ -38,6 +38,8 @@ import yaml +from heart import _workspace + HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" @@ -144,7 +146,7 @@ def run(runner: Runner | None = None, repos: list[str] | None = None) -> dict[st repos = repos if repos is not None else DEFAULT_REPOS python = os.environ.get("HYGIENE_PYTHON", "python3") timeout = float(os.environ.get("HEART_UNIT_TEST_TIMEOUT", "1800")) - root = Path(os.environ.get("PYAUTO_ROOT", str(Path.home() / "Code" / "PyAutoLabs"))) + root = _workspace.canonical_root() # grading: the main checkout runner = runner or default_runner(python, timeout, top_n) findings: dict[str, list[dict[str, Any]]] = {"red": [], "yellow": [], "green": []} diff --git a/heart/checks/url_sweep.sh b/heart/checks/url_sweep.sh index 602f992c..d3fc8c6a 100755 --- a/heart/checks/url_sweep.sh +++ b/heart/checks/url_sweep.sh @@ -35,7 +35,7 @@ check_url_sweep() { local rows="" local repo dir out rc findings for repo in "${URL_CHECK_REPOS[@]}"; do - dir="$PYAUTO_ROOT/$repo" + dir="$PYAUTO_MAIN_ROOT/$repo" if [[ ! -d "$dir" ]]; then rows+="${repo}|0|0"$'\n' continue diff --git a/heart/checks/version_skew.py b/heart/checks/version_skew.py index 6cf57c9e..4351c061 100644 --- a/heart/checks/version_skew.py +++ b/heart/checks/version_skew.py @@ -62,10 +62,13 @@ import yaml +from heart import _workspace + HEART_HOME = Path(__file__).resolve().parents[2] CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" -_p3 = Path(__file__).resolve().parents[3] -PYAUTO_ROOT = _p3 if _p3.name == "PyAutoLabs" else Path.home() / "Code" / "PyAutoLabs" +# The MAIN checkout via the one shared resolver — grading reads the +# canonical tree, not a task bundle. See heart/_workspace.py. +PYAUTO_ROOT = _workspace.canonical_root() HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" diff --git a/heart/checks/workspace_testmode_timing.py b/heart/checks/workspace_testmode_timing.py index 0587b6c5..f06d57f7 100644 --- a/heart/checks/workspace_testmode_timing.py +++ b/heart/checks/workspace_testmode_timing.py @@ -40,6 +40,8 @@ import yaml +from heart import _workspace + HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" @@ -137,7 +139,7 @@ def run(runner: Runner | None = None, scripts: list[tuple[str, str]] | None = No scripts = scripts if scripts is not None else DEFAULT_SCRIPTS python = os.environ.get("HYGIENE_PYTHON", "python3") timeout = float(os.environ.get("HEART_WS_SCRIPT_TIMEOUT", "300")) - root = Path(os.environ.get("PYAUTO_ROOT", str(Path.home() / "Code" / "PyAutoLabs"))) + root = _workspace.canonical_root() # grading: the main checkout runner = runner or default_runner(root, python, timeout) findings: dict[str, list[dict[str, Any]]] = {"red": [], "yellow": [], "green": []} diff --git a/heart/checks/worktree_drift.py b/heart/checks/worktree_drift.py index 914c97a0..79bcd2f0 100644 --- a/heart/checks/worktree_drift.py +++ b/heart/checks/worktree_drift.py @@ -12,7 +12,7 @@ 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 +non-claimed repo back to the canonical checkout, 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. @@ -42,10 +42,20 @@ from pathlib import Path from typing import Any +from heart import _workspace + 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") +# The MAIN checkout and its worktree area, via the one shared resolver +# (heart/_workspace.py). Grading reads the canonical tree, never the bundle +# this module may be running from — `canonical_root()` asks git which checkout +# a worktree belongs to. This used to accept the grandparent only when it was +# literally named after this workspace's directory, and otherwise reach for a +# hard-coded path under `$HOME` — writing that directory's name twice, in the +# one check whose whole job is to look at task bundles, which are never named +# after it. $PYAUTO_ROOT / +# $PYAUTO_WT_ROOT still win, so grading a branch stays a one-variable opt-in. +PYAUTO_ROOT = _workspace.canonical_root() +PYAUTO_WT_ROOT = _workspace.wt_root() 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") diff --git a/heart/dashboard.py b/heart/dashboard.py index 0957f732..904c7074 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -53,7 +53,7 @@ from dataclasses import dataclass, field from typing import Any, Iterable, Sequence -from heart import validate +from heart import _workspace, validate from heart.checks.test_run import counts_measured as tr_counts_measured from heart.heart_color import ( c_bold, c_dim, c_fail, c_info, c_meta, c_ok, c_warn, @@ -170,13 +170,16 @@ def _library_names() -> tuple: def _workspace_root() -> pathlib.Path: - """Where the sibling PyAuto checkouts live: `$PYAUTO_ROOT`, else `~/Code`. - - The org's own directory name is an instance fact, so it is never written - here — a workspace that does not follow the default sets `$PYAUTO_ROOT` - (the same variable the dev-flow doors read). + """Where the sibling PyAuto checkouts live — via `heart/_workspace.py`. + + The workspace directory's own name is an instance fact, so it is never + written here; neither is the `$HOME`-relative path this used to fall back + to. That fallback named the directory ABOVE the workspace, so `_workspace_root() / + "PyAutoBrain"` pointed at a path that has never existed — masked only + because `theme()` tries it last, after the sibling checkout that answers. + `$PYAUTO_ROOT` still wins, as the resolver's first rule. """ - return pathlib.Path(os.environ.get("PYAUTO_ROOT") or pathlib.Path.home() / "Code") + return _workspace.workspace_root() def theme(): diff --git a/heart/fix.py b/heart/fix.py index f3bc4b00..c2ea0947 100644 --- a/heart/fix.py +++ b/heart/fix.py @@ -22,7 +22,7 @@ import sys from pathlib import Path -from heart import state +from heart import _workspace, state from heart.heart_color import c_bold, c_fail, c_info, c_meta, c_ok, c_warn @@ -65,7 +65,7 @@ def fix_ci(repo: str) -> int: "Investigate the latest red CI run on this repo. Pull the failing", "job log tail via `gh run view --log-failed`, identify which", "step(s) failed, and propose a minimal fix as a plan. Repo is at", - f"~/Code/PyAutoLabs/{name}.", + f"{_workspace.canonical_root()}/{name}.", ] print("\n".join(body_lines)) return 0 @@ -130,7 +130,7 @@ def fix_dirty(repo: str) -> int: print(c_info("# Paste/run this in a fresh Claude Code session:"), file=sys.stderr) print() print(f"# Clean up the dirty working tree in {repo}") - print(f"# Repo: ~/Code/PyAutoLabs/{repo}") + print(f"# Repo: {_workspace.canonical_root()}/{repo}") print() print("## Generated artifacts (regenerated by build/simulator runs)") print("# These are almost always safe to revert (`git checkout -- `)") diff --git a/heart/tick.sh b/heart/tick.sh index 5730a8e5..61e1b12f 100755 --- a/heart/tick.sh +++ b/heart/tick.sh @@ -21,14 +21,19 @@ bash "$HEART_HOME/heart/checks/open_prs.sh" || heart_log WARN "$(c_warn ' bash "$HEART_HOME/heart/checks/worktree_drift.sh" || heart_log WARN "$(c_warn 'worktree_drift failed')" # Python: script timing regressions. Needs a local PyAutoHands run_logs/latest. -if [[ -d "$PYAUTO_ROOT/PyAutoHands/run_logs/latest" ]]; then +if [[ -d "$PYAUTO_MAIN_ROOT/PyAutoHands/run_logs/latest" ]]; then PYTHONPATH="$HEART_HOME" python3 -m heart.checks.script_timing || heart_log WARN "$(c_warn 'script_timing failed')" else heart_log INFO "$(c_meta 'script_timing: skipped (no PyAutoHands/run_logs/latest)')" fi # Python: profiling pinned-value drift. Reads autolens_profiling result JSONs. -if [ -d "$PYAUTO_ROOT/autolens_profiling/results" ] 2>/dev/null || [ -d "$HEART_HOME/../autolens_profiling/results" ]; then +# One root, not two: `$HEART_HOME/..` was a second, hand-rolled guess at the +# workspace root, and it could answer differently from the module's own — the +# guard firing on a tree the check then failed to find. Every guard here reads +# $PYAUTO_MAIN_ROOT, the tree the checks themselves grade, from +# heart/_workspace.{sh,py}. +if [ -d "$PYAUTO_MAIN_ROOT/autolens_profiling/results" ] 2>/dev/null; then PYTHONPATH="$HEART_HOME" python3 -m heart.checks.profiling_drift || heart_log WARN "$(c_warn 'profiling_drift failed')" else heart_log INFO "$(c_meta 'profiling_drift: skipped (no autolens_profiling/results)')" @@ -56,7 +61,7 @@ PYTHONPATH="$HEART_HOME" python3 -m heart.checks.required_workflow_drift || hear # Python: body-map identity drift — PyAutoMind/repos.yaml vs Heart/Build/labels # repo lists and every checkout's origin (delegates to repos_sync.py --check). -if [[ -f "$PYAUTO_ROOT/PyAutoMind/scripts/repos_sync.py" ]]; then +if [[ -f "$PYAUTO_MAIN_ROOT/PyAutoMind/scripts/repos_sync.py" ]]; then PYTHONPATH="$HEART_HOME" python3 -m heart.checks.manifest_drift || heart_log WARN "$(c_warn 'manifest_drift failed')" else heart_log INFO "$(c_meta 'manifest_drift: skipped (no PyAutoMind checkout)')" diff --git a/scripts/health_audit.sh b/scripts/health_audit.sh index d447f822..9c15b927 100644 --- a/scripts/health_audit.sh +++ b/scripts/health_audit.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # health_audit.sh — on-demand structural repo-health audit. # -# Defines `_health_audit` (run via `health audit`) that scans ~/Code/PyAutoLabs/ +# Defines `_health_audit` (run via `health audit`) that scans the workspace root # for state the git-sync dashboard (`health` / `health sync`) doesn't surface: # # 1. Top-level directories with no .git (intentionally-not-a-repo or bug). @@ -18,11 +18,18 @@ # health audit # # Override via env vars: -# PYAUTO_AUDIT_ROOT scan root (default $HOME/Code/PyAutoLabs) +# PYAUTO_AUDIT_ROOT scan root (default: the resolved workspace root) # PYAUTO_AUDIT_STASH_DAYS stash age threshold in days (default 14) # PYAUTO_AUDIT_BRANCH_DAYS branch age threshold in days (default 30) -PYAUTO_AUDIT_ROOT="${PYAUTO_AUDIT_ROOT:-$HOME/Code/PyAutoLabs}" +# The scan root: this override first, else the MAIN checkout from the one +# shared resolver (heart/_workspace.sh) — these dashboards report on the +# canonical tree, never on a task bundle. Sourced in a subshell so a script that +# lives in the user's ~/.bashrc does not export PYAUTO_ROOT into every shell. +_health_audit_self="$(readlink -f "${BASH_SOURCE[0]}")" +PYAUTO_AUDIT_ROOT="${PYAUTO_AUDIT_ROOT:-$( + . "$(dirname "$_health_audit_self")/../heart/_workspace.sh"; printf '%s' "$PYAUTO_MAIN_ROOT" +)}" PYAUTO_AUDIT_STASH_DAYS="${PYAUTO_AUDIT_STASH_DAYS:-14}" PYAUTO_AUDIT_BRANCH_DAYS="${PYAUTO_AUDIT_BRANCH_DAYS:-30}" diff --git a/scripts/health_release.sh b/scripts/health_release.sh index b74620d1..d0c76be2 100755 --- a/scripts/health_release.sh +++ b/scripts/health_release.sh @@ -28,7 +28,16 @@ # layer over the same run artefacts). This function prints straight to stdout, # no Claude needed. -PYAUTO_STATUS_FULL_DEFAULT="${PYAUTO_STATUS_FULL_DEFAULT:-$HOME/Code/PyAutoLabs/PyAutoHands/run_logs/latest}" +# The run to read: this override first, else PyAutoHands/run_logs/latest under +# the MAIN checkout from the one shared resolver (heart/_workspace.sh) — the +# run logs live in the canonical tree, never in a task bundle. +# Sourced in a subshell so a script that lives in the user's ~/.bashrc does not +# export PYAUTO_ROOT into every shell. +_health_release_self="$(readlink -f "${BASH_SOURCE[0]}")" +PYAUTO_STATUS_FULL_DEFAULT="${PYAUTO_STATUS_FULL_DEFAULT:-$( + . "$(dirname "$_health_release_self")/../heart/_workspace.sh" + printf '%s' "$PYAUTO_MAIN_ROOT/PyAutoHands/run_logs/latest" +)}" _health_release() { local run_dir="${1:-$PYAUTO_STATUS_FULL_DEFAULT}" diff --git a/scripts/health_sync.sh b/scripts/health_sync.sh index 297088e8..07949d10 100644 --- a/scripts/health_sync.sh +++ b/scripts/health_sync.sh @@ -54,7 +54,14 @@ # `/health status` shows planned / active / complete tasks. Different views, # both under the "health" vocabulary. -PYAUTO_STATUS_ROOT="${PYAUTO_STATUS_ROOT:-$HOME/Code/PyAutoLabs}" +# The scan root: this override first, else the MAIN checkout from the one +# shared resolver (heart/_workspace.sh) — these dashboards report on the +# canonical tree, never on a task bundle. Sourced in a subshell so a script that +# lives in the user's ~/.bashrc does not export PYAUTO_ROOT into every shell. +_health_sync_self="$(readlink -f "${BASH_SOURCE[0]}")" +PYAUTO_STATUS_ROOT="${PYAUTO_STATUS_ROOT:-$( + . "$(dirname "$_health_sync_self")/../heart/_workspace.sh"; printf '%s' "$PYAUTO_MAIN_ROOT" +)}" _health_sync() { local root="$PYAUTO_STATUS_ROOT" @@ -337,7 +344,7 @@ _health_sync() { fi # Smoke tests. Reads per-workspace JSON written by the /smoke-test skill - # (admin_jammy/skills/smoke_test/SKILL.md step 7). One python invocation + # (PyAutoHeart/skills/smoke_test/SKILL.md step 7). One python invocation # parses all files; bash formats with ANSI color (green if failed=0). local smoke_dir="$HOME/.cache/pyauto/smoke" if [[ -d "$smoke_dir" ]] && compgen -G "$smoke_dir/*.json" > /dev/null; then