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: 4 additions & 0 deletions heart/_common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions heart/_workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
"canonical_root",
"canonical_root_reason",
"wt_root",
"repo_path",
"iter_checkouts",
"ROOT_MARKER",
]

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion heart/checks/manifest_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": {}}
Expand Down
2 changes: 1 addition & 1 deletion heart/checks/profiling_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
16 changes: 13 additions & 3 deletions heart/checks/repo_state.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")"
}

Expand Down
2 changes: 1 addition & 1 deletion heart/checks/script_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion heart/checks/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion heart/checks/unit_test_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 19 additions & 4 deletions heart/checks/url_check_live.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand Down Expand Up @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions heart/checks/url_sweep.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -88,4 +88,6 @@ print(json.dumps({
fi
}

check_url_sweep "$@"
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
check_url_sweep "$@"
fi
4 changes: 2 additions & 2 deletions heart/checks/version_skew.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion heart/checks/workspace_testmode_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions heart/checks/worktree_drift.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down
2 changes: 1 addition & 1 deletion heart/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
23 changes: 12 additions & 11 deletions heart/smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand All @@ -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():
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions heart/tick.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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)')"
Expand All @@ -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)')"
Expand Down Expand Up @@ -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)')"
Expand Down
Loading
Loading