diff --git a/heart/_common.sh b/heart/_common.sh index 9502e239..f92711c5 100644 --- a/heart/_common.sh +++ b/heart/_common.sh @@ -35,6 +35,10 @@ export HEART_HOME # the literal that used to be is right on one box and wrong everywhere else. source "$HEART_HOME/heart/_workspace.sh" +heart_repo_path() { + PYTHONPATH="$HEART_HOME" python3 -c 'import sys; from pathlib import Path; from heart import _workspace; print(_workspace.repo_path(Path(sys.argv[1]), sys.argv[2]))' "$PYAUTO_MAIN_ROOT" "$1" +} + HEART_STATE_DIR="${HEART_STATE_DIR:-$HOME/.pyauto-heart}" HEART_PER_REPO_DIR="$HEART_STATE_DIR/per-repo" # Agent/MCP-supplied CI run payloads, one per repo — the mobile/cloud path diff --git a/heart/_workspace.py b/heart/_workspace.py index 8e02eb33..5ef9d3cc 100644 --- a/heart/_workspace.py +++ b/heart/_workspace.py @@ -58,6 +58,8 @@ "canonical_root", "canonical_root_reason", "wt_root", + "repo_path", + "iter_checkouts", "ROOT_MARKER", ] @@ -96,6 +98,7 @@ def _shared(): os.environ.get("PYAUTO_BRAIN"), HEART_HOME.parent / "PyAutoBrain", HEART_HOME / "PyAutoBrain", + *(child / "PyAutoBrain" for child in HEART_HOME.parent.iterdir() if child.is_dir() and not (child / ".git").exists()), ): if not cand: continue @@ -160,6 +163,45 @@ def workspace_root() -> Path: return Path(workspace_root_reason()[0]) +def _repo_paths(): + for base in (os.environ.get("PYAUTO_BRAIN"), HEART_HOME.parent / "PyAutoBrain", HEART_HOME / "PyAutoBrain", workspace_root() / "PyAutoBrain", *(child / "PyAutoBrain" for child in workspace_root().iterdir() if child.is_dir() and not (child / ".git").exists())): + if not base: + continue + source = Path(base) / "agents" / "_repo_paths.py" + if source.is_file(): + spec = importlib.util.spec_from_file_location("_pyauto_repo_paths", source) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + return None + + +def repo_path(root: Path, name: str, required: bool = False) -> Path: + """Locate a checkout through Brain when available, with flat CI fallback.""" + shared = _repo_paths() + if shared is not None and callable(getattr(shared, "repo_path", None)): + return shared.repo_path(Path(root), name, required=required) + path = Path(root) / name + if required and not (path / ".git").exists(): + raise FileNotFoundError(f"Missing checkout {name}: {path}") + if not path.exists() and any( + child.is_dir() and (child / name).exists() for child in Path(root).iterdir() + ): + raise RuntimeError(f"Grouped checkout {name} needs PyAutoBrain repo resolver") + return path + + +def iter_checkouts(root: Path) -> list[Path]: + shared = _repo_paths() + if shared is not None and callable(getattr(shared, "iter_checkouts", None)): + return shared.iter_checkouts(Path(root)) + if any((nested / ".git").exists() for child in Path(root).iterdir() + if child.is_dir() and not (child / ".git").exists() + for nested in child.iterdir() if nested.is_dir()): + raise RuntimeError("Grouped checkouts need PyAutoBrain repo resolver") + return [p for p in Path(root).iterdir() if (p / ".git").exists()] + + _canonical_cache: tuple[Path, str] | None = None diff --git a/heart/checks/manifest_drift.py b/heart/checks/manifest_drift.py index a8e24d9f..ff2f1542 100644 --- a/heart/checks/manifest_drift.py +++ b/heart/checks/manifest_drift.py @@ -63,7 +63,7 @@ def parse_check_output(text: str) -> dict[str, dict[str, Any]]: def run() -> dict[str, Any]: - script = PYAUTO_ROOT / "PyAutoMind" / "scripts" / "repos_sync.py" + script = _workspace.repo_path(PYAUTO_ROOT, "PyAutoMind") / "scripts" / "repos_sync.py" result: dict[str, Any] if not script.is_file(): result = {"available": False, "reason": f"missing {script}", "checks": {}} diff --git a/heart/checks/profiling_drift.py b/heart/checks/profiling_drift.py index 00cc6b8a..b307fd7f 100644 --- a/heart/checks/profiling_drift.py +++ b/heart/checks/profiling_drift.py @@ -41,7 +41,7 @@ # 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" +RESULTS_ROOT = _workspace.repo_path(PYAUTO_ROOT, "autolens_profiling") / "results" def scan_results(results_root: Path) -> dict[str, Any]: diff --git a/heart/checks/repo_state.sh b/heart/checks/repo_state.sh index 793aaa89..fa685186 100755 --- a/heart/checks/repo_state.sh +++ b/heart/checks/repo_state.sh @@ -13,9 +13,10 @@ check_one_repo() { local owner_name="$1" local group="$2" local name="${owner_name##*/}" - local repo_path="$PYAUTO_MAIN_ROOT/$name" + local repo_path + repo_path="$(heart_repo_path "$name")" || return 1 - if [[ ! -d "$repo_path/.git" ]]; then + if [[ ! -e "$repo_path/.git" ]]; then heart_write_json "$HEART_PER_REPO_DIR/$name.repo_state.json" "$(printf '{"name":"%s","present":false,"group":"%s"}' "$name" "$group")" heart_log WARN "$(c_warn "$name") — repo missing on disk" return @@ -74,14 +75,23 @@ check_one_repo() { check_repo_state_all() { heart_state_dir heart_log INFO "$(c_info "repo_state: scanning $(load_repos_yaml | wc -l) repos")" + local -a repo_pids=() + local repo_pid failed=0 while read -r line; do [[ -z "$line" ]] && continue local owner_name group owner_name="${line%% *}" group="${line##* }" check_one_repo "$owner_name" "$group" & + repo_pids+=("$!") done < <(load_repos_yaml) - wait + for repo_pid in "${repo_pids[@]}"; do + wait "$repo_pid" || failed=1 + done + if [[ "$failed" -ne 0 ]]; then + heart_log WARN "repo_state: checkout resolution/check failed" + return 1 + fi heart_log OK "$(c_ok "repo_state: done")" } diff --git a/heart/checks/script_timing.py b/heart/checks/script_timing.py index ced6ed89..c1bbe8f5 100644 --- a/heart/checks/script_timing.py +++ b/heart/checks/script_timing.py @@ -80,7 +80,7 @@ # 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" +TEST_RESULTS_LATEST = _workspace.repo_path(PYAUTO_ROOT, "PyAutoHands") / "run_logs" / "latest" # Distinct runs the prior window must hold before a ratio is a verdict rather # than a coin flip. Below this the script is counted as "building" a baseline. diff --git a/heart/checks/test_run.py b/heart/checks/test_run.py index 2cafc9b6..4ef0d414 100644 --- a/heart/checks/test_run.py +++ b/heart/checks/test_run.py @@ -43,7 +43,7 @@ # reads the canonical tree, not a task bundle. HEART_HOME = Path(__file__).resolve().parents[2] PYAUTO_ROOT = _workspace.canonical_root() -TEST_RESULTS_LATEST = PYAUTO_ROOT / "PyAutoHands" / "run_logs" / "latest" +TEST_RESULTS_LATEST = _workspace.repo_path(PYAUTO_ROOT, "PyAutoHands") / "run_logs" / "latest" HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart" diff --git a/heart/checks/unit_test_timing.py b/heart/checks/unit_test_timing.py index 0a44e9bc..cd7153d0 100644 --- a/heart/checks/unit_test_timing.py +++ b/heart/checks/unit_test_timing.py @@ -155,7 +155,7 @@ def run(runner: Runner | None = None, repos: list[str] | None = None) -> dict[st new_tests = 0 for repo in repos: - durations = runner(root / repo) + durations = runner(_workspace.repo_path(root, repo)) if durations is None: unavailable.append(repo) continue diff --git a/heart/checks/url_check_live.py b/heart/checks/url_check_live.py index 5034d3e5..0616b776 100644 --- a/heart/checks/url_check_live.py +++ b/heart/checks/url_check_live.py @@ -43,9 +43,16 @@ from pathlib import Path from typing import Iterable -import requests -from requests.adapters import HTTPAdapter -from urllib3.util.retry import Retry +if __package__: + from heart import _workspace +else: # standalone script from another checkout + import importlib.util + _spec = importlib.util.spec_from_file_location( + "_heart_workspace", Path(__file__).resolve().parents[1] / "_workspace.py" + ) + _workspace = importlib.util.module_from_spec(_spec) + _spec.loader.exec_module(_workspace) + SCAN_SUFFIXES = { @@ -202,6 +209,10 @@ def _colab_to_raw(url: str) -> str | None: def _build_session() -> requests.Session: + import requests + from requests.adapters import HTTPAdapter + from urllib3.util.retry import Retry + s = requests.Session() retry = Retry( total=2, connect=2, read=2, backoff_factor=0.3, @@ -216,6 +227,8 @@ def _build_session() -> requests.Session: def check_url(session: requests.Session, url: str, timeout: float = 12.0) -> Result: + import requests + raw = _colab_to_raw(url) probe_url = raw if raw else url @@ -400,7 +413,9 @@ def main(argv: list[str] | None = None) -> int: for r in repo_args: path = Path(r) if not path.is_absolute(): - path = root / r + path = (_workspace.repo_path(root, r) + if path.parts == (r,) and r not in (".", "..") + else root / path) repos.append((path, path.resolve())) print(f"Scanning {len(repos)} repo(s) under {root}", file=sys.stderr) diff --git a/heart/checks/url_sweep.sh b/heart/checks/url_sweep.sh index d3fc8c6a..50cfb7db 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_MAIN_ROOT/$repo" + dir="$(heart_repo_path "$repo")" || return 1 if [[ ! -d "$dir" ]]; then rows+="${repo}|0|0"$'\n' continue @@ -88,4 +88,6 @@ print(json.dumps({ fi } -check_url_sweep "$@" +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + check_url_sweep "$@" +fi diff --git a/heart/checks/version_skew.py b/heart/checks/version_skew.py index 4351c061..853dd1e9 100644 --- a/heart/checks/version_skew.py +++ b/heart/checks/version_skew.py @@ -90,7 +90,7 @@ def read_workspace_floor(workspace: str, root: Path = PYAUTO_ROOT) -> str | None """The compatibility floor: ``config/general.yaml`` → ``version.minimum_library_version``. Returns None when absent (the workspace is not a floor candidate).""" - general = root / workspace / "config" / "general.yaml" + general = _workspace.repo_path(root, workspace) / "config" / "general.yaml" if not general.is_file(): return None try: @@ -113,7 +113,7 @@ def newest_release_tag(repo: str, root: Path = PYAUTO_ROOT) -> str | None: """Newest ``YYYY.M.D.B`` release tag on the library checkout (``git tag``), or None when the repo isn't a checkout or carries no release tags. No network — reads local tags only, so it stays inside the tick budget.""" - repo_dir = root / repo + repo_dir = _workspace.repo_path(root, repo) if not (repo_dir / ".git").exists(): return None try: diff --git a/heart/checks/workspace_testmode_timing.py b/heart/checks/workspace_testmode_timing.py index f06d57f7..e6893ed4 100644 --- a/heart/checks/workspace_testmode_timing.py +++ b/heart/checks/workspace_testmode_timing.py @@ -86,7 +86,7 @@ def default_runner(root: Path, python: str, timeout: float) -> Runner: } def run_script(workspace: str, rel: str) -> float | None: - workspace_dir = root / workspace + workspace_dir = _workspace.repo_path(root, workspace) script = workspace_dir / rel if not script.is_file(): return None diff --git a/heart/checks/worktree_drift.py b/heart/checks/worktree_drift.py index 79bcd2f0..3bf27abd 100644 --- a/heart/checks/worktree_drift.py +++ b/heart/checks/worktree_drift.py @@ -56,8 +56,8 @@ # $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" +ACTIVE_MD = _workspace.repo_path(PYAUTO_ROOT, "PyAutoMind") / "active.md" +PARKED_MD = _workspace.repo_path(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 904c7074..0892966c 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -190,7 +190,7 @@ def theme(): """ for cand in (os.environ.get("PYAUTO_BRAIN"), HEART_HOME / "PyAutoBrain", HEART_HOME.parent / "PyAutoBrain", - _workspace_root() / "PyAutoBrain"): + _workspace.repo_path(_workspace_root(), "PyAutoBrain")): if not cand: continue board_dir = pathlib.Path(cand) / "board" diff --git a/heart/smoke.py b/heart/smoke.py index dacefdd4..63d93998 100644 --- a/heart/smoke.py +++ b/heart/smoke.py @@ -31,6 +31,7 @@ from typing import Iterable, Mapping, Sequence import yaml +from heart import _workspace FINGERPRINT_SCHEMA = 1 MARKER_NAME = ".pyauto-smoke-environment.json" @@ -133,9 +134,9 @@ def environment_fingerprint( python_identity: Mapping[str, str], ) -> dict: """Return the complete, serialisable cache contract for one workspace.""" - workspace = organism_root / spec.directory + workspace = _workspace.repo_path(organism_root, spec.directory) watched = [workspace / ".github" / "scripts" / "smoke_install.sh"] - watched.extend(organism_root / repo / "pyproject.toml" for repo in spec.chain) + watched.extend(_workspace.repo_path(organism_root, repo) / "pyproject.toml" for repo in spec.chain) files = { str(path.relative_to(organism_root)): _sha256(path) for path in watched @@ -226,8 +227,8 @@ def runtime_environment( for name in tuple(env): if name.startswith("PYAUTO_"): env.pop(name) - source_paths = [str(organism_root / repo) for repo in spec.chain] - source_paths.append(str(organism_root / "PyAutoHands" / "autohands")) + source_paths = [str(_workspace.repo_path(organism_root, repo)) for repo in spec.chain] + source_paths.append(str(_workspace.repo_path(organism_root, "PyAutoHands") / "autohands")) cache_dir = state_root / "smoke-runtime" / spec.key (cache_dir / "numba").mkdir(parents=True, exist_ok=True) (cache_dir / "matplotlib").mkdir(parents=True, exist_ok=True) @@ -252,7 +253,7 @@ def runtime_environment( def _optional_local_targets(organism_root: Path, chain: Iterable[str]) -> list[str]: targets: list[str] = [] for repo in chain: - pyproject = organism_root / repo / "pyproject.toml" + pyproject = _workspace.repo_path(organism_root, repo) / "pyproject.toml" if not pyproject.is_file(): continue with pyproject.open("rb") as stream: @@ -310,7 +311,7 @@ def _install_environment( if spec.arcticpy: _install_arcticpy(python, env) - workspace = organism_root / spec.directory + workspace = _workspace.repo_path(organism_root, spec.directory) installer = workspace / ".github" / "scripts" / "smoke_install.sh" if installer.is_file(): _run(["bash", installer], cwd=organism_root, env=env) @@ -415,7 +416,7 @@ def _preflight( _pip_check(python, env, spec) expected = { - IMPORT_NAMES[repo]: str((organism_root / repo).resolve()) + IMPORT_NAMES[repo]: str((_workspace.repo_path(organism_root, repo)).resolve()) for repo in spec.chain if repo in IMPORT_NAMES } @@ -430,7 +431,7 @@ def _preflight( ) _run([python, "-c", probe, json.dumps(expected)], env=env, capture_output=True) - notebook_list = organism_root / spec.directory / "smoke_notebooks.txt" + notebook_list = _workspace.repo_path(organism_root, spec.directory) / "smoke_notebooks.txt" if notebook_list.is_file() and notebook_list.read_text().strip(): jupyter = _environment_bin(environment) / "jupyter" if not jupyter.is_file(): @@ -564,7 +565,7 @@ def _run_legacy_workspace( env: Mapping[str, str], ) -> int: """Run an allowlist for the one legacy workspace without a runner.""" - hands_path = organism_root / "PyAutoHands" / "autohands" + hands_path = _workspace.repo_path(organism_root, "PyAutoHands") / "autohands" sys.path.insert(0, str(hands_path)) try: from env_config import build_env_for_script, load_env_config @@ -615,7 +616,7 @@ def run_workspace( state_root: Path, spec: WorkspaceSpec, ) -> int: - workspace = organism_root / spec.directory + workspace = _workspace.repo_path(organism_root, spec.directory) _wipe_output(workspace) env = runtime_environment(environment, organism_root, spec, state_root) python = _environment_python(environment) @@ -672,7 +673,7 @@ def main(argv: Sequence[str] | None = None) -> int: failures = 0 for key in selected: spec = WORKSPACES[key] - workspace = root / spec.directory + workspace = _workspace.repo_path(root, spec.directory) if not workspace.is_dir(): print(f"[{key}] missing workspace: {workspace}", file=sys.stderr) failures += 1 diff --git a/heart/tick.sh b/heart/tick.sh index 61e1b12f..7e4844d4 100755 --- a/heart/tick.sh +++ b/heart/tick.sh @@ -21,7 +21,8 @@ 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_MAIN_ROOT/PyAutoHands/run_logs/latest" ]]; then +hands_checkout="$(heart_repo_path PyAutoHands)" || exit 1 +if [[ -d "$hands_checkout/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)')" @@ -33,7 +34,8 @@ fi # 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 +profiling_checkout="$(heart_repo_path autolens_profiling)" || exit 1 +if [ -d "$profiling_checkout/results" ]; 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)')" @@ -61,7 +63,8 @@ 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_MAIN_ROOT/PyAutoMind/scripts/repos_sync.py" ]]; then +mind_checkout="$(heart_repo_path PyAutoMind)" || exit 1 +if [[ -f "$mind_checkout/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/tests/test_repo_paths_grouped.py b/tests/test_repo_paths_grouped.py new file mode 100644 index 00000000..8cd53f0a --- /dev/null +++ b/tests/test_repo_paths_grouped.py @@ -0,0 +1,13 @@ +"""Heart's checkout resolver works with the canonical family layout.""" +from pathlib import Path + +from heart import _workspace + + +def test_grouped_checkout_is_used_for_smoke_and_checks(tmp_path): + family = tmp_path / "workspaces" + checkout = family / "demo_workspace" + checkout.mkdir(parents=True) + (checkout / ".git").mkdir() + assert _workspace.repo_path(tmp_path, "demo_workspace", required=True) == checkout + assert checkout in _workspace.iter_checkouts(tmp_path) diff --git a/tests/test_repo_resolution_shell_failure.py b/tests/test_repo_resolution_shell_failure.py new file mode 100644 index 00000000..5a43c260 --- /dev/null +++ b/tests/test_repo_resolution_shell_failure.py @@ -0,0 +1,29 @@ +"""A failing path resolver must not become an absent/clean repository.""" +from pathlib import Path +import subprocess + +ROOT = Path(__file__).resolve().parents[1] + + +def test_repo_state_propagates_background_worker_failure(): + result = subprocess.run(['bash', '-c', ''' +source "$1/heart/checks/repo_state.sh" +heart_state_dir() { :; } +heart_log() { :; } +load_repos_yaml() { printf 'Example/Demo workspace\\n'; } +heart_repo_path() { return 2; } +check_repo_state_all +''', 'test', str(ROOT)], capture_output=True, text=True) + assert result.returncode != 0 + + +def test_url_sweep_rejects_unresolved_checkout(): + result = subprocess.run(['bash', '-c', ''' +source "$1/heart/checks/url_sweep.sh" +heart_state_dir() { :; } +heart_log() { :; } +URL_CHECK_REPOS=(Demo) +heart_repo_path() { return 2; } +check_url_sweep +''', 'test', str(ROOT)], capture_output=True, text=True) + assert result.returncode != 0 diff --git a/tests/test_url_check_live_repo_paths.py b/tests/test_url_check_live_repo_paths.py new file mode 100644 index 00000000..a959968a --- /dev/null +++ b/tests/test_url_check_live_repo_paths.py @@ -0,0 +1,19 @@ +"""URL audit accepts the default cwd and relative checkout paths.""" +from heart.checks import url_check_live + + +def test_default_dot_is_scanned_without_a_repository_identity(tmp_path, monkeypatch): + seen = [] + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(url_check_live, "scan_repos", lambda paths: seen.extend(paths) or {}) + assert url_check_live.main(["--no-check"]) == 0 + assert seen == [tmp_path] + + +def test_relative_path_is_kept_relative_to_root(tmp_path, monkeypatch): + seen = [] + child = tmp_path / "local" / "scripts" + child.mkdir(parents=True) + monkeypatch.setattr(url_check_live, "scan_repos", lambda paths: seen.extend(paths) or {}) + assert url_check_live.main(["--root", str(tmp_path), "--repos", "local/scripts", "--no-check"]) == 0 + assert seen == [child]