diff --git a/agents/_common.sh b/agents/_common.sh index 625f6832..e0325a2a 100755 --- a/agents/_common.sh +++ b/agents/_common.sh @@ -12,6 +12,7 @@ # remote session ($HOME=/root, checkouts under /home/user) and report empty # rather than fail. . "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../bin/_pyauto_root.sh" +. "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../bin/_repo_paths.sh" # _resolve_bin — echo a runnable invocation or # print an install hint to stderr and return 127. @@ -34,11 +35,15 @@ _resolve_bin() { # organism). The former name was `pyauto-pulse` (the back-compat shim has since # been removed); the canonical command is `pyauto-heart`. resolve_heart() { - _resolve_bin pyauto-heart "$PYAUTO_ROOT/PyAutoHeart/bin/pyauto-heart" + local checkout + checkout="$(pyauto_repo_path PyAutoHeart "$PYAUTO_ROOT")" || return $? + _resolve_bin pyauto-heart "$checkout/bin/pyauto-heart" } resolve_autohands() { - _resolve_bin autohands "$PYAUTO_ROOT/PyAutoHands/bin/autohands" + local checkout + checkout="$(pyauto_repo_path PyAutoHands "$PYAUTO_ROOT")" || return $? + _resolve_bin autohands "$checkout/bin/autohands" } # _resolve_dir — echo the path to a sibling PyAuto @@ -54,6 +59,8 @@ _resolve_dir() { # (organs are typically cloned side by side), so check it first. local brain_parent brain_parent="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../.." && pwd)" + c="$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")" || return 1 + if [[ -d "$c" ]]; then printf '%s' "$c"; return 0; fi # $PYAUTO_ROOT already resolves to the checkout parent on a developer box, # so the old instance-named entry here was redundant as well as wrong # anywhere else. diff --git a/agents/_repo_paths.py b/agents/_repo_paths.py new file mode 100644 index 00000000..52e7e44d --- /dev/null +++ b/agents/_repo_paths.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +"""Repository placement, independent of a workspace's physical layout. + +Mind's repos.yaml declares preferred canonical paths. Actual context wins: CI +and task bundles can still place those same repositories side by side. Discovery +stops at checkout boundaries and rejects ambiguity rather than selecting another +checkout silently. Missing optional paths are returned for callers which inspect +partial clones; callers requiring a repository use required=True. +""" +from __future__ import annotations + +import argparse +import os +from pathlib import Path, PurePosixPath +import re +import sys + + +def _name(name: str) -> str: + if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9_.-]+', name) or name in ('.', '..'): + raise ValueError(f'unsafe repository identity: {name!r}') + return name + + +def _placement(name: str, value: str) -> Path: + if not isinstance(value, str) or '\\' in value: + raise ValueError(f'{name}: invalid repository path: {value!r}') + path = PurePosixPath(value) + if path.is_absolute() or '..' in path.parts or not path.parts or path.name != name: + raise ValueError(f'{name}: unsafe repository path: {value!r}') + if len(path.parts) > 2 or any(p.startswith('.') for p in path.parts[:-1]): + raise ValueError(f'{name}: expected a repository at root or in one family directory: {value!r}') + return Path(*path.parts) + + +def manifest_paths(root: Path) -> dict[str, Path]: + """Read only identity and placement from the body's simple YAML mapping. + + This bootstrap must work before PyYAML is installed. Accept the manifest's + two/four-space mapping grammar, including quoted path scalars, and validate + every explicit placement. Other metadata is deliberately not interpreted. + """ + manifest = Path(root) / 'PyAutoMind' / 'repos.yaml' + if not manifest.is_file(): + return {} + paths: dict[str, Path] = {} + active = False + current = None + for line in manifest.read_text().splitlines(): + if line.strip() == 'repos:': + active = True + continue + if not active or not line.strip() or line.lstrip().startswith('#'): + continue + if not line.startswith(' '): + break + match = re.fullmatch(r' ([A-Za-z0-9_.-]+):\s*(?:#.*)?', line) + if match: + current = _name(match[1]) + if current in paths: + raise ValueError(f'duplicate repository identity: {current}') + paths[current] = Path(current) + continue + if current and re.match(r' path\s*:', line): + raw = line.split(':', 1)[1].strip() + if raw.startswith(('"', "'")): + quote = raw[0] + end = raw.find(quote, 1) + if end < 0 or (raw[end + 1:].strip() and not raw[end + 1:].strip().startswith('#')): + raise ValueError(f'{current}: invalid path scalar: {raw!r}') + value = raw[1:end] + else: + value = raw.split(' #', 1)[0].strip() + paths[current] = _placement(current, value) + by_path: dict[Path, str] = {} + for name, path in paths.items(): + if path in by_path: + raise ValueError(f'duplicate repository placement: {by_path[path]} and {name}') + by_path[path] = name + return paths + + +def is_checkout(path: Path) -> bool: + return path.is_dir() and (path / '.git').exists() + + +def _families(root: Path): + if root.is_dir(): + for path in sorted(root.iterdir()): + if (path.is_dir() and not path.is_symlink() + and not path.name.startswith('.') and not is_checkout(path)): + yield path + + +def iter_checkouts(root: Path) -> list[Path]: + """Actual flat or family checkouts, including symlinked bundle dependencies. + + Never recursively search inside a repository (datasets can contain clones). + Each logical identity must have exactly one physical target in this context. + """ + root = Path(root) + if not root.is_dir(): + return [] + found = [p for p in sorted(root.iterdir()) if is_checkout(p)] + for family in _families(root): + found.extend(p for p in sorted(family.iterdir()) if is_checkout(p)) + unique: dict[str, Path] = {} + for path in found: + previous = unique.get(path.name) + if previous is not None and previous.resolve() != path.resolve(): + raise ValueError(f'{path.name}: ambiguous checkouts: {previous}, {path}') + unique.setdefault(path.name, path) + return sorted(unique.values(), key=lambda p: p.name) + + +def repo_path(root: Path, name: str, required: bool = False) -> Path: + """Locate a repo within the specified context, never a different workspace. + + Existing directories remain usable for partial fixtures and bootstrap writes; + only required=True establishes checkout presence, through the .git marker. + Missing paths retain their declared placement for precise error messages. + """ + root = Path(root) + name = _name(name) + declared = manifest_paths(root).get(name, Path(name)) + if len(declared.parts) > 1 and (root / declared.parts[0]).is_symlink(): + raise ValueError(f'{name}: repository family must not be a symlink: {root / declared.parts[0]}') + candidates = [root / name, root / declared] + candidates.extend(family / name for family in _families(root)) + existing: dict[Path, Path] = {} + for path in candidates: + if path.is_dir(): + existing.setdefault(path.resolve(), path) + if len(existing) > 1: + raise ValueError(f'{name}: ambiguous checkouts: ' + ', '.join(map(str, existing.values()))) + result = next(iter(existing.values()), root / declared) + if required and not is_checkout(result): + raise FileNotFoundError(f'{name}: repository checkout missing at {result}') + return result + + +def repo_paths(root: Path) -> dict[str, Path]: + """All manifest identities, retaining missing paths so coverage cannot shrink.""" + return {name: repo_path(root, name) for name in manifest_paths(Path(root))} + + +def package_paths(root: Path) -> list[Path]: + """Import roots for packages declared by the body map, in manifest order.""" + root = Path(root) + declared = manifest_paths(root) + manifest = root / 'PyAutoMind/repos.yaml' + if not manifest.is_file(): + return [] + names = [] + current = None + active = False + for line in manifest.read_text().splitlines(): + if line.strip() == 'repos:': + active = True + continue + if not active or not line.strip() or line.lstrip().startswith('#'): + continue + if not line.startswith(' '): + break + match = re.fullmatch(r' ([A-Za-z0-9_.-]+):\s*(?:#.*)?', line) + if match: + current = match[1] + elif current in declared and re.match(r' package:\s*\S+', line): + names.append(current) + return [repo_path(root, name) for name in names] + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + one = commands.add_parser('path') + one.add_argument('name') + one.add_argument('--required', action='store_true') + for cmd in (one, commands.add_parser('list'), commands.add_parser('pythonpath')): + cmd.add_argument('--root', type=Path, default=Path(os.environ.get('PYAUTO_ROOT', '.'))) + args = parser.parse_args(argv) + try: + if args.command == 'path': + print(repo_path(args.root, args.name, args.required)) + elif args.command == 'pythonpath': + print(os.pathsep.join(str(p) for p in package_paths(args.root) if p.is_dir())) + else: + for path in iter_checkouts(args.root): + print(f'{path.name}\t{path}') + except (ValueError, OSError) as error: + print(f'repository lookup: {error}', file=sys.stderr) + return 2 + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/agents/conductors/batch/_integration.py b/agents/conductors/batch/_integration.py index 195c0ea4..3bf3377d 100644 --- a/agents/conductors/batch/_integration.py +++ b/agents/conductors/batch/_integration.py @@ -42,6 +42,10 @@ import subprocess from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import repo_path # noqa: E402 + BRAIN = Path(__file__).resolve().parents[3] WORKTREE_SH = BRAIN / "bin" / "worktree.sh" @@ -217,7 +221,7 @@ def ensure_root(slot: str, repo_dirs: list, notes: list): return None return root for name in repo_dirs: - if (root / name / ".git").exists(): + if (repo_path(root, name) / ".git").exists(): continue proc = _worktree_sh("worktree_add_repo", slot, name) if proc.returncode != 0: diff --git a/agents/conductors/clone/_clone.py b/agents/conductors/clone/_clone.py index 3597b2c9..10d4b213 100644 --- a/agents/conductors/clone/_clone.py +++ b/agents/conductors/clone/_clone.py @@ -53,6 +53,7 @@ # failing. sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import _pyauto_root # noqa: E402 +from _repo_paths import repo_path, iter_checkouts # noqa: E402 PYAUTO_ROOT = _pyauto_root.pyauto_root() @@ -203,7 +204,7 @@ def fail(code, msg): def repo_root(name): - path = PYAUTO_ROOT / name + path = repo_path(PYAUTO_ROOT, name) if not (path / ".git").exists(): fail(4, f"repo '{name}' not checked out at {path}") return path @@ -343,7 +344,7 @@ def build_decision(args): ws = workspace_shape(workspace_root_) if not ws["start_here"] and "start_here" not in " ".join(ws["script_dirs"]): risks.append("workspace has no scripts/start_here.py — weak front-door signal") - if (PYAUTO_ROOT / target).exists(): + if (repo_path(PYAUTO_ROOT, target)).exists(): risks.append(f"target '{target}' already exists locally — name collision") return { @@ -415,7 +416,7 @@ def reference_library(reference_name): derived from its name (e.g. autolens_assistant -> autolens, PyAutoLens).""" package = reference_name.replace("_assistant", "") want = f"pyauto{package[4:]}" if package.startswith("auto") else None - for child in sorted(PYAUTO_ROOT.iterdir()): + for child in sorted(set(iter_checkouts(PYAUTO_ROOT)) | set(PYAUTO_ROOT.iterdir())): if child.is_dir() and child.name.lower() == want: return package, child.name fail(4, f"cannot resolve the reference's library repo for '{reference_name}'") @@ -556,7 +557,7 @@ def apply_seed(args, decision): plan_path = Path(tempfile.mkstemp(prefix="clone_plan_", suffix=".json")[1]) plan_path.write_text(json.dumps(plan, indent=2)) - seed_script = PYAUTO_ROOT / "PyAutoHands" / "autohands" / "clone_seed.py" + seed_script = repo_path(PYAUTO_ROOT, "PyAutoHands") / "autohands" / "clone_seed.py" if not seed_script.exists(): fail(4, f"Build primitive not found: {seed_script}") cmd = [sys.executable, str(seed_script), str(plan_path)] @@ -634,7 +635,7 @@ def discover_targets(reference_name): """Sibling assistants checked out beside the reference.""" return sorted( child.name - for child in PYAUTO_ROOT.iterdir() + for child in (set(iter_checkouts(PYAUTO_ROOT)) | set(PYAUTO_ROOT.iterdir())) if child.is_dir() and child.name.endswith("_assistant") and child.name != reference_name diff --git a/agents/conductors/hygiene/_hygiene_docstrings.py b/agents/conductors/hygiene/_hygiene_docstrings.py index 18c251e5..8b5fb789 100644 --- a/agents/conductors/hygiene/_hygiene_docstrings.py +++ b/agents/conductors/hygiene/_hygiene_docstrings.py @@ -11,6 +11,10 @@ from dataclasses import asdict, dataclass from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import iter_checkouts # noqa: E402 + TRIPLE_QUOTE = re.compile(r"(?i)^[ruf]*(?:\"\"\"|''')") @@ -36,7 +40,8 @@ class ParseError: def repository_paths(root: Path) -> list[Path]: """Return user-facing ``*_workspace`` and ``HowTo*`` repositories.""" - candidates = [*root.glob("*_workspace"), *root.glob("HowTo*")] + candidates = [*iter_checkouts(root), *root.glob("*_workspace"), *root.glob("HowTo*")] + candidates = [p for p in candidates if p.name.endswith("_workspace") or p.name.startswith("HowTo")] return sorted( {path.resolve() for path in candidates if (path / "scripts").is_dir()}, key=lambda path: path.name.lower(), diff --git a/agents/conductors/hygiene/_hygiene_escapes.py b/agents/conductors/hygiene/_hygiene_escapes.py index 3dffe01a..0e481966 100755 --- a/agents/conductors/hygiene/_hygiene_escapes.py +++ b/agents/conductors/hygiene/_hygiene_escapes.py @@ -37,6 +37,10 @@ from dataclasses import asdict, dataclass from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import iter_checkouts # noqa: E402 + SKIP_PARTS = {".git", "__pycache__", "build", "dist", ".ipynb_checkpoints"} # A newline in a string value is ordinary text, not evidence of a mangled macro. CONTROL_EXCEPT_NEWLINE = "\n" @@ -59,7 +63,8 @@ class ParseError: def repository_paths(root: Path) -> list[Path]: """Return user-facing ``*_workspace`` and ``HowTo*`` repositories.""" - candidates = [*root.glob("*_workspace"), *root.glob("HowTo*")] + candidates = [*iter_checkouts(root), *root.glob("*_workspace"), *root.glob("HowTo*")] + candidates = [p for p in candidates if p.name.endswith("_workspace") or p.name.startswith("HowTo")] return sorted( {path.resolve() for path in candidates if (path / "scripts").is_dir()}, key=lambda path: path.name.lower(), diff --git a/agents/conductors/hygiene/_hygiene_extras.py b/agents/conductors/hygiene/_hygiene_extras.py index d9f6f5ef..ae9819ce 100644 --- a/agents/conductors/hygiene/_hygiene_extras.py +++ b/agents/conductors/hygiene/_hygiene_extras.py @@ -52,6 +52,10 @@ import tomllib from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import iter_checkouts # noqa: E402 + # The extra mode=release installs for every library, and therefore the coverage # mode=smoke is expected to match. RELEASE_EXTRA = "optional" @@ -97,7 +101,7 @@ def libraries(root: Path) -> dict[str, tuple[str, dict]]: return {} found: dict[str, tuple[str, dict]] = {} - for checkout in sorted(p for p in root.iterdir() if p.is_dir()): + for checkout in sorted(p for p in (set(iter_checkouts(root)) | set(root.iterdir())) if p.is_dir()): pyproject = checkout / "pyproject.toml" try: data = tomllib.loads(pyproject.read_text()) diff --git a/agents/conductors/hygiene/_hygiene_optdeps.py b/agents/conductors/hygiene/_hygiene_optdeps.py index ca4663e0..eb40120a 100644 --- a/agents/conductors/hygiene/_hygiene_optdeps.py +++ b/agents/conductors/hygiene/_hygiene_optdeps.py @@ -38,6 +38,10 @@ import warnings from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import repo_path # noqa: E402 + # Workspace prose blocks contain LaTeX (\sigma, \epsilon, ...), so parsing them # emits a SyntaxWarning per occurrence. That is the scanned repo's business, not # a signal from this scan, and it would bury the report. @@ -87,7 +91,7 @@ def unguarded(root: Path) -> list[dict]: findings: list[dict] = [] for name in WORKSPACES: - workspace = root / name + workspace = repo_path(root, name) if not (workspace / ".git").exists(): continue diff --git a/agents/conductors/hygiene/_hygiene_refs.py b/agents/conductors/hygiene/_hygiene_refs.py index 945e977a..714a9f28 100644 --- a/agents/conductors/hygiene/_hygiene_refs.py +++ b/agents/conductors/hygiene/_hygiene_refs.py @@ -129,6 +129,10 @@ from dataclasses import asdict, dataclass from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import repo_path, iter_checkouts # noqa: E402 + # Backtick-quoted spans, and bare scripts//notebooks/ path mentions. BACKTICK_REFERENCE = re.compile(r"`([^`\n]{1,200}?)`") BARE_PATH_REFERENCE = re.compile( @@ -285,7 +289,8 @@ def line_of(offsets: list[int], position: int) -> int: def repository_paths(root: Path) -> list[Path]: """Return user-facing ``*_workspace`` and ``HowTo*`` repositories.""" - candidates = [*root.glob("*_workspace"), *root.glob("HowTo*")] + candidates = [*iter_checkouts(root), *root.glob("*_workspace"), *root.glob("HowTo*")] + candidates = [p for p in candidates if p.name.endswith("_workspace") or p.name.startswith("HowTo")] return sorted( {path.resolve() for path in candidates if (path / "scripts").is_dir()}, key=lambda path: path.name.lower(), @@ -355,12 +360,14 @@ class Resolver: def __init__(self, root: Path): self.root = root self.indexes: dict[str, RepositoryIndex] = {} - self.siblings = {path.name for path in root.iterdir() if path.is_dir()} + if not root.is_dir(): + raise FileNotFoundError(root) + self.siblings = {path.name for path in (iter_checkouts(root) or root.iterdir()) if path.is_dir()} self.suppressed = 0 def index(self, name: str) -> RepositoryIndex | None: if name not in self.indexes: - path = self.root / name + path = repo_path(self.root, name) if not path.is_dir(): return None self.indexes[name] = RepositoryIndex(path) diff --git a/agents/conductors/hygiene/hygiene.sh b/agents/conductors/hygiene/hygiene.sh index d7b62a7c..e7cec623 100755 --- a/agents/conductors/hygiene/hygiene.sh +++ b/agents/conductors/hygiene/hygiene.sh @@ -102,9 +102,15 @@ SCAN_REPOS=("${CODE_REPOS[@]}" "${WS_REPOS[@]}") # silently drop it: the very bug this change repairs, re-created one line down. # `docs` was pinned to three named repos and so never noticed a fourth acquiring # Sphinx docs. Presence is the honest test in both cases. -repo_is_checked_out() { [[ -d "$ROOT/$1/.git" || -f "$ROOT/$1/.git" ]]; } -repo_ships_distribution() { [[ -f "$ROOT/$1/pyproject.toml" ]]; } -repo_ships_api_docs() { [[ -d "$ROOT/$1/docs/api" ]]; } +declare -A CHECKOUT_DIRS=() +CHECKOUT_LIST="$(pyauto_repo_list "$ROOT")" || exit $? +while IFS=$'\t' read -r _checkout_name _checkout_path; do + [[ -n "$_checkout_name" ]] && CHECKOUT_DIRS["$_checkout_name"]="$_checkout_path" +done <<< "$CHECKOUT_LIST" +repo_dir() { printf '%s' "${CHECKOUT_DIRS[$1]:-$ROOT/$1}"; } +repo_is_checked_out() { local dir; dir="$(repo_dir "$1")" || return 1; [[ -e "$dir/.git" ]]; } +repo_ships_distribution() { [[ -f "$(repo_dir "$1")/pyproject.toml" ]]; } +repo_ships_api_docs() { [[ -d "$(repo_dir "$1")/docs/api" ]]; } # MANAGED_PRESENT — how many declared repos are actually checked out under # $ROOT. Zero means the repo-array modes saw NOTHING, and their counts would be @@ -185,7 +191,7 @@ declare -A MODE_KIND=( prescan_tidy() { local branches=0 stashes=0 gone=0 dirty=0 scanned=0 repo dir for repo in "${CODE_REPOS[@]}"; do - dir="$ROOT/$repo" + dir="$(repo_dir "$repo")" repo_is_checked_out "$repo" || continue scanned=$((scanned + 1)) local b s g cur @@ -216,7 +222,7 @@ prescan_deps() { repo_is_checked_out "$repo" || continue scanned=$((scanned + 1)) repo_ships_distribution "$repo" || continue - pj="$ROOT/$repo/pyproject.toml" + pj="$(repo_dir "$repo")/pyproject.toml" files=$((files + 1)) local c c=$(grep -oE '[<>=!~]=?[[:space:]]*[0-9]' "$pj" 2>/dev/null | grep -cE '<|==' || true) @@ -234,7 +240,7 @@ prescan_docs() { scanned=$((scanned + 1)) repo_ships_api_docs "$repo" || continue doc_repos=$((doc_repos + 1)) - d="$ROOT/$repo/docs/api" + d="$(repo_dir "$repo")/docs/api" local n c n=$(find "$d" -maxdepth 1 -name '*.rst' 2>/dev/null | wc -l | tr -d ' ') c=$(grep -rhE '^\s*\.\.\s+currentmodule::' "$d" 2>/dev/null | wc -l | tr -d ' ') @@ -252,7 +258,7 @@ prescan_docs() { prescan_crlf() { local scripts=0 cosmetic=0 scanned=0 sdetail="" repo dir sh_n exe_list exe_n py_n for repo in "${SCAN_REPOS[@]}"; do - dir="$ROOT/$repo" + dir="$(repo_dir "$repo")" repo_is_checked_out "$repo" || continue scanned=$((scanned + 1)) # .sh with CRLF (all shell scripts break) @@ -328,7 +334,7 @@ prescan_refs() { prescan_artifacts() { local total=0 scanned=0 detail="" repo dir n for repo in "${SCAN_REPOS[@]}"; do - dir="$ROOT/$repo" + dir="$(repo_dir "$repo")" repo_is_checked_out "$repo" || continue scanned=$((scanned + 1)) local leaked @@ -351,7 +357,7 @@ prescan_artifacts() { prescan_packaging() { local total=0 scanned=0 detail="" dir repo candidate rel repo_count for repo in "${CODE_REPOS[@]}"; do - dir="$ROOT/$repo" + dir="$(repo_dir "$repo")" repo_is_checked_out "$repo" || continue scanned=$((scanned + 1)) repo_count=0 @@ -538,7 +544,7 @@ fi enumerate_condemn_candidates() { local repo dir def br cur for repo in "${CODE_REPOS[@]}"; do - dir="$ROOT/$repo" + dir="$(repo_dir "$repo")" repo_is_checked_out "$repo" || continue def=$(git -C "$dir" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@') [[ -n "$def" ]] || def=main @@ -600,7 +606,7 @@ run_tidy() { else slug="${repo,,}-${loc//[^A-Za-z0-9]/-}" echo " - ${repo}:${loc} — ${typ}, unmerged → archive then condemn:" - echo " (cd $ROOT/$repo && $GUT_CMD archive ${loc} ${slug})" + echo " (cd $(repo_dir "$repo") && $GUT_CMD archive ${loc} ${slug})" echo " condemned.md: type=${typ} locator=${loc} merged=${merged} sweep-after=${sweep_after} archive-ref=refs/heads/archive/condemned/${slug}" fi done <<< "$rows" diff --git a/agents/conductors/profiling/_profiling.py b/agents/conductors/profiling/_profiling.py index 1ee66233..82c07766 100644 --- a/agents/conductors/profiling/_profiling.py +++ b/agents/conductors/profiling/_profiling.py @@ -48,6 +48,7 @@ # failing. sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import _pyauto_root # noqa: E402 +from _repo_paths import repo_path # noqa: E402 PYAUTO_ROOT = _pyauto_root.pyauto_root() HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR", Path.home() / ".pyauto-heart")) @@ -100,7 +101,7 @@ def workspace_root(explicit: str | None = None) -> Path: if explicit: return Path(explicit) - return PYAUTO_ROOT / "autolens_profiling" + return repo_path(PYAUTO_ROOT, "autolens_profiling") def _module_literal(py_path: Path, name: str): diff --git a/agents/conductors/workspace/_workspace.py b/agents/conductors/workspace/_workspace.py index 79128cfa..a059b7c5 100644 --- a/agents/conductors/workspace/_workspace.py +++ b/agents/conductors/workspace/_workspace.py @@ -36,6 +36,7 @@ # failing. sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import _pyauto_root # noqa: E402 +from _repo_paths import repo_path # noqa: E402 PYAUTO_ROOT = _pyauto_root.pyauto_root() @@ -103,7 +104,7 @@ def fail(code, msg): def read_intent(arg): """The intent text: a PyAutoMind prompt path if it resolves, else raw text.""" - for base in (Path(arg), PYAUTO_ROOT / "PyAutoMind" / arg): + for base in (Path(arg), repo_path(PYAUTO_ROOT, "PyAutoMind") / arg): if base.is_file(): return base.read_text(encoding="utf-8"), str(base) return arg, None @@ -136,7 +137,7 @@ def detect_family(text): def scripts_root(repo): - return PYAUTO_ROOT / repo / "scripts" + return repo_path(PYAUTO_ROOT, repo) / "scripts" def example_packages(repo): diff --git a/agents/faculties/review/_review.py b/agents/faculties/review/_review.py index 64a13ee8..dab0e7da 100755 --- a/agents/faculties/review/_review.py +++ b/agents/faculties/review/_review.py @@ -23,6 +23,10 @@ import sys from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import iter_checkouts, repo_path # noqa: E402 + # The one workspace-root resolver, shared with bin/_pyauto_root.sh, so a # remote session (checkouts under /home/user, $HOME=/root) resolves the same # tree a developer box does. @@ -149,7 +153,7 @@ def in_place_repos(task: str) -> list[Path]: if in_block: m = re.match(r"^ - ([A-Za-z0-9_-]+):", line) if m: - repos.append(pyauto_root / m.group(1)) + repos.append(repo_path(pyauto_root, m.group(1))) else: in_block = False return [r for r in repos if (r / ".git").exists()] @@ -164,7 +168,7 @@ def resolve_repos(task: str | None, repos: list[str]) -> list[Path]: # Claimed repos are real directories (not symlinks) holding a .git # file/dir — worktree_create symlinks everything unclaimed. return sorted( - p for p in root.iterdir() + p for p in iter_checkouts(root) if p.is_dir() and not p.is_symlink() and (p / ".git").exists() ) return [Path(r).resolve() for r in repos] diff --git a/agents/faculties/sizing/_sizing.py b/agents/faculties/sizing/_sizing.py index da790996..7f0c722b 100755 --- a/agents/faculties/sizing/_sizing.py +++ b/agents/faculties/sizing/_sizing.py @@ -41,6 +41,10 @@ import re from pathlib import Path +import sys +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from _repo_paths import repo_path # noqa: E402 + # --- the PyAutoMind taxonomy (mirrors PyAutoMind/ROUTING.md) ----------------- # work-type folder -> the kind of work it holds. WORK_TYPES = { @@ -88,7 +92,7 @@ def norm_work_type(value: str) -> str: BRAIN_HOME = Path(__file__).resolve().parents[3] POLICY_PATH = BRAIN_HOME / "config" / "policy.yaml" -BODY_MAP_PATH = BRAIN_HOME.parent / "PyAutoMind" / "repos.yaml" +BODY_MAP_PATH = repo_path(BRAIN_HOME.parent, "PyAutoMind") / "repos.yaml" _POLICY_CACHE: dict = {} diff --git a/bin/_repo_paths.sh b/bin/_repo_paths.sh new file mode 100644 index 00000000..cfedc82d --- /dev/null +++ b/bin/_repo_paths.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Python owns repository identity and placement; shell consumers use this door. +_pyauto_repo_module="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../agents/_repo_paths.py" +pyauto_repo_path() { + python3 "$_pyauto_repo_module" path "$1" --root "${2:-${PYAUTO_ROOT:-.}}" +} +pyauto_repo_list() { + python3 "$_pyauto_repo_module" list --root "${1:-${PYAUTO_ROOT:-.}}" +} diff --git a/bin/check_skill_line_counts.sh b/bin/check_skill_line_counts.sh index ed844955..ec6041b7 100755 --- a/bin/check_skill_line_counts.sh +++ b/bin/check_skill_line_counts.sh @@ -17,14 +17,18 @@ set -euo pipefail LIMIT="${1:-200}" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" PYAUTO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +. "$SCRIPT_DIR/_repo_paths.sh" +for _repo in PyAutoMind PyAutoBrain PyAutoHeart PyAutoHands autolens_profiling; do + pyauto_repo_path "$_repo" "$PYAUTO_ROOT" >/dev/null || exit $? +done ROOTS=( "$PYAUTO_ROOT/admin_jammy/skills" # vestigial (hosts no skills) - "$PYAUTO_ROOT/PyAutoMind/skills" - "$PYAUTO_ROOT/PyAutoBrain/skills" - "$PYAUTO_ROOT/PyAutoHeart/skills" - "$PYAUTO_ROOT/PyAutoHands/skills" - "$PYAUTO_ROOT/autolens_profiling/skills" + "$(pyauto_repo_path PyAutoMind "$PYAUTO_ROOT")/skills" + "$(pyauto_repo_path PyAutoBrain "$PYAUTO_ROOT")/skills" + "$(pyauto_repo_path PyAutoHeart "$PYAUTO_ROOT")/skills" + "$(pyauto_repo_path PyAutoHands "$PYAUTO_ROOT")/skills" + "$(pyauto_repo_path autolens_profiling "$PYAUTO_ROOT")/skills" ) over=0 diff --git a/bin/install.sh b/bin/install.sh index 34b7efcd..eeaaee5c 100755 --- a/bin/install.sh +++ b/bin/install.sh @@ -52,12 +52,16 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" DEFAULT_PYAUTO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" PYAUTO_ROOT="${PYAUTO_ROOT:-$DEFAULT_PYAUTO_ROOT}" +. "$SCRIPT_DIR/_repo_paths.sh" +for _repo in PyAutoMind PyAutoBrain PyAutoMemory PyAutoHeart PyAutoHands autolens_profiling PyAutoFit; do + pyauto_repo_path "$_repo" "$PYAUTO_ROOT" >/dev/null || exit $? +done ADMIN_SKILLS_DIR="$PYAUTO_ROOT/admin_jammy/skills" -MIND_SKILLS_DIR="$PYAUTO_ROOT/PyAutoMind/skills" -BRAIN_SKILLS_DIR="$PYAUTO_ROOT/PyAutoBrain/skills" -HEART_SKILLS_DIR="$PYAUTO_ROOT/PyAutoHeart/skills" -BUILD_SKILLS_DIR="$PYAUTO_ROOT/PyAutoHands/skills" -PROFILING_SKILLS_DIR="$PYAUTO_ROOT/autolens_profiling/skills" +MIND_SKILLS_DIR="$(pyauto_repo_path PyAutoMind "$PYAUTO_ROOT")/skills" +BRAIN_SKILLS_DIR="$(pyauto_repo_path PyAutoBrain "$PYAUTO_ROOT")/skills" +HEART_SKILLS_DIR="$(pyauto_repo_path PyAutoHeart "$PYAUTO_ROOT")/skills" +BUILD_SKILLS_DIR="$(pyauto_repo_path PyAutoHands "$PYAUTO_ROOT")/skills" +PROFILING_SKILLS_DIR="$(pyauto_repo_path autolens_profiling "$PYAUTO_ROOT")/skills" CLAUDE_HOME="${CLAUDE_HOME:-$HOME/.claude}" CODEX_HOME="${CODEX_HOME:-$HOME/.codex}" @@ -144,7 +148,7 @@ write_agents_surface() { local blockfile repo agents blockfile="$(mktemp)"; agents_surface_block > "$blockfile" for repo in "${ORGAN_REPOS[@]}"; do - agents="$PYAUTO_ROOT/$repo/AGENTS.md" + agents="$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")/AGENTS.md" if [ ! -f "$agents" ]; then echo "skipped (absent): $agents"; continue fi @@ -160,7 +164,7 @@ check_agents_surface() { local blockfile repo agents cur drift=0 blockfile="$(mktemp)"; agents_surface_block > "$blockfile" for repo in "${ORGAN_REPOS[@]}"; do - agents="$PYAUTO_ROOT/$repo/AGENTS.md" + agents="$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")/AGENTS.md" if [ ! -f "$agents" ]; then echo "skipped (absent): $agents"; continue fi @@ -325,7 +329,7 @@ _discovery_actual() { write_project_discovery() { local repo repo_dir link target d for repo in "${DISCOVERY_REPOS[@]}"; do - repo_dir="$PYAUTO_ROOT/$repo" + repo_dir="$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")" if [ ! -d "$repo_dir/skills" ]; then echo "skipped (no skills/): $repo_dir"; continue; fi # Drop our managed symlinks (only symlinks — never real files) so a removed # or renamed skill does not leave a stale committed link. @@ -348,7 +352,7 @@ check_project_discovery() { local repos=("${DISCOVERY_REPOS[@]}") [ "$#" -gt 0 ] && repos=("$@") for repo in "${repos[@]}"; do - repo_dir="$PYAUTO_ROOT/$repo" + repo_dir="$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")" [ -d "$repo_dir/skills" ] || continue want="$(_discovery_manifest "$repo_dir")" got="$(_discovery_actual "$repo_dir")" @@ -380,7 +384,7 @@ esac # web-github, ci-only). When a root repo is not checked out, it is simply # skipped — the skills from the roots that ARE present still install. -if [ -d "$PYAUTO_ROOT/PyAutoFit" ] || [ -d "$HOME/Code/PyAutoLabs/PyAutoFit" ]; then +if [ -d "$(pyauto_repo_path PyAutoFit "$PYAUTO_ROOT")" ] || [ -d "$HOME/Code/PyAutoLabs/PyAutoFit" ]; then echo "Environment: local-dev (PyAuto repos detected)" else echo "Environment: web-github / ci-only (clone roots on demand)" diff --git a/bin/morning.sh b/bin/morning.sh index 7fd3ead7..dbb28d8c 100755 --- a/bin/morning.sh +++ b/bin/morning.sh @@ -28,6 +28,7 @@ set -u HERE="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" +. "$HERE/_repo_paths.sh" echo "== morning: sync every repo to main (ff-only; real work is skipped) ==" bash "$HERE/pull_all_main.sh" @@ -50,7 +51,8 @@ if [ "${1:-}" != "--no-publish" ]; then # saw (the observation expires after 48h). Publishing it here, beside the # Brain's, is what keeps those eight rows lit — they went grey because this # leg did not exist and the last hand-run was a week old. - heart="$HERE/../../PyAutoHeart/bin/pyauto-heart" + heart_checkout="$(pyauto_repo_path PyAutoHeart "$HERE/../..")" || exit $? + heart="$heart_checkout/bin/pyauto-heart" if [ -x "$heart" ]; then echo echo "== morning: publish the Heart's dev-box observation ==" diff --git a/bin/regroup_workspace.py b/bin/regroup_workspace.py new file mode 100644 index 00000000..0ea9c63f --- /dev/null +++ b/bin/regroup_workspace.py @@ -0,0 +1,294 @@ +#!/usr/bin/env python3 +"""Plan/apply/rollback local checkout placement declared by the body map. + +No git content is edited. Renames preserve ignored data and untracked files. +The durable journal records original symlinks and local configuration; every +mutation can be reversed with rollback. Run plan first and inspect its summary. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +from pathlib import Path +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'agents')) +from _repo_paths import manifest_paths, repo_path + + +def git(path, *args): + return subprocess.check_output(['git', '-C', str(path), *args], text=True).strip() + + +def remap(path, moves): + path = Path(os.path.abspath(path)) + for old, new in moves: + try: + return Path(new) / path.relative_to(old) + except ValueError: + pass + return path + + +def snapshot(path): + stat = path.stat() + return {'head': git(path, 'rev-parse', 'HEAD'), + 'status': git(path, 'status', '--porcelain', '--untracked-files=all'), + 'device': stat.st_dev, 'inode': stat.st_ino} + + +def symlinks(roots): + seen = set() + for root in roots: + for current, dirs, files in os.walk(root, followlinks=False): + dirs[:] = [d for d in dirs if d not in ('.git', '.git-salvage')] + for name in dirs + files: + path = Path(current) / name + if path.is_symlink() and str(path) not in seen: + seen.add(str(path)) + yield path + + +def save(state, data): + state.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp(prefix=state.name + '.', dir=state.parent) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, 'w') as stream: + stream.write(json.dumps(data, indent=2) + '\n') + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(state) + finally: + if temporary.exists(): + temporary.unlink() + + + +def validate_destination(root, new): + root, new = Path(root).absolute(), Path(new).absolute() + if new.parent.parent != root: + raise ValueError(f'destination must be inside one workspace family: {new}') + family = new.parent + if family.is_symlink() or (family.exists() and not family.is_dir()) or (family / '.git').exists(): + raise ValueError(f'destination family must be a real directory, not a symlink or checkout: {family}') + + +def plan(root, state, bundles_root=None, manifest_root=None): + root = root.absolute() + if not (root / '.pyauto-root').is_file(): + raise ValueError('the canonical workspace must carry .pyauto-root') + if state.exists(): + raise ValueError(f'refusing to overwrite migration journal: {state}') + moves, records = [], [] + for name, relative in manifest_paths(manifest_root or root).items(): + old = repo_path(root, name, required=True).absolute() + new = root / relative + if old == new: + continue + if old.is_symlink() or old.parent != root: + raise ValueError(f'{name}: source must be a canonical flat checkout: {old}') + validate_destination(root, new) + if new.exists() or new.is_symlink(): + raise ValueError(f'{name}: destination already exists: {new}') + if not (old / '.git').is_dir(): + raise ValueError(f'{name}: refusing to move a linked worktree as canonical') + worktrees = [line[9:] for line in git(old, 'worktree', 'list', '--porcelain').splitlines() + if line.startswith('worktree ')] + records.append({'name': name, 'old': str(old), 'new': str(new), + 'before': snapshot(old), 'worktrees': worktrees}) + moves.append((str(old), str(new))) + roots = [root] + if bundles_root is not None and bundles_root.exists(): + roots.append(bundles_root.absolute()) + # Git may register task roots elsewhere: include only their immediate + # dependency links; never recursively walk arbitrary parents like /tmp. + links = list(symlinks(roots)) + known = {str(p) for p in links} + for row in records: + for wt in row['worktrees']: + parent = Path(wt).parent + if parent not in roots and parent.is_dir(): + for p in parent.iterdir(): + if p.is_symlink() and str(p) not in known: + links.append(p) + known.add(str(p)) + link_changes = [] + for path in links: + raw = os.readlink(path) + target = Path(raw) if os.path.isabs(raw) else path.parent / raw + relocated = remap(path, moves) + new_target = remap(target, moves) + if relocated == path and new_target == Path(os.path.abspath(target)): + continue + new_raw = str(new_target) if os.path.isabs(raw) else os.path.relpath(new_target, relocated.parent) + if new_raw != raw: + link_changes.append({'old_path': str(path), 'new_path': str(relocated), + 'old': raw, 'new': new_raw}) + configs = [] + # These are local, workspace-owned paths, not versioned source or shell RCs. + config_paths = list((root / '.idea').glob('*.xml')) + list((root / '.idea').glob('*.iml')) + config_paths += [root / '.claude/settings.json'] + for path in config_paths: + if not path.is_file() or path.is_symlink(): + continue + before = path.read_text() + after = before + for old, new in sorted(moves, key=lambda pair: len(pair[0]), reverse=True): + # Absolute paths and IDE-relative paths both have repo boundaries. + name = Path(old).name + relative = str(Path(new).relative_to(root)) + after = re.sub(re.escape(old) + r'(?=[/"\s:<]|$)', lambda _: new, after) + for prefix in ('$PROJECT_DIR$/', '$MODULE_DIR$/', './'): + after = re.sub(re.escape(prefix + name) + r'(?=[/"\s<]|$)', lambda _, p=prefix, r=relative: p+r, after) + if before != after: + configs.append({'path': str(path), 'old': before, 'new': after}) + activation = root / 'activate.sh' + activate_text = '''# Source this file after opening a shell in the grouped workspace. +_pyauto_activation_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +export PYAUTO_ROOT="$_pyauto_activation_root" +_pyauto_import_paths="$(python3 "$PYAUTO_ROOT/PyAutoBrain/agents/_repo_paths.py" pythonpath --root "$PYAUTO_ROOT")" || return +export PYTHONPATH="$_pyauto_import_paths:$PYAUTO_ROOT/PyAutoHeart${PYTHONPATH:+:$PYTHONPATH}" +export NUMBA_CACHE_DIR="${NUMBA_CACHE_DIR:-/tmp/numba_cache}" +export MPLCONFIGDIR="${MPLCONFIGDIR:-/tmp/matplotlib}" +mkdir -p "$NUMBA_CACHE_DIR" "$MPLCONFIGDIR" +unset _pyauto_activation_root _pyauto_import_paths _pyauto_import_repo _pyauto_import_dir +''' + configs.append({'path': str(activation), 'old': activation.read_text() if activation.exists() else None, + 'new': activate_text}) + data = {'root': str(root), 'stage': 'planned', 'repos': records, + 'links': link_changes, 'configs': configs, 'completed': []} + save(state, data) + return data + + +def verify(data): + for row in data['repos']: + new = Path(row['new']) + if snapshot(new) != row['before']: + raise ValueError(f'{row["name"]}: checkout content or identity changed during migration') + for old_wt in row['worktrees']: + wt = new if old_wt == row['old'] else Path(old_wt) + git(wt, 'rev-parse', '--git-common-dir') + git(wt, 'status', '--porcelain', '--untracked-files=no') + for row in data['links']: + if os.readlink(row['new_path']) != row['new']: + raise ValueError(f'link was not repaired: {row["new_path"]}') + + +def replace_link(path, target): + path = Path(path) + temporary = path.with_name(path.name + '.regroup-link') + if temporary.exists() or temporary.is_symlink(): + raise ValueError(f'link staging path already exists: {temporary}') + temporary.symlink_to(target) + temporary.replace(path) + + +def read_optional(path): + path = Path(path) + return path.read_text() if path.exists() else None + + +def rollback(state, data): + for row in reversed(data['configs']): + path = Path(row['path']) + if read_optional(path) == row['new']: + if row['old'] is None: + path.unlink() + else: + path.write_text(row['old']) + elif read_optional(path) != row['old']: + raise ValueError(f'local configuration changed since migration: {path}') + for row in reversed(data['links']): + path = Path(row['new_path']) + if not path.is_symlink(): + path = Path(row['old_path']) + if path.is_symlink() and os.readlink(path) == row['new']: + replace_link(path, row['old']) + for row in reversed(data['repos']): + old, new = Path(row['old']), Path(row['new']) + if new.exists() and not old.exists(): + new.rename(old) + git(old, 'worktree', 'repair') + for parent in {Path(row['new']).parent for row in data['repos']}: + if parent.exists() and not any(parent.iterdir()): + parent.rmdir() + data['stage'] = 'rolled-back' + save(state, data) + + +def apply(state, data): + if data['stage'] != 'planned': + raise ValueError(f'journal is {data["stage"]}; expected planned') + # Validate every source before changing any of them. + for row in data['repos']: + validate_destination(data['root'], row['new']) + if Path(row['new']).exists() or Path(row['new']).is_symlink(): + raise ValueError(f'destination appeared since planning: {row["new"]}') + if snapshot(Path(row['old'])) != row['before']: + raise ValueError(f'{row["name"]}: source changed since planning; make a fresh plan') + for row in data['links']: + if os.readlink(row['old_path']) != row['old']: + raise ValueError(f'link changed since planning: {row["old_path"]}') + for row in data['configs']: + if read_optional(row['path']) != row['old']: + raise ValueError(f'configuration changed since planning: {row["path"]}') + data['stage'] = 'applying' + save(state, data) + try: + for row in data['repos']: + old, new = Path(row['old']), Path(row['new']) + validate_destination(data['root'], new) + new.parent.mkdir(exist_ok=True) + old.rename(new) + data['completed'].append(row['name']) + save(state, data) + git(new, 'worktree', 'repair') + for row in data['links']: + path = Path(row['new_path']) + replace_link(path, row['new']) + for row in data['configs']: + if read_optional(row['path']) != row['old']: + raise ValueError(f'configuration changed during migration: {row["path"]}') + Path(row['path']).write_text(row['new']) + verify(data) + except Exception: + rollback(state, data) + raise + data['stage'] = 'applied' + save(state, data) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('command', choices=['plan', 'apply', 'verify', 'rollback']) + parser.add_argument('--state', required=True, type=Path) + parser.add_argument('--root', type=Path) + parser.add_argument('--bundles-root', type=Path) + parser.add_argument('--manifest-root', type=Path) + args = parser.parse_args() + if args.command == 'plan': + if args.root is None: + parser.error('plan requires --root') + data = plan(args.root, args.state, args.bundles_root, args.manifest_root) + else: + data = json.loads(args.state.read_text()) + if args.command == 'apply': + apply(args.state, data) + elif args.command == 'verify': + verify(data) + else: + rollback(args.state, data) + print(f'{data["stage"]}: {len(data["repos"])} repos, {len(data["links"])} symlinks, {len(data["configs"])} local configs') + if args.command == 'plan': + for row in data['repos']: + print(f' {row["old"]} -> {row["new"]}') + + +if __name__ == '__main__': + main() diff --git a/bin/version_drift.sh b/bin/version_drift.sh index a2698296..e31e31bf 100755 --- a/bin/version_drift.sh +++ b/bin/version_drift.sh @@ -24,6 +24,7 @@ set -u . "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/_pyauto_root.sh" ROOT="$PYAUTO_ROOT" +. "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/_repo_paths.sh" OWNER=PyAutoLabs VERPAT='[0-9]{4}\.[0-9]+\.[0-9]+\.[0-9]+' @@ -62,8 +63,9 @@ repos=() vers=() for s in "${STAMPS[@]}"; do repo="${s%%:*}"; path="${s#*:}" - if [ -f "$ROOT/$repo/$path" ]; then - v=$(grep -oE "$VERPAT" "$ROOT/$repo/$path" 2>/dev/null | head -1) + checkout="$(pyauto_repo_path "$repo" "$ROOT")" || exit $? + if [ -f "$checkout/$path" ]; then + v=$(grep -oE "$VERPAT" "$checkout/$path" 2>/dev/null | head -1) elif [ "$gh_ok" -eq 1 ]; then v=$(gh api "repos/$OWNER/$repo/contents/$path" -q '.content' 2>/dev/null \ | base64 -d 2>/dev/null | grep -oE "$VERPAT" | head -1) diff --git a/bin/worktree.sh b/bin/worktree.sh index 9d6fb965..eebbb2e0 100644 --- a/bin/worktree.sh +++ b/bin/worktree.sh @@ -25,6 +25,7 @@ set -o pipefail . "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/_pyauto_root.sh" +. "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/_repo_paths.sh" PYAUTO_MAIN="${PYAUTO_MAIN:-$PYAUTO_ROOT}" PYAUTO_WT_ROOT="${PYAUTO_WT_ROOT:-${PYAUTO_MAIN}-wt}" @@ -82,7 +83,8 @@ EOF # worktree_create and worktree_add_repo. _worktree_add_one() { local task="$1" repo="$2" - local repo_src="$PYAUTO_MAIN/$repo" + local repo_src + repo_src="$(pyauto_repo_path "$repo" "$PYAUTO_MAIN")" || return 1 local repo_dest="$PYAUTO_WT_ROOT/$task/$repo" local branch="${PYAUTO_WT_BRANCH:-feature/$task}" @@ -121,6 +123,8 @@ worktree_create() { local root root="$(worktree_root_path "$task")" + local repo_listing + repo_listing="$(pyauto_repo_list "$PYAUTO_MAIN")" || return 1 if [[ -e "$root" ]]; then echo "worktree_create: $root already exists. Refusing to overwrite." >&2 @@ -158,14 +162,30 @@ EOF fi done - # Symlink every other top-level entry in PyAutoLabs back to the main checkout - # so relative paths (admin_jammy/, autolens_workspace/, etc.) keep resolving. - local entry name + # Keep task bundles flat: every declared checkout gets its canonical name, + # even when the main workspace stores it inside a family directory. + local entry name family + local -A families=() + while IFS=$'\t' read -r name entry; do + [[ -n "$entry" ]] || continue + if [[ "$(dirname "$entry")" != "$PYAUTO_MAIN" ]]; then + family="$(basename "$(dirname "$entry")")" + families["$family"]=1 + fi + done <<< "$repo_listing" for entry in "$PYAUTO_MAIN"/*; do name="$(basename "$entry")" + [[ -n "${families[$name]:-}" ]] && continue + [[ -d "$entry/.git" || -f "$entry/.git" ]] && continue [[ -e "$root/$name" ]] && continue # already a real worktree ln -s "$entry" "$root/$name" done + while IFS=$'\t' read -r name entry; do + [[ -n "$name" && -n "$entry" ]] || continue + [[ -d "$entry" ]] || continue + [[ -e "$root/$name" ]] && continue + ln -s "$entry" "$root/$name" + done <<< "$repo_listing" worktree_activate_script "$task" > "$root/activate.sh" chmod +x "$root/activate.sh" @@ -211,7 +231,9 @@ worktree_add_repo() { if ! _worktree_add_one "$task" "$repo"; then # Best-effort: restore the symlink so the root is not left half-broken. - ln -s "$PYAUTO_MAIN/$repo" "$repo_dest" 2>/dev/null || true + local repo_src + repo_src="$(pyauto_repo_path "$repo" "$PYAUTO_MAIN")" || return 1 + ln -s "$repo_src" "$repo_dest" 2>/dev/null || true return 1 fi @@ -232,7 +254,7 @@ worktree_add_repo() { # squash-merged branch) returns 1 = "not stale" and the caller proceeds. worktree_claim_is_stale() { local task="$1" root="$2" - local active="$PYAUTO_MAIN/PyAutoMind/active.md" + local active="$(pyauto_repo_path PyAutoMind "$PYAUTO_MAIN")/active.md" [[ -f "$active" ]] || return 1 grep -Eq "^## ${task}([[:space:]]|\$)" "$active" || return 1 @@ -307,13 +329,15 @@ worktree_remove() { [[ -L "$entry" ]] && continue [[ -e "$entry/.git" ]] || continue # linked worktrees have .git as a FILE name="$(basename "$entry")" - git -C "$PYAUTO_MAIN/$name" worktree remove --force "$entry" || { + local repo_src + repo_src="$(pyauto_repo_path "$name" "$PYAUTO_MAIN")" || return 1 + git -C "$repo_src" worktree remove --force "$entry" || { echo "worktree_remove: failed to remove worktree for $name" >&2 return 1 } # Belt-and-braces: prune stale metadata in case `remove` left a "prunable" # entry behind (seen on some git versions). - git -C "$PYAUTO_MAIN/$name" worktree prune + git -C "$repo_src" worktree prune done # Unlink the remaining symlinks + activate.sh, then rmdir. @@ -336,7 +360,7 @@ worktree_remove() { # it cannot be found. Split out so a caller can tell "nothing is claimed" apart # from "I could not read the registry" — see worktree_check_conflict. worktree_registry_path() { - local active="$PYAUTO_MAIN/PyAutoMind/active.md" + local active="$(pyauto_repo_path PyAutoMind "$PYAUTO_MAIN")/active.md" # Back-compat: fall back to the pre-rename PyAutoPrompt/ path if present. [[ -f "$active" ]] || active="$PYAUTO_MAIN/PyAutoPrompt/active.md" [[ -f "$active" ]] || return 3 diff --git a/board/_board.py b/board/_board.py index 10c7a991..86a77d0c 100755 --- a/board/_board.py +++ b/board/_board.py @@ -64,6 +64,7 @@ # looked in the wrong tree. sys.path.insert(0, str(BRAIN_HOME / "agents")) import _pyauto_root # noqa: E402 +from _repo_paths import repo_path # noqa: E402 PYAUTO_ROOT, ROOT_REASON = _pyauto_root.workspace_root_reason() GH = os.environ.get("BOARD_GH", "gh") @@ -341,7 +342,7 @@ def _local_published_json(repo, name): reporting nothing. """ for rel in (Path("board") / name, Path("docs") / name, Path(name)): - candidate = PYAUTO_ROOT / repo / rel + candidate = repo_path(PYAUTO_ROOT, repo) / rel try: if candidate.is_file(): return json.loads(candidate.read_text(encoding="utf-8")) @@ -522,7 +523,7 @@ def collect_versions(stamps, org, reference_repo, degraded): for s in stamps: repo, _, path = str(s).partition(":") v = None - local = PYAUTO_ROOT / repo / path + local = repo_path(PYAUTO_ROOT, repo) / path if local.is_file(): m = re.search(VERPAT, local.read_text(encoding="utf-8", errors="replace")) v = m.group(0) if m else None diff --git a/board/_publish.py b/board/_publish.py index d9cb49fc..fb81a6db 100755 --- a/board/_publish.py +++ b/board/_publish.py @@ -40,6 +40,9 @@ from datetime import datetime, timezone from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "agents")) +from _repo_paths import iter_checkouts # noqa: E402 + BRAIN_HOME = Path(__file__).resolve().parents[1] PYAUTO_ROOT = Path(os.environ.get("PYAUTO_ROOT", BRAIN_HOME.parent)) DEVBOX_FILE = Path(os.environ.get( @@ -98,7 +101,7 @@ def collect_worktrees(): rows = [] if not PYAUTO_ROOT.is_dir(): return rows - for repo in sorted(PYAUTO_ROOT.iterdir()): + for repo in sorted(iter_checkouts(PYAUTO_ROOT)): if not (repo / ".git").exists(): continue branch = _git_out(repo, "branch", "--show-current") or "?" diff --git a/docs/index.md b/docs/index.md index 354b1b57..68c7d4c2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -77,4 +77,5 @@ example agent_failure_modes codex_usage +workspace_layout ``` diff --git a/docs/workspace_layout.md b/docs/workspace_layout.md new file mode 100644 index 00000000..bfa8f782 --- /dev/null +++ b/docs/workspace_layout.md @@ -0,0 +1,42 @@ +# Repository locations + +`PyAutoMind/repos.yaml` declares each repository's identity and optional canonical +`path`. Science checkouts may live in family folders; organs remain at the workspace +root. CI and task bundles may still place the same checkouts side by side. + +Python callers use `agents/_repo_paths.py`: `repo_path(root, name)` locates a +repository in the supplied context, `required=True` additionally requires a Git +checkout, and `iter_checkouts(root)` enumerates flat and one-level family checkouts. +Discovery stops at repository boundaries. Multiple distinct checkouts with the same +identity are an error. Missing optional paths remain visible to coverage checks. +Shell callers source `bin/_repo_paths.sh` and use `pyauto_repo_path` or +`pyauto_repo_list`; always check their exit status before interpreting absence. + +## Local migration + +Make and inspect a journal before changing canonical directory placement: + +```bash +python3 PyAutoBrain/bin/regroup_workspace.py plan --root "$PWD" \ + --bundles-root "${PWD}-wt" --state PyAutoMind/tmp/regroup.json +python3 PyAutoBrain/bin/regroup_workspace.py apply --state PyAutoMind/tmp/regroup.json +source activate.sh +python3 PyAutoBrain/bin/regroup_workspace.py verify --state PyAutoMind/tmp/regroup.json +``` + +The command renames existing directories without copying or cleaning their contents, +repairs registered Git worktrees and dependency links, and updates local IDE paths. +It preserves dirty files and ignored data, validates directory identity and Git state, +and records original link/configuration values. A source changed since planning or +an occupied destination stops the operation. A failed application rolls back. + +To reverse an applied move before making further changes: + +```bash +python3 PyAutoBrain/bin/regroup_workspace.py rollback --state PyAutoMind/tmp/regroup.json +``` + +Keep the journal outside the directories being moved. After successful validation, +retain it as the local migration receipt. Existing shells retain their old environment; +source the generated root `activate.sh` before further Python work. Task bundles keep +flat repository names and their own activation files. diff --git a/tests/test_hygiene_grouped.py b/tests/test_hygiene_grouped.py new file mode 100644 index 00000000..82aebdbe --- /dev/null +++ b/tests/test_hygiene_grouped.py @@ -0,0 +1,22 @@ +"""Hygiene workspace scanners include repositories one family level down.""" + +import runpy +from pathlib import Path + +import pytest + + +HYG = Path(__file__).resolve().parents[1] / "agents" / "conductors" / "hygiene" + + +@pytest.mark.parametrize("module", [ + "_hygiene_docstrings.py", "_hygiene_escapes.py", "_hygiene_refs.py", +]) +def test_grouped_repository_discovery(tmp_path, module): + repo = tmp_path / "science" / "demo_workspace" + (repo / ".git").mkdir(parents=True) + (repo / "scripts").mkdir() + (repo / "scripts" / "example.py").write_text("pass\n") + functions = runpy.run_path(str(HYG / module)) + assert functions["repository_paths"](tmp_path) == [repo] + assert "1 repo" in functions["row_for"](tmp_path)["summary"] diff --git a/tests/test_regroup_workspace.py b/tests/test_regroup_workspace.py new file mode 100644 index 00000000..6c70390e --- /dev/null +++ b/tests/test_regroup_workspace.py @@ -0,0 +1,102 @@ +"""Exercise real Git administration and reversible data/link preservation.""" +import importlib.util +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'agents')) +spec = importlib.util.spec_from_file_location('regroup_under_test', ROOT / 'bin/regroup_workspace.py') +migration = importlib.util.module_from_spec(spec) +spec.loader.exec_module(migration) + + +def git(path, *args): + return subprocess.check_output(['git', '-C', str(path), *args], text=True).strip() + + +def fixture(tmp_path): + root = tmp_path / 'workspace' + root.mkdir() + (root / '.pyauto-root').touch() + (root / 'PyAutoMind').mkdir() + (root / 'PyAutoMind/repos.yaml').write_text('repos:\n Demo:\n path: science/Demo\n') + repo = root / 'Demo' + repo.mkdir() + git(repo, 'init', '-q') + git(repo, 'config', 'user.email', 'test@example.org') + git(repo, 'config', 'user.name', 'Test') + (repo / '.gitignore').write_text('output/\n') + git(repo, 'add', '.gitignore') + git(repo, 'commit', '-qm', 'initial') + (repo / 'output').mkdir() + (repo / 'output/result.bin').write_bytes(b'irreplaceable result') + (repo / 'untracked.txt').write_text('user work') + bundles = tmp_path / 'bundles' + task = bundles / 'task' + task.mkdir(parents=True) + git(repo, 'worktree', 'add', '-qb', 'task', str(task / 'Demo')) + dependency = bundles / 'other' + dependency.mkdir() + (dependency / 'Demo').symlink_to(repo, target_is_directory=True) + (root / '.idea').mkdir() + (root / '.idea/vcs.xml').write_text('') + return root, repo, bundles, task + + +def test_apply_and_rollback_preserve_dirty_data_and_linked_worktree(tmp_path): + root, repo, bundles, task = fixture(tmp_path) + journal = tmp_path / 'journal.json' + data = migration.plan(root, journal, bundles) + before = migration.snapshot(repo) + migration.apply(journal, data) + new = root / 'science/Demo' + assert not repo.exists() + assert (new / 'output/result.bin').read_bytes() == b'irreplaceable result' + assert (new / 'untracked.txt').read_text() == 'user work' + assert migration.snapshot(new) == before + assert git(task / 'Demo', 'branch', '--show-current') == 'task' + assert (bundles / 'other/Demo').resolve() == new + assert 'science/Demo' in (root / '.idea/vcs.xml').read_text() + migration.rollback(journal, data) + assert migration.snapshot(repo) == before + assert not new.exists() + assert (bundles / 'other/Demo').resolve() == repo + assert git(task / 'Demo', 'branch', '--show-current') == 'task' + assert 'science/Demo' not in (root / '.idea/vcs.xml').read_text() + + +def test_stale_plan_cannot_overwrite_new_user_work(tmp_path): + import pytest + root, repo, bundles, _ = fixture(tmp_path) + journal = tmp_path / 'journal.json' + data = migration.plan(root, journal, bundles) + (repo / 'new-work.txt').write_text('arrived after plan') + with pytest.raises(ValueError, match='source changed'): + migration.apply(journal, data) + assert repo.exists() + assert not (root / 'science/Demo').exists() + + +def test_destination_family_cannot_redirect_move(tmp_path): + import pytest + root, repo, bundles, _ = fixture(tmp_path) + outside = tmp_path / 'outside' + outside.mkdir() + journal = tmp_path / 'journal.json' + data = migration.plan(root, journal, bundles) + (root / 'science').symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError, match='family must be a real directory'): + migration.apply(journal, data) + assert repo.exists() + assert not (outside / 'Demo').exists() + + +def test_journal_does_not_follow_preexisting_temp_link(tmp_path): + journal = tmp_path / 'journal.json' + important = tmp_path / 'important.txt' + important.write_text('KEEP') + journal.with_suffix('.json.tmp').symlink_to(important) + migration.save(journal, {'stage': 'planned'}) + assert important.read_text() == 'KEEP' + assert 'planned' in journal.read_text() diff --git a/tests/test_repo_paths.py b/tests/test_repo_paths.py new file mode 100644 index 00000000..53179b45 --- /dev/null +++ b/tests/test_repo_paths.py @@ -0,0 +1,111 @@ +"""Repository identity survives grouped canonical trees and flat task/CI trees.""" +import importlib.util +from pathlib import Path +import subprocess + +import pytest + +MODULE = Path(__file__).resolve().parents[1] / 'agents' / '_repo_paths.py' +spec = importlib.util.spec_from_file_location('repo_paths_under_test', MODULE) +paths = importlib.util.module_from_spec(spec) +spec.loader.exec_module(paths) + + +def manifest(root, body=' Demo:\n path: science/Demo\n'): + (root / 'PyAutoMind').mkdir(exist_ok=True) + (root / 'PyAutoMind' / 'repos.yaml').write_text('repos:\n' + body) + + +def checkout(path): + (path / '.git').mkdir(parents=True) + return path + + +@pytest.mark.parametrize('layout', ['flat', 'grouped']) +def test_context_owns_checkout(tmp_path, layout): + manifest(tmp_path) + actual = checkout(tmp_path / ('science/Demo' if layout == 'grouped' else 'Demo')) + assert paths.repo_path(tmp_path, 'Demo', required=True) == actual + assert actual in paths.iter_checkouts(tmp_path) + + +def test_flat_bundle_symlink_uses_its_own_context(tmp_path): + canonical = tmp_path / 'canonical' + canonical.mkdir() + manifest(canonical) + target = checkout(canonical / 'science/Demo') + bundle = tmp_path / 'bundle' + bundle.mkdir() + (bundle / 'PyAutoMind').symlink_to(canonical / 'PyAutoMind', target_is_directory=True) + (bundle / 'Demo').symlink_to(target, target_is_directory=True) + assert paths.repo_path(bundle, 'Demo', required=True) == bundle / 'Demo' + assert paths.repo_paths(bundle)['Demo'] == bundle / 'Demo' + + +def test_missing_repo_stays_in_coverage(tmp_path): + manifest(tmp_path) + assert paths.repo_paths(tmp_path) == {'Demo': tmp_path / 'science/Demo'} + with pytest.raises(FileNotFoundError, match='Demo'): + paths.repo_path(tmp_path, 'Demo', required=True) + + +def test_plain_directory_does_not_prove_a_checkout(tmp_path): + (tmp_path / 'Demo').mkdir() + assert paths.iter_checkouts(tmp_path) == [] + with pytest.raises(FileNotFoundError): + paths.repo_path(tmp_path, 'Demo', required=True) + + +def test_ambiguity_is_not_silently_resolved(tmp_path): + checkout(tmp_path / 'Demo') + checkout(tmp_path / 'science/Demo') + with pytest.raises(ValueError, match='ambiguous'): + paths.repo_path(tmp_path, 'Demo') + with pytest.raises(ValueError, match='ambiguous'): + paths.iter_checkouts(tmp_path) + + +def test_alias_to_same_checkout_is_unambiguous(tmp_path): + target = checkout(tmp_path / 'science/Demo') + (tmp_path / 'Demo').symlink_to(target, target_is_directory=True) + assert paths.repo_path(tmp_path, 'Demo') == tmp_path / 'Demo' + assert len(paths.iter_checkouts(tmp_path)) == 1 + + +def test_enumeration_stops_at_git_boundary(tmp_path): + top = checkout(tmp_path / 'science/Demo') + checkout(top / 'dataset/HiddenClone') + assert paths.iter_checkouts(tmp_path) == [top] + + +@pytest.mark.parametrize('value', ['/outside/Demo', '../Demo', 'science/../Demo', 'science/Wrong', 'a/b/Demo']) +def test_rejects_unsafe_placement(tmp_path, value): + manifest(tmp_path, f' Demo:\n path: {value}\n') + with pytest.raises(ValueError): + paths.repo_path(tmp_path, 'Demo') + + +def test_shell_and_python_agree(tmp_path): + manifest(tmp_path) + actual = checkout(tmp_path / 'science/Demo') + shell = MODULE.parents[1] / 'bin/_repo_paths.sh' + result = subprocess.run(['bash', '-c', 'source "$1"; pyauto_repo_path Demo "$2"', 'test', str(shell), str(tmp_path)], text=True, capture_output=True, check=True) + assert result.stdout.strip() == str(actual) + + +def test_declared_family_cannot_escape_via_symlink(tmp_path): + root = tmp_path / 'root' + root.mkdir() + manifest(root) + external = tmp_path / 'outside' + checkout(external / 'Demo') + (root / 'science').symlink_to(external, target_is_directory=True) + with pytest.raises(ValueError, match='family must not be a symlink'): + paths.repo_path(root, 'Demo', required=True) + + +def test_pythonpath_follows_manifest_package_order(tmp_path): + manifest(tmp_path, ' Demo:\n path: science/Demo\n package: demo\n Other:\n package: other\n') + first = checkout(tmp_path / 'science/Demo') + second = checkout(tmp_path / 'Other') + assert paths.package_paths(tmp_path) == [first, second] diff --git a/tests/test_worktree_grouped.py b/tests/test_worktree_grouped.py new file mode 100644 index 00000000..4dde2fc4 --- /dev/null +++ b/tests/test_worktree_grouped.py @@ -0,0 +1,60 @@ +"""Task bundles keep flat repo names when canonical checkouts are grouped.""" + +import os +import subprocess +from pathlib import Path + + +WORKTREE_SH = Path(__file__).resolve().parents[1] / "bin/worktree.sh" + + +def _git(*args): + subprocess.run(["git", *map(str, args)], check=True, capture_output=True) + + +def test_create_and_remove_from_grouped_checkout(tmp_path): + main = tmp_path / "main" + mind = main / "PyAutoMind" + mind.mkdir(parents=True) + (mind / "repos.yaml").write_text("repos:\n Demo:\n path: science/Demo\n") + demo = main / "science" / "Demo" + demo.mkdir(parents=True) + remote = tmp_path / "remote.git" + _git("init", "--bare", remote) + _git("init", "-b", "main", demo) + _git("-C", demo, "config", "user.email", "test@example.com") + _git("-C", demo, "config", "user.name", "Test") + (demo / "README.md").write_text("demo\n") + _git("-C", demo, "add", "README.md") + _git("-C", demo, "commit", "-m", "initial") + _git("-C", demo, "remote", "add", "origin", remote) + _git("-C", demo, "push", "-u", "origin", "main") + + bundle = tmp_path / "bundles" / "task" + env = os.environ | { + "PYAUTO_MAIN": str(main), + "PYAUTO_WT_ROOT": str(bundle.parent), + "PYAUTO_WT_FORCE": "1", + } + result = subprocess.run( + ["bash", "-c", f'source "{WORKTREE_SH}"; worktree_create task Demo'], + env=env, capture_output=True, text=True, + ) + assert result.returncode == 0, result.stderr + assert (bundle / "Demo" / ".git").is_file() + assert (bundle / "PyAutoMind").is_symlink() + assert not (bundle / "science").exists() + lookup = subprocess.run( + ["python3", str(WORKTREE_SH.parents[1] / "agents" / "_repo_paths.py"), + "path", "Demo", "--root", str(bundle), "--required"], + capture_output=True, text=True, + ) + assert lookup.returncode == 0, lookup.stderr + assert lookup.stdout.strip() == str(bundle / "Demo") + + result = subprocess.run( + ["bash", "-c", f'source "{WORKTREE_SH}"; worktree_remove task'], + env=env, capture_output=True, text=True, + ) + assert result.returncode == 0, result.stderr + assert not bundle.exists()